body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have this messy helper method:</p>
<pre><code>def gesture(klass, item, text, desc)
element_class = klass.to_s + " gesture"
content_tag :li do
if klass == :sell
link_to new_reply_path(item_id: item.id), title: desc, data: {qtip: desc}, class: element_class do
content_tag(:div, nil, class: element_class) +
content_tag(:span, text, class: 'gesture-text')
end
elsif klass == :alternative
link_to new_reply_path(item_id: item.id, alternative: true), title: desc, data: {qtip: desc}, class: element_class do
content_tag(:div, nil, class: element_class) +
content_tag(:span, text, class: 'gesture-text')
end
elsif klass == :join
link_to new_item_affiliation_path(item), title: desc, data: {qtip: desc}, class: element_class do
content_tag(:div, nil, class: element_class) +
content_tag(:span, text, class: 'gesture-text')
end
end
end
end
</code></pre>
<p>As you can see, it has a lot of repetition, any idea on how I can refactor it?</p>
|
[] |
[
{
"body": "<p>I'd write:</p>\n\n<pre><code>def gesture(klass, item, text, desc)\n element_class = [klass.to_s, \"gesture\"]\n url = case klass\n when :sell\n new_reply_path(item_id: item.id)\n when :alternative\n new_reply_path(item_id: item.id, alternative: true)\n when :join\n new_item_affiliation_path(item)\n else\n fail(\"Unsupported klass: #{klass}\")\n end\n\n content_tag(:li) do\n link_to(url, title: desc, data: {qtip: desc}, class: element_class) do\n content_tag(:div, nil, class: element_class) +\n content_tag(:span, text, class: 'gesture-text')\n end \n end \nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T13:38:13.987",
"Id": "23267",
"ParentId": "23257",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23267",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T10:45:33.183",
"Id": "23257",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Rails helper method refactor"
}
|
23257
|
<p>I came up with <a href="http://ideone.com/a8hcbp" rel="nofollow noreferrer">this code</a> whilst answering <a href="https://stackoverflow.com/q/15124432/1084416">this question</a>.</p>
<p>Is there a simpler way of doing this using standard library?</p>
<p>I want to iterate over every object and do something with every other object. </p>
<p>For example, 4 values <code>1</code>, <code>2</code>, <code>3</code>, <code>4</code> would pair like:</p>
<pre><code>(1, 2), (1, 3), (1, 4)
(2, 3), (2, 4)
(3, 4)
</code></pre>
<p>Each value combines with every other value. None combine with themselves, and symmetric pairings are considered the same.</p>
<p>This might be useful in a collision system where you want to check every solid with every other.</p>
<pre><code>template<typename Iter, typename Func>
void pair_wise(Iter it, Iter last, Func func) {
while(it != last) {
Iter other = it;
++other;
while(other != last) {
func(*it, *other);
++other;
}
++it;
}
}
</code></pre>
<p>Usage:</p>
<pre><code>#include <iostream>
#include <vector>
int main() {
std::vector<int> values = {1, 2, 3, 4};
pair_wise(values.begin(), values.end(),
[](int& lhs, int& rhs) {
std::cout << "(" << lhs << ", " << rhs << ")\n";
});
}
</code></pre>
<p>Output:</p>
<pre><code>(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
</code></pre>
|
[] |
[
{
"body": "<p>It would be possible to write as <code>for_each</code> call to a functor writing <code>for_each</code> again, but I don't think it would actually be shorter.</p>\n\n<p>I don't think <code>pair_wise</code> is a good name. There are two many things that it could mean. I'd suggest something with <code>combinations</code> as it calls the function for all 2-combinations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T12:30:01.997",
"Id": "35869",
"Score": "0",
"body": "Maybe `pairwise_combinations`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T12:30:48.890",
"Id": "35870",
"Score": "1",
"body": "Or `combine_pairwise`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T12:31:32.003",
"Id": "35871",
"Score": "0",
"body": "@PeterWood: Yes, those are decent names."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T12:25:07.503",
"Id": "23265",
"ParentId": "23262",
"Score": "5"
}
},
{
"body": "<p>You could do this:</p>\n\n<pre><code>template<typename Iter, typename Func>\nvoid combine_pairwise(Iter first, Iter last, Func func)\n{\n for(; first != last; ++first)\n std::for_each(std::next(first), last, std::bind(func, *first, std::placeholders::_1));\n}\n</code></pre>\n\n<p>but if I was doing this in real code I would opt not to. The above is basically just being complicated for the hell of it. I would write the following in <em>real</em> code:</p>\n\n<pre><code>template<typename Iter, typename Func>\nvoid combine_pairwise(Iter first, Iter last, Func func)\n{\n for(; first != last; ++first)\n for(Iter next = std::next(first); next != last; ++next)\n func(*first, *next);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T09:30:50.237",
"Id": "35932",
"Score": "0",
"body": "I think the two `for` loops are clearer than my two `while` loops. Having the `next` makes it clearer that the inner loop is over an [increasingly smaller](http://english.stackexchange.com/q/68406) sub-list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T21:16:13.887",
"Id": "36007",
"Score": "0",
"body": "@PeterWood I don't know why, but even seasoned C++ devs love to write `iter i = begin; while(i != end){ /*...*/ ++i; }` (or the equivalent) instead of using a for loop. I find it constantly in other people's code; And it's *much* harder to quickly understand what's going on (it's longer too)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T23:02:41.820",
"Id": "36019",
"Score": "0",
"body": "Normally I would write a `for` loop, but as the iterators were passed in and no initialisation was necessary I just jumped straight to the condition: `while`. It doesn't feel quite right to have empty initialisation in the `for`, but having thought about it I prefer it to `while`, now."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T21:39:29.560",
"Id": "23287",
"ParentId": "23262",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23287",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T11:50:11.763",
"Id": "23262",
"Score": "10",
"Tags": [
"c++",
"algorithm",
"library"
],
"Title": "Using standard library to simplify pairwise iteration of container values"
}
|
23262
|
<p>I put the full code at the rear of this post. </p>
<p>I've recently answered a question, and the detail explanation is posted in </p>
<ul>
<li><a href="https://stackoverflow.com/questions/15051660/physical-disk-size-not-correct-ioctldiskgetdrivegeometry">Physical disk size not correct (IoCtlDiskGetDriveGeometry)</a> </li>
</ul>
<p>And en passant answer another one </p>
<ul>
<li><a href="https://stackoverflow.com/questions/13192616/deviceiocontrol-does-not-set-output-buffer/15110951#15110951">DeviceIoControl does not set output buffer</a> </li>
</ul>
<p>I'd like to know that if any one think there's any problem or improvement of the code. </p>
<hr>
<p>code: </p>
<pre><code>using System.Runtime.InteropServices;
using System.ComponentModel;
using System;
namespace DiskManagement {
using Microsoft.Win32.SafeHandles;
using LPSECURITY_ATTRIBUTES=IntPtr;
using LPOVERLAPPED=IntPtr;
using LPVOID=IntPtr;
using HANDLE=IntPtr;
using LARGE_INTEGER=Int64;
using DWORD=UInt32;
using LPCTSTR=String;
public static partial class IoCtl /* methods */ {
[DllImport("kernel32.dll", SetLastError=true)]
static extern SafeFileHandle CreateFile(
LPCTSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
[DllImport("kernel32.dll", SetLastError=true)]
static extern DWORD DeviceIoControl(
SafeFileHandle hDevice,
DWORD dwIoControlCode,
LPVOID lpInBuffer,
DWORD nInBufferSize,
LPVOID lpOutBuffer,
int nOutBufferSize,
ref DWORD lpBytesReturned,
LPOVERLAPPED lpOverlapped
);
static DWORD CTL_CODE(DWORD DeviceType, DWORD Function, DWORD Method, DWORD Access) {
return (((DeviceType)<<16)|((Access)<<14)|((Function)<<2)|(Method));
}
public static void Execute<T>(
ref T x,
DWORD dwIoControlCode,
LPCTSTR lpFileName,
DWORD dwDesiredAccess=GENERIC_READ,
DWORD dwShareMode=FILE_SHARE_WRITE|FILE_SHARE_READ,
LPSECURITY_ATTRIBUTES lpSecurityAttributes=default(LPSECURITY_ATTRIBUTES),
DWORD dwCreationDisposition=OPEN_EXISTING,
DWORD dwFlagsAndAttributes=0,
HANDLE hTemplateFile=default(IntPtr)
) {
using(
var hDevice=
CreateFile(
lpFileName,
dwDesiredAccess, dwShareMode,
lpSecurityAttributes,
dwCreationDisposition, dwFlagsAndAttributes,
hTemplateFile
)
) {
if(null==hDevice||hDevice.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());
var nOutBufferSize=Marshal.SizeOf(typeof(T));
var lpOutBuffer=Marshal.AllocHGlobal(nOutBufferSize);
var lpBytesReturned=default(DWORD);
var NULL=IntPtr.Zero;
var result=
DeviceIoControl(
hDevice, dwIoControlCode,
NULL, 0,
lpOutBuffer, nOutBufferSize,
ref lpBytesReturned, NULL
);
if(0==result)
throw new Win32Exception(Marshal.GetLastWin32Error());
x=(T)Marshal.PtrToStructure(lpOutBuffer, typeof(T));
Marshal.FreeHGlobal(lpOutBuffer);
}
}
}
public enum MEDIA_TYPE: int {
Unknown=0,
F5_1Pt2_512=1,
F3_1Pt44_512=2,
F3_2Pt88_512=3,
F3_20Pt8_512=4,
F3_720_512=5,
F5_360_512=6,
F5_320_512=7,
F5_320_1024=8,
F5_180_512=9,
F5_160_512=10,
RemovableMedia=11,
FixedMedia=12,
F3_120M_512=13,
F3_640_512=14,
F5_640_512=15,
F5_720_512=16,
F3_1Pt2_512=17,
F3_1Pt23_1024=18,
F5_1Pt23_1024=19,
F3_128Mb_512=20,
F3_230Mb_512=21,
F8_256_128=22,
F3_200Mb_512=23,
F3_240M_512=24,
F3_32M_512=25
}
partial class DiskGeometry /* structures */ {
[StructLayout(LayoutKind.Sequential)]
struct DISK_GEOMETRY {
internal LARGE_INTEGER Cylinders;
internal MEDIA_TYPE MediaType;
internal DWORD TracksPerCylinder;
internal DWORD SectorsPerTrack;
internal DWORD BytesPerSector;
}
[StructLayout(LayoutKind.Sequential)]
struct DISK_GEOMETRY_EX {
internal DISK_GEOMETRY Geometry;
internal LARGE_INTEGER DiskSize;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)]
internal byte[] Data;
}
}
partial class DiskGeometry /* properties and fields */ {
public MEDIA_TYPE MediaType {
get {
return m_Geometry.MediaType;
}
}
public String MediaTypeName {
get {
return Enum.GetName(typeof(MEDIA_TYPE), this.MediaType);
}
}
public override long Cylinder {
get {
return m_Geometry.Cylinders;
}
}
public override uint Head {
get {
return m_Geometry.TracksPerCylinder;
}
}
public override uint Sector {
get {
return m_Geometry.SectorsPerTrack;
}
}
public DWORD BytesPerSector {
get {
return m_Geometry.BytesPerSector;
}
}
public long DiskSize {
get {
return m_DiskSize;
}
}
public long MaximumLinearAddress {
get {
return m_MaximumLinearAddress;
}
}
public CubicAddress MaximumCubicAddress {
get {
return m_MaximumCubicAddress;
}
}
public DWORD BytesPerCylinder {
get {
return m_BytesPerCylinder;
}
}
CubicAddress m_MaximumCubicAddress;
long m_MaximumLinearAddress;
DWORD m_BytesPerCylinder;
LARGE_INTEGER m_DiskSize;
DISK_GEOMETRY m_Geometry;
}
}
namespace DiskManagement {
using Microsoft.Win32.SafeHandles;
using LPSECURITY_ATTRIBUTES=IntPtr;
using LPOVERLAPPED=IntPtr;
using LPVOID=IntPtr;
using HANDLE=IntPtr;
using LARGE_INTEGER=Int64;
using DWORD=UInt32;
using LPCTSTR=String;
partial class IoCtl /* constants */ {
public const DWORD
DISK_BASE=0x00000007,
METHOD_BUFFERED=0,
FILE_ANY_ACCESS=0;
public const DWORD
GENERIC_READ=0x80000000,
FILE_SHARE_WRITE=0x2,
FILE_SHARE_READ=0x1,
OPEN_EXISTING=0x3;
public static readonly DWORD DISK_GET_DRIVE_GEOMETRY_EX=
IoCtl.CTL_CODE(DISK_BASE, 0x0028, METHOD_BUFFERED, FILE_ANY_ACCESS);
public static readonly DWORD DISK_GET_DRIVE_GEOMETRY=
IoCtl.CTL_CODE(DISK_BASE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS);
}
public partial class CubicAddress {
public static CubicAddress Transform(long linearAddress, CubicAddress geometry) {
var cubicAddress=new CubicAddress();
var sectorsPerCylinder=geometry.Sector*geometry.Head;
long remainder;
cubicAddress.Cylinder=Math.DivRem(linearAddress, sectorsPerCylinder, out remainder);
cubicAddress.Head=(uint)Math.DivRem(remainder, geometry.Sector, out remainder);
cubicAddress.Sector=1+(uint)remainder;
return cubicAddress;
}
public virtual long Cylinder {
get;
set;
}
public virtual uint Head {
get;
set;
}
public virtual uint Sector {
get;
set;
}
}
public partial class DiskGeometry: CubicAddress {
internal static void ThrowIfDiskSizeOutOfIntegrity(long remainder) {
if(0!=remainder) {
var message="DiskSize is not an integral multiple of a sector size";
throw new ArithmeticException(message);
}
}
public static DiskGeometry FromDevice(String deviceName) {
return new DiskGeometry(deviceName);
}
DiskGeometry(String deviceName) {
var x=new DISK_GEOMETRY_EX();
IoCtl.Execute(ref x, IoCtl.DISK_GET_DRIVE_GEOMETRY_EX, deviceName);
m_DiskSize=x.DiskSize;
m_Geometry=x.Geometry;
long remainder;
m_MaximumLinearAddress=Math.DivRem(DiskSize, BytesPerSector, out remainder)-1;
ThrowIfDiskSizeOutOfIntegrity(remainder);
m_BytesPerCylinder=BytesPerSector*Sector*Head;
m_MaximumCubicAddress=DiskGeometry.Transform(m_MaximumLinearAddress, this);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T18:17:55.887",
"Id": "35883",
"Score": "2",
"body": "I like what you have. It is much cleaner than what I did. I'm usually not a fan of recreating C++ names match in C# (since they are different languages) but it makes sense in this application."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T20:26:16.310",
"Id": "35895",
"Score": "0",
"body": "Thank you. If there is anything can be improved or corrected, post an answer for me would be wonderful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T20:44:01.877",
"Id": "35897",
"Score": "1",
"body": "Have you run StyleCop on it and listened to its feedback? My only input is on the import statements - they should go inside of the namespace. You can then ask Visual Studio to sort and remove unused imports."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T20:52:29.680",
"Id": "35898",
"Score": "3",
"body": "Also, you use a C++ -ism: \"Yoda conditions\" that are not necessary in C#, you used `var` instead of `string` and I think that built-in types should not be \"vared\". You also left out some braces around a one-liner if, which I prefer not to do. Finally there are some minor spacing issues that Visual Studio can fix for you if you delete the very last } in the class and then type it again. Your code is basically good and there exist tools that cam help you polish it better than humans can: Stylecop FxCop. The trick is using your judgement - when some StyleCop error is important and when it is not."
}
] |
[
{
"body": "<p>As most people in the comments suggest, it is missing a few conventions that are pretty generally accepting across all C# developers. This will mostly be looking at stylistic points as there isn't really much in wrong with the implementation.</p>\n\n<p><strong>General notes</strong></p>\n\n<p>Most of the bracket/whitespace-related points are enforced by Visual Studio when you close a code block (<code>{</code>).</p>\n\n<ul>\n<li>Types should be in <code>PascalCase</code></li>\n<li>Public member names should be in <code>PascalCase</code></li>\n<li>Hungarian notation (<code>dwDesiredAccess</code>) is discourages except for when naming controls in WebForms and WinForms. Go with <code>camelCase</code>.</li>\n<li><p>Your spacing is a bit off, all curly braces should be on separate lines. Methods generally should look like this:</p>\n\n<pre><code>public void Method(Type param)\n{\n // Implementation\n}\n</code></pre></li>\n<li><p>Generally you should have 1 (partial) class per file, this may not be applicable but wanted to mention.</p></li>\n<li>Placing a space between most symbols is encourages.</li>\n<li><p>Order your type's members like this:</p>\n\n<ol>\n<li>Variables (pref. const/static first)</li>\n<li>Constructors/Properties (either way)</li>\n<li>Methods</li>\n</ol></li>\n<li><p>Normally <code>ALL_CAPS</code>-style naming is not used in C#, sometimes it is for constants but generally not.</p></li>\n</ul>\n\n<p><strong>Line-by-line</strong></p>\n\n<p>Normally comments are made on the line above class definitions, you may be better putting this into an IoCtrl.Methods.cs file or something if you really want to separate the different sections of the file. I usually stay away from <code>partial</code> unless the file gets ridiculously long and can't be factored out.</p>\n\n<pre><code>// methods\npublic static partial class IoCtl {\n</code></pre>\n\n<p>While I'm not particularly a fan of it, your 'defines' at the top make sense given their application and <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx\" rel=\"nofollow\">the documentation</a> of the kernal32.dll assembly.</p>\n\n<pre><code>using LPSECURITY_ATTRIBUTES = IntPtr;\nusing LPOVERLAPPED = IntPtr;\nusing LPVOID = IntPtr;\nusing HANDLE = IntPtr;\n\nusing LARGE_INTEGER = Int64;\nusing DWORD = UInt32;\nusing LPCTSTR = String;\n</code></pre>\n\n<p>Structure your braces like this:</p>\n\n<pre><code>public static void Execute<T>(\n ref T x,\n DWORD dwIoControlCode,\n LPCTSTR lpFileName,\n DWORD dwDesiredAccess = GENERIC_READ,\n DWORD dwShareMode = FILE_SHARE_WRITE | FILE_SHARE_READ,\n LPSECURITY_ATTRIBUTES lpSecurityAttributes = default(LPSECURITY_ATTRIBUTES),\n DWORD dwCreationDisposition = OPEN_EXISTING,\n DWORD dwFlagsAndAttributes = 0,\n HANDLE hTemplateFile = default(IntPtr)) \n{\n</code></pre>\n\n<p>Try not to span too many lines when calling functions</p>\n\n<pre><code> using (var hDevice = CreateFile(lpFileName, dwDesiredAccess, dwShareMode,\n lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes,\n hTemplateFile)) \n {\n\n if (null == hDevice || hDevice.IsInvalid)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n\n var nOutBufferSize = Marshal.SizeOf(typeof(T));\n var lpOutBuffer = Marshal.AllocHGlobal(nOutBufferSize);\n var lpBytesReturned = default(DWORD);\n</code></pre>\n\n<p>Using <code>IntPtr.Zero</code> rather than an alias (<code>NULL</code>) makes it easier to understand what the value is later on.</p>\n\n<pre><code> var result = DeviceIoControl(hDevice, dwIoControlCode, IntPtr.Zero, 0,\n lpOutBuffer, nOutBufferSize, ref lpBytesReturned, IntPtr.Zero);\n</code></pre>\n\n<p>Always prefer <code>var == <number></code> over <code><number> == var</code>, this type of condition is affectionately known as a 'yoda condition'.</p>\n\n<pre><code> if (result == 0)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n\n x = (T)Marshal.PtrToStructure(lpOutBuffer, typeof(T));\n Marshal.FreeHGlobal(lpOutBuffer);\n }\n}\n</code></pre>\n\n<p>Use pascal case for all types.</p>\n\n<pre><code>public enum MediaType : int\n{\n Unknown = 0,\n F5_1Pt2_512 = 1,\n F3_1Pt44_512 = 2,\n F3_2Pt88_512 = 3,\n F3_20Pt8_512 = 4,\n F3_720_512 = 5,\n F5_360_512 = 6,\n F5_320_512 = 7,\n F5_320_1024 = 8,\n F5_180_512 = 9,\n F5_160_512 = 10,\n RemovableMedia = 11,\n FixedMedia = 12,\n F3_120M_512 = 13,\n F3_640_512 = 14,\n F5_640_512 = 15,\n F5_720_512 = 16,\n F3_1Pt2_512 = 17,\n F3_1Pt23_1024 = 18,\n F5_1Pt23_1024 = 19,\n F3_128Mb_512 = 20,\n F3_230Mb_512 = 21,\n F8_256_128 = 22,\n F3_200Mb_512 = 23,\n F3_240M_512 = 24,\n F3_32M_512 = 25\n}\n</code></pre>\n\n<p>Always specify access modifiers.</p>\n\n<pre><code>// Structures\ninternal partial class DiskGeometry\n{\n [StructLayout(LayoutKind.Sequential)]\n internal struct DISK_GEOMETRY \n {\n internal LARGE_INTEGER Cylinders;\n internal MEDIA_TYPE MediaType;\n internal DWORD TracksPerCylinder;\n internal DWORD SectorsPerTrack;\n internal DWORD BytesPerSector;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct DISK_GEOMETRY_EX \n {\n internal DISK_GEOMETRY Geometry;\n internal LARGE_INTEGER DiskSize;\n\n [MarshalAs(UnmanagedType.ByValArray, SizeConst=1)]\n internal byte[] Data;\n }\n}\n</code></pre>\n\n<p>There isn't really a standard on this but I prefer to keep simple getters on a single line. Also keep variables at the top of the file and use <code>pascalCase</code>;</p>\n\n<pre><code>// properties and fields\npartial class DiskGeometry \n{\n private CubicAddress maximumCubicAddress;\n private long maximumLinearAddress;\n private DWORD bytesPerCylinder;\n private LARGE_INTEGER diskSize;\n private DISK_GEOMETRY geometry;\n\n public MEDIA_TYPE MediaType\n {\n get { return geometry.MediaType; }\n }\n\n public String MediaTypeName\n {\n get { return Enum.GetName(typeof(MEDIA_TYPE), this.MediaType); }\n }\n\n public override long Cylinder\n {\n get { return geometry.Cylinders; }\n }\n\n public override uint Head\n {\n get { return geometry.TracksPerCylinder; }\n }\n\n public override uint Sector\n {\n get { return geometry.SectorsPerTrack; }\n }\n\n public DWORD BytesPerSector\n {\n get { return geometry.BytesPerSector; }\n }\n\n public long DiskSize\n {\n get { return diskSize; }\n }\n\n public long MaximumLinearAddress\n {\n get { return maximumLinearAddress; }\n }\n\n public CubicAddress MaximumCubicAddress\n {\n get { return maximumCubicAddress; }\n }\n\n public DWORD BytesPerCylinder\n {\n get { return bytesPerCylinder; }\n }\n}\n</code></pre>\n\n<p>Don't concatenate variable declarations, one line, one variable.</p>\n\n<pre><code>// constants\npartial class IoCtl\n{\n public const DWORD DISK_BASE = 0x00000007;\n public const DWORD METHOD_BUFFERED = 0;\n public const DWORD FILE_ANY_ACCESS = 0;\n\n public const DWORD GENERIC_READ = 0x80000000;\n public const DWORD FILE_SHARE_WRITE = 0x2;\n public const DWORD FILE_SHARE_READ = 0x1;\n public const DWORD OPEN_EXISTING = 0x3;\n\n public static readonly DWORD DISK_GET_DRIVE_GEOMETRY_EX =\n IoCtl.CTL_CODE(DISK_BASE, 0x0028, METHOD_BUFFERED, FILE_ANY_ACCESS);\n\n public static readonly DWORD DISK_GET_DRIVE_GEOMETRY =\n IoCtl.CTL_CODE(DISK_BASE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS);\n}\n</code></pre>\n\n<p>Put properties before methods (optional), use a single line for auto-properties.</p>\n\n<pre><code>public partial class CubicAddress\n{\n public virtual long Cylinder { get; set; }\n public virtual uint Head { get; set; }\n public virtual uint Sector { get; set; }\n\n public static CubicAddress Transform(long linearAddress, CubicAddress geometry) \n {\n var cubicAddress = new CubicAddress();\n var sectorsPerCylinder = geometry.Sector * geometry.Head;\n long remainder;\n cubicAddress.Cylinder = Math.DivRem(linearAddress, sectorsPerCylinder, out remainder);\n cubicAddress.Head = (uint)Math.DivRem(remainder, geometry.Sector, out remainder);\n cubicAddress.Sector = 1 + (uint)remainder;\n return cubicAddress;\n }\n}\n</code></pre>\n\n<p>Constructor(s) before methods.</p>\n\n<pre><code>public partial class DiskGeometry: CubicAddress \n{\n DiskGeometry(String deviceName)\n {\n var x = new DISK_GEOMETRY_EX();\n IoCtl.Execute(ref x, IoCtl.DISK_GET_DRIVE_GEOMETRY_EX, deviceName);\n diskSize = x.DiskSize;\n geometry = x.Geometry;\n\n long remainder;\n m_MaximumLinearAddress = Math.DivRem(DiskSize, BytesPerSector, out remainder) - 1;\n ThrowIfDiskSizeOutOfIntegrity(remainder);\n\n mytesPerCylinder = BytesPerSector * Sector * Head;\n maximumCubicAddress = DiskGeometry.Transform(maximumLinearAddress, this);\n }\n\n internal static void ThrowIfDiskSizeOutOfIntegrity(long remainder) \n {\n if (remainder != 0)\n {\n var message = \"DiskSize is not an integral multiple of a sector size\";\n throw new ArithmeticException(message);\n }\n }\n\n public static DiskGeometry FromDevice(String deviceName)\n {\n return new DiskGeometry(deviceName);\n }\n}\n</code></pre>\n\n<p>Phew... Big.</p>\n\n<p>I haven't changed the hungarian notations because I'm sure I would miss some and inconsistencies are no good in review :) I also didn't change the <code>ALL_CAPS</code> variables as I couldn't find where some were defined.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T09:43:54.697",
"Id": "23528",
"ParentId": "23264",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "23528",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T11:53:21.463",
"Id": "23264",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Expecting working sample of DeviceIoControl reviewed"
}
|
23264
|
<p>I had developed an application in which I hit several URLs and show data on mobile. But the problem is that it requires more time. If I check the same URL on Firebug tool I get a response in 2-3 seconds, but the same URL requires 8-15 seconds on mobile. In my Android application I am using HTTP get and post method as follows:</p>
<pre><code>public InputStream httpGetResponseStream(String url, String request) {
connectionUrl = url;
InputStream response = null;
try {
processGetRequest();
HttpResponse httpresponse = httpclient.execute(host, get);
response = httpresponse.getEntity().getContent();
} catch (Exception e) {
response = null;
}
return response;
}
public InputStream httpPostResponseStream(String url, String request) {
connectionUrl = url;
InputStream response = null;
try {
processPostRequest();
if (request != null) {
InputStreamEntity streamEntity = new InputStreamEntity(
new ByteArrayInputStream(request.getBytes()), request
.length());
post.setEntity(streamEntity);
}
HttpResponse httpresponse = httpclient.execute(host, post);
response = httpresponse.getEntity().getContent();
}catch (Exception e) {
response = null;
}
return response;
}
private void processGetRequest(){
uri = Uri.parse(connectionUrl);
String protocol = connectionUrl.substring(0, 5).toLowerCase();
if (protocol.startsWith("https")) {
securedConnection = true;
} else {
securedConnection = false;
}
if (securedConnection) {
host = new HttpHost(uri.getHost(), 443, uri.getScheme());
} else {
host = new HttpHost(uri.getHost(), 80, uri.getScheme());
}
get = new HttpGet(uri.getPath()+query_string);
}
private void processPostRequest() {
uri = Uri.parse(connectionUrl);
String protocol = connectionUrl.substring(0, 5).toLowerCase();
if (protocol.startsWith("https")) {
securedConnection = true;
} else {
securedConnection = false;
}
if (securedConnection) {
host = new HttpHost(uri.getHost(), 443, uri.getScheme());
} else {
host = new HttpHost(uri.getHost(), 80, uri.getScheme());
}
post = new HttpPost(uri.getPath());
}
</code></pre>
<p>Any suggestion to improve code will be appreciated</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T13:54:37.347",
"Id": "35874",
"Score": "0",
"body": "Without inspecting the code: Could it be that your mobile is slower in bandwidth and hardware processing power?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T04:14:30.360",
"Id": "35916",
"Score": "0",
"body": "@tb- thanks for suggestion yes, mobile is slower in bandwidth and hardware processing power but still there is any change that I should make in code so speed will increase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T12:01:18.037",
"Id": "35933",
"Score": "0",
"body": "Try using `HttpUrlConnection` instead of `HttpClient`. [Android's HTTP clients](http://android-developers.blogspot.ru/2011/09/androids-http-clients.html)"
}
] |
[
{
"body": "<p>I personally haven't used anything HTTP-related in Java yet, and thus can't talk about your performance. What I can see though is the following code:</p>\n\n<pre><code>if(protocol.startsWith(\"https\"){\n securedConnection = true;\n} else {\n securedConnection = false;\n}\n</code></pre>\n\n<p>I will assume you have <code>securedConnection</code> as a private classwide field, so I won't talk about the fact that you only use it to determine the port in the method scope.</p>\n\n<p>the fun thing is, your code could be written in one line:</p>\n\n<pre><code>securedConnection = protocol.startsWith(\"https\");\n</code></pre>\n\n<p>if you now inline protocol (Eclipse <kbd>Alt</kbd> + <kbd>Shift</kbd> + <kbd>i</kbd>) you get following line:</p>\n\n<pre><code>securedConnection = connectionUrl.substring(0,5).toLowerCase().startsWith(\"https\");\n</code></pre>\n\n<p>you see that the call to substring is unneccesary.</p>\n\n<hr>\n\n<p>You also have a large duplication in itself with the methods <code>processPostRequest()</code> and <code>processGetRequest</code>. they are actually exactly the same apart from the last line:</p>\n\n<pre><code>get = new HttpGet(uri.getPath()+query_string);\npost = new HttpPost(uri.getPath()); \n</code></pre>\n\n<p>you might want to move them into a method like this:</p>\n\n<pre><code>private enum Type{\n GET, POST\n}\n\nprivate HttpRequest processRequestOfType(Type t){\n uri = Uri.parse(connectionUrl);\n securedConnection = connectionUrl.toLowerCase().startsWith(\"https\");\n host = securedConnection ? new HttpHost(uri.getHost(), 443, uri.getScheme())\n : new HttpHost(uri.getHost(), 80, uri.getScheme());\n request = t == Type.GET ? new HttpGet(uri.getPath()+query_string) \n : new HttpPost(uri.getPath());\n return request;\n}\n</code></pre>\n\n<hr>\n\n<p>Lastly I saw that in your method <code>httpGetResponseStream()</code> you have the parameter request, which is never used in the code you posted.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T14:43:17.747",
"Id": "43141",
"ParentId": "23266",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T13:04:48.287",
"Id": "23266",
"Score": "4",
"Tags": [
"java",
"android",
"http",
"https"
],
"Title": "HTTP Get & Post code with slow performance"
}
|
23266
|
<p>Should the equals sign be alined on protocol buffers? I am having a huge discussion with a colleague and we can't get to decide on what's the best practice.</p>
<pre><code>message foobar {
optional bool var_one_short = 1;
optional bool var_two_looooooooong_name = 2;
optional bool another_var = 3;
}
</code></pre>
<p>vs</p>
<pre><code>message foobar {
optional bool var_one_short = 1;
optional bool var_two_looooooooong_name = 2;
optional bool another_var = 3;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-02T13:39:43.303",
"Id": "98125",
"Score": "0",
"body": "This question appears to be off-topic because it is about formatting data, not code (although code can be generated *from* a .proto file, the .proto file itself doesn't contain any code)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-02T14:19:48.703",
"Id": "98136",
"Score": "0",
"body": "@JerryCoffin I had completely forgot about this question if it wasn't for the notification. This question was originally migrated from SO to here. I don't want to seem protective but I actually disagree, protobufs defines a schema, so I would argue that schemas are subject to codereview."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-02T14:29:09.433",
"Id": "98138",
"Score": "0",
"body": "You raise a fair argument, *but* the long and short of it is that you need to draw a line somewhere. IMO, the line is drawn at languages that let you specify *actions* to be taken. Yes, actions such as reading and writing are implied with protobufs, but they're still strictly implicit, not embodied in the code itself."
}
] |
[
{
"body": "<p>I like more the first solution because it visually groups together the variables on the left side of the <code>=</code> and the value on the right side.\nUnfortunately I can't back this preference with a strong reason other than personal taste.</p>\n\n<p>In your situation I'd struggle for uniformity across your codebase and define a single convention that every programmer should follow.\nIt seems that you and your colleague are already trying to agree, but I wanted to point it out explicitly because I think that it is very important.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T15:20:36.853",
"Id": "23271",
"ParentId": "23270",
"Score": "1"
}
},
{
"body": "<p>I think the second version is much easier to maintain. If you have a new variable with a longer name (like <code>var_two_reaalllllly_looooooooong_name</code>) you don't have to modify three other lines too to keep it nice. The first version also could cause unnecessary patch/merge conflicts.</p>\n\n<p>From <em>Code Complete, 2nd Edition</em> by <em>Steve McConnell</em>, p758:</p>\n\n<blockquote>\n <p><strong>Do not align right sides of assignment statements</strong></p>\n \n <p>[...]</p>\n \n <p>With the benefit of 10 years’ hindsight, I have found that, \n while this indentation style might look attractive, it becomes\n a headache to maintain the alignment of the equals signs as variable \n names change and code is run through tools that substitute tabs\n for spaces and spaces for tabs. It is also hard to maintain as\n lines are moved among different parts of the program that have \n different levels of indentation.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T16:19:28.860",
"Id": "35880",
"Score": "0",
"body": "I think it's important to note that a lot of modern editors support this (example: [Sublime Text 2](http://wbond.net/sublime_packages/alignment)), so maintenance becomes trivial."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T16:21:45.210",
"Id": "35881",
"Score": "1",
"body": "I use sublime and yes it makes it easier. But his opinion convinced me."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T16:06:27.640",
"Id": "23273",
"ParentId": "23270",
"Score": "8"
}
},
{
"body": "<p>This is a simple \"Readability vs Maintainability\" issue. In a case like this, choose the second one. So, if you change your code or add a new variable, you don't have to realign the code at the end. You can achieve readability with other ways like giving your variables good names.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T20:01:10.047",
"Id": "23585",
"ParentId": "23270",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23273",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T15:09:42.520",
"Id": "23270",
"Score": "7",
"Tags": [
"protocol-buffers"
],
"Title": "Aligning '=' on protocol buffers .proto files"
}
|
23270
|
<p>I posted this on SO and would appreciate any ideas on it's stability.</p>
<p>Much like the old double-buffering algorithm, this uses a <code>List<T></code> to which are added entries. You can also take the list at any time, it will be atomically replaced with a new empty one.</p>
<p>Both adding and removing is thread safe. You can add from many threads and remove from many threads.</p>
<p>Most of the code is test code - everything after the <code>//TESTING</code> comment. My test consists of creating a number of producer and consumer threads and passing a known number of <code>Widget</code>s through. If all sent items appear on the other side correctly without loss or duplication my test passes.</p>
<p>Can anyone think of more tests?</p>
<p>Has anyone any general thoughts on the code?</p>
<pre><code>public class DoubleBufferedList<T> {
// Atomic reference so I can atomically swap it through.
// Mark = true means I am adding to it so momentarily unavailable for iteration.
private AtomicMarkableReference<List<T>> list = new AtomicMarkableReference<>(newList(), false);
// Factory method to create a new list - may be best to abstract this.
protected List<T> newList() {
return new ArrayList<>();
}
// Get and replace the current list.
public List<T> get() {
// Atomically grab and replace the list with an empty one.
List<T> empty = newList();
List<T> it;
// Replace an unmarked list with an empty one.
if (!list.compareAndSet(it = list.getReference(), empty, false, false)) {
// Failed to replace!
// It is probably marked as being appended to but may have been replaced by another thread.
// Return empty and come back again soon.
return Collections.<T>emptyList();
}
// Successfully replaced an unmarked list with an empty list!
return it;
}
// Grab and lock the list in preparation for append.
private List<T> grab() {
List<T> it;
// We cannot fail so spin on get and mark.
while (!list.compareAndSet(it = list.getReference(), it, false, true)) {
// Spin on mark - waiting for another grabber to release (which it must).
}
return it;
}
// Release the list.
private void release(List<T> it) {
// Unmark it - should this be a compareAndSet(it, it, true, false)?
if (!list.attemptMark(it, false)) {
// Should never fail because once marked it will not be replaced.
throw new IllegalMonitorStateException("It changed while we were adding to it!");
}
}
// Add an entry to the list.
public void add(T entry) {
List<T> it = grab();
try {
// Successfully marked! Add my new entry.
it.add(entry);
} finally {
// Always release after a grab.
release(it);
}
}
// Add many entries to the list.
public void add(List<T> entries) {
List<T> it = grab();
try {
// Successfully marked! Add my new entries.
it.addAll(entries);
} finally {
// Always release after a grab.
release(it);
}
}
// Add a number of entries.
public void add(T... entries) {
// Make a list of them.
add(Arrays.asList(entries));
}
// TESTING.
// How many testers to run.
static final int N = 10;
// The next one we're waiting for.
static final AtomicInteger[] seen = new AtomicInteger[N];
// The ones that arrived out of order.
static final Set<Widget>[] queued = new ConcurrentSkipListSet[N];
static {
// Populate the arrays.
for (int i = 0; i < N; i++) {
seen[i] = new AtomicInteger();
queued[i] = new ConcurrentSkipListSet();
}
}
// Thing that is produced and consumed.
private static class Widget implements Comparable<Widget> {
// Who produced it.
public final int producer;
// Its sequence number.
public final int sequence;
public Widget(int producer, int sequence) {
this.producer = producer;
this.sequence = sequence;
}
@Override
public String toString() {
return producer + "\t" + sequence;
}
@Override
public int compareTo(Widget o) {
// Sort on producer
int diff = Integer.compare(producer, o.producer);
if (diff == 0) {
// And then sequence
diff = Integer.compare(sequence, o.sequence);
}
return diff;
}
}
// Produces Widgets and feeds them to the supplied DoubleBufferedList.
private static class TestProducer implements Runnable {
// The list to feed.
final DoubleBufferedList<Widget> list;
// My ID
final int id;
// The sequence we're at
int sequence = 0;
// Set this at true to stop me.
public volatile boolean stop = false;
public TestProducer(DoubleBufferedList<Widget> list, int id) {
this.list = list;
this.id = id;
}
@Override
public void run() {
// Just pump the list.
while (!stop) {
list.add(new Widget(id, sequence++));
}
}
}
// Consumes Widgets from the suplied DoubleBufferedList
private static class TestConsumer implements Runnable {
// The list to bleed.
final DoubleBufferedList<Widget> list;
// My ID
final int id;
// Set this at true to stop me.
public volatile boolean stop = false;
public TestConsumer(DoubleBufferedList<Widget> list, int id) {
this.list = list;
this.id = id;
}
@Override
public void run() {
// The list I am working on.
List<Widget> l = list.get();
// Stop when stop == true && list is empty
while (!(stop && l.isEmpty())) {
// Record all items in list as arrived.
arrived(l);
// Grab another list.
l = list.get();
}
}
private void arrived(List<Widget> l) {
for (Widget w : l) {
// Mark each one as arrived.
arrived(w);
}
}
// A Widget has arrived.
private static void arrived(Widget w) {
// Which one is it?
AtomicInteger n = seen[w.producer];
// Don't allow multi-access to the same producer data or we'll end up confused.
synchronized (n) {
// Is it the next to be seen?
if (n.compareAndSet(w.sequence, w.sequence + 1)) {
// It was the one we were waiting for! See if any of the ones in the queue can now be consumed.
for (Iterator<Widget> i = queued[w.producer].iterator(); i.hasNext();) {
Widget it = i.next();
// Is it in sequence?
if (n.compareAndSet(it.sequence, it.sequence + 1)) {
// Done with that one too now!
i.remove();
} else {
// Found a gap! Stop now.
break;
}
}
} else {
// Out of sequence - Queue it.
queued[w.producer].add(w);
}
}
}
}
// Main tester
public static void main(String args[]) {
try {
System.out.println("DoubleBufferedList:Test");
// Create my test buffer.
DoubleBufferedList<Widget> list = new DoubleBufferedList<>();
// All running threads - Producers then Consumers.
List<Thread> running = new LinkedList<>();
// Start some producer tests.
List<TestProducer> producers = new ArrayList<>();
for (int i = 0; i < N; i++) {
TestProducer producer = new TestProducer(list, i);
Thread t = new Thread(producer);
t.setName("Producer " + i);
t.start();
producers.add(producer);
running.add(t);
}
// Start the same number of consumers (could do less or more if we wanted to).
List<TestConsumer> consumers = new ArrayList<>();
for (int i = 0; i < N; i++) {
TestConsumer consumer = new TestConsumer(list, i);
Thread t = new Thread(consumer);
t.setName("Consumer " + i);
t.start();
consumers.add(consumer);
running.add(t);
}
// Wait for a while.
Thread.sleep(5000);
// Close down all.
for (TestProducer p : producers) {
p.stop = true;
}
for (TestConsumer c : consumers) {
c.stop = true;
}
// Wait for all to stop.
for (Thread t : running) {
System.out.println("Joining " + t.getName());
t.join();
}
// What results did we get?
int totalMessages = 0;
for (int i = 0; i < N; i++) {
// How far did the producer get?
int gotTo = producers.get(i).sequence;
// The consumer's state
int seenTo = seen[i].get();
totalMessages += seenTo;
Set<Widget> queue = queued[i];
if (seenTo == gotTo && queue.isEmpty()) {
System.out.println("Producer " + i + " ok.");
} else {
// Different set consumed as produced!
System.out.println("Producer " + i + " Failed: gotTo=" + gotTo + " seenTo=" + seenTo + " queued=" + queue);
}
}
System.out.println("Total messages " + totalMessages);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T19:01:00.927",
"Id": "35888",
"Score": "0",
"body": "What is the specification of a Double Buffered List? I did not find a clear reference for this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T19:05:23.293",
"Id": "35889",
"Score": "0",
"body": "It's a list you can add to from multiple threads and at any time remove whatever has been collected, atomically replacing it with a fresh one. It is a list with double-buffer like features. Thank you for your interest."
}
] |
[
{
"body": "<p>Old question, new review.... I think, in general, I don't believe you are actually building anything better than what can be done with regular locking..... let me rephrase that to: the risk of spin-looping during an add is a significant drawback over regularly locked systems.</p>\n\n<p>So, while AtomicReferences may in fact be (marginally) faster than a ReentrantLock or a synchronization lock, the CPU cost of a spin while waiting for a 'slow' <code>add(T....values)</code> may in fact be significant.</p>\n\n<p>Another problem is that you may in fact be over-supplying new List instances. For example, you have to create a <code>new List<T>()</code> for every <code>get()</code>, but, if the current list is empty this is a waste. Also, it's a waste if the buffer is locked. This may add up to quite a lot of waste.</p>\n\n<p>While talking about this area of code, to get around Generic warnings, you should stop using <code>Collections.EMPTY_LIST</code> and instead use the type-safe and generics-friendly <code>Collections.emptyList()</code> (See <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#emptyList%28%29\" rel=\"nofollow\">the Javadoc</a>).</p>\n\n<p>So, as an academic exercise, I think your code is reasonable, but unnecessarily cumbersome. I think a simpler lock will suffice, produce better looking code, and provides functionality that you may not even consider now (like a blocking <code>get()</code> that only returns when data is available)</p>\n\n<p>Bottom line is that I don't believe your solution will have a noticable gain over something more simple/traditional. Certainly your solution has a number of complicated and esoteric concepts.... the Mark-flag is challenging, and the spin-lock-wait process is inefficient. </p>\n\n<p>So consider this alternative:</p>\n\n<pre><code>private List<T> mylist = newList();\nprivate final ReentrantLock mylock = new ReentrantLock();\n\n// Factory method to create a new list - may be best to abstract this.\nprotected List<T> newList() {\n return new ArrayList<>();\n}\n\n// Get and replace the current list.\npublic List<T> get() {\n // Atomically grab and replace the list with an empty one.\n mylock.lock();\n try {\n if (mylist.isEmpty()) {\n return Collections.emptyList();\n }\n final List<T> ret = mylist;\n mylist = newList();\n return ret;\n } finally {\n mylock.unlock();\n }\n}\n\n// Add an entry to the list.\npublic void add(T entry) {\n mylock.lock();\n try {\n mylist.add(entry);\n } finally {\n mylock.unlock();\n }\n}\n\n// Add many entries to the list.\npublic void add(List<T> entries) {\n // Atomically grab and replace the list with an empty one.\n mylock.lock();\n try {\n mylist.addAll(entries);\n } finally {\n mylock.unlock();\n }\n}\n\n// Add a number of entries.\npublic void add(T... entries) {\n // Make a list of them.\n add(Arrays.asList(entries));\n}\n</code></pre>\n\n<p>The above solution can be extended easily (in ways the AtomicMarkedReference cannot), for example, creating a Condition on the Lock would allow you to have a blocking get(), and other neat tricks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T09:03:41.513",
"Id": "58297",
"Score": "0",
"body": "Thankyou - I like your alternative and you make a good case for it's simplicity. I would move the check for empty outside the locked area but that is just me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T09:29:53.827",
"Id": "58300",
"Score": "0",
"body": "... `emptyList()` fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T06:55:58.537",
"Id": "35808",
"ParentId": "23275",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "35808",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T16:26:10.117",
"Id": "23275",
"Score": "3",
"Tags": [
"java",
"lock-free"
],
"Title": "Lock-free DoubleBufferedList"
}
|
23275
|
<p>I have some code that needs to update 2 separate databases with user credentials.
The first database, I just use standard sql to do it. The second database, I have to use command line scripts to update a specific table.
What I'm worried about is what to do if the first update fails, or if any of the updates fail.
Here's what the code looks like right now: </p>
<pre><code>local update_password = function(user_id, new_password, session_userid)
local user = listusers(user_id,nil)
if #user == 0 then
return false, "User does not exist"
else
sql = "UPDATE users SET password='"..new_password.."', ".."updatedname='"..session_userid.."', updateddatetime="..os.date("%Y%m%d%H%M%S")..createwhereclause(uid)
runsqlcommand(sql)
-- remove user from second db
local user = {}
user.descr, user.errtxt = opencmd({"dbctrl", "rm", user_id})
if not user.errtext then
user.descr, user.errtxt = opencmd({"dbctrl", "add", user_id, new_password})
else
result = "Unable to update cdb with new credentials"
return false, result
end
if not user.errtext then
result = "User's password has been updated"
else
result = "Unable to update cdb with new credentials"
return false, result
end
end
return true, result
end
</code></pre>
<p>I guess I should check each step of the way to make sure that the previous sql worked. So after updating database 1, I should do a select using the new credentials to make sure I get a result.
But do you have any other suggestions to improve the reliability of this code?
Thanks.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T16:31:36.620",
"Id": "23276",
"Score": "3",
"Tags": [
"lua"
],
"Title": "How can i make this code more robust, fail proof?"
}
|
23276
|
<p>I am trying to grab the ffprobe values from the video file into a variable that I can compare against others or move the value into a database. The question I have; Is there a better way of doing it than below?</p>
<p>I don't like the multiple if/elif/line.startswith statements and I am not sure of split is the best way of getting the ffprobe values?</p>
<pre><code>#!/usr/bin/python
import os, sys, subprocess, shlex, re, fnmatch
from subprocess import call
videoDrop_dir="/mnt/VoigtKampff/Temp/_Jonatha/test_drop"
for r,d,f in os.walk(videoDrop_dir):
for files in f:
print "Files: %s" % files
if files.startswith(('._', '.')):
print "This file: %s is not valid" % files
elif files.endswith(('.mov', '.mpg', '.mp4', '.wmv', '.mxf')):
fpath = os.path.join(r, files)
def probe_file(fpath):
cmnd = ['ffprobe', '-show_format', '-show_streams', '-pretty', '-loglevel', 'quiet', fpath]
p = subprocess.Popen(cmnd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print files
out, err = p.communicate()
print "===============================OUTPUT START: %s ===============================" % files
print out
for line in out.split('\n'):
line = line.strip()
if line.startswith('codec_name='):
s = line
codec_name = s.split('codec_name=', 1)
print "Codec is: %s" % codec_name[1]
codec_1 = codec_name[1]
elif line.startswith('codec_type='):
s = line
codec_type = s.split('codec_type=', 1)
print "Codec type is: %s" % codec_type[1]
codec_type1 = codec_type[1]
elif line.startswith('codec_long_name=', 1):
s = line
codec_long_name = s.split('codec_long_name=', 1)
print "Codec long name: %s" % codec_long_name[1]
codec_long_name = codec_long_name[1]
elif line.startswith('format_long_name=', 1):
s = line
format_long_name = s.split('format_long_name=', 1)
print "Format long name: %s" % format_long_name[1]
format_long_name = format_long_name[1]
elif line.startswith('width='):
s = line
width = s.split('width=', 1)
print "Video pixel width is: %s" % width[1]
p_width = width[1]
elif line.startswith('height='):
s = line
height = s.split('height=', 1)
print "Video pixel height is: %s" % height[1]
p_height = height[1]
elif line.startswith('bit_rate='):
s = line
bit_rate = s.split('bit_rate=', 1)
print "Bit rate is: %s" % bit_rate[1]
bit_rate1 = bit_rate[1]
elif line.startswith('display_aspect_ratio=', 1):
s = line
display_aspect_ratio = s.split('display_aspect_ratio=', 1)
print "Display aspect ratio: %s" % display_aspect_ratio[1]
display_aspect_ratio1 = display_aspect_ratio[1]
elif line.startswith('avg_frame_rate=', 1):
s = line
avg_frame_rate = s.split('avg_frame_rate=', 1)
print "Average Frame Rate: %s" % avg_frame_rate[1]
avg_frame_rate1 = avg_frame_rate[1]
print "===============================OUTPUT FINISH: %s ===============================" % files
if err:
print "===============================ERROR: %s ===============================" % files
print err
probe_file(fpath)
else:
if not files.endswith(('.mov', '.mpg', '.mp4', '.wmv', '.mxf')):
print "This file: %s is not a valid video file" % files
</code></pre>
|
[] |
[
{
"body": "<pre><code>#!/usr/bin/python\nimport os, sys, subprocess, shlex, re, fnmatch\nfrom subprocess import call \n\nvideoDrop_dir=\"/mnt/VoigtKampff/Temp/_Jonatha/test_drop\"\n</code></pre>\n\n<p>Python convention is to ALL_CAPS for global constants</p>\n\n<pre><code>for r,d,f in os.walk(videoDrop_dir):\n</code></pre>\n\n<p>I suggest not using single letter variable names here, it just obfuscates the meanings.</p>\n\n<pre><code> for files in f:\n</code></pre>\n\n<p>files is a single file, not plural, it should be file or filename.</p>\n\n<pre><code> print \"Files: %s\" % files\n if files.startswith(('._', '.')):\n</code></pre>\n\n<p>Since ._ starts with . there is no reason to check both.</p>\n\n<pre><code> print \"This file: %s is not valid\" % files\n elif files.endswith(('.mov', '.mpg', '.mp4', '.wmv', '.mxf')):\n fpath = os.path.join(r, files)\n def probe_file(fpath):\n</code></pre>\n\n<p>Why do you define a function inline and then just call it? Either get rid of the function or move the function outside of the loop and call it.</p>\n\n<pre><code> cmnd = ['ffprobe', '-show_format', '-show_streams', '-pretty', '-loglevel', 'quiet', fpath]\n</code></pre>\n\n<p>Don't needlessly abbreivate, call it <code>command</code></p>\n\n<pre><code> p = subprocess.Popen(cmnd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n print files\n out, err = p.communicate()\n print \"===============================OUTPUT START: %s ===============================\" % files\n print out\n</code></pre>\n\n<p>See subprocess.check_output. It calls the command returns the string so you can simplify this last but of code.</p>\n\n<pre><code> for line in out.split('\\n'):\n line = line.strip()\n if line.startswith('codec_name='):\n s = line \n codec_name = s.split('codec_name=', 1)\n print \"Codec is: %s\" % codec_name[1]\n codec_1 = codec_name[1]\n</code></pre>\n\n<p>Rather then repeating this bunches of times, do something like</p>\n\n<pre><code>decoder_configuration = {}\nfor line in out.splitlines():\n if '=' in line:\n key, value = line.split('=')\n decoder_configuration[key] = value\n\n\nThen all of the pieces of data will be held in decoder_configuration. You can do what you want with it from there.\n\n print \"===============================OUTPUT FINISH: %s ===============================\" % files\n if err: \n print \"===============================ERROR: %s ===============================\" % files\n print err\n probe_file(fpath)\n else:\n if not files.endswith(('.mov', '.mpg', '.mp4', '.wmv', '.mxf')):\n print \"This file: %s is not a valid video file\" % files \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T18:01:56.660",
"Id": "35882",
"Score": "0",
"body": "Thank you so much - I really appreciate your help! I will try and put this into play right now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T19:39:06.803",
"Id": "35891",
"Score": "0",
"body": "It worked. The only thing I did not manage to get working was the subprocess.check_output - but I will spend some time getting more familiar with subprocess calls. Again thank you"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T17:53:26.090",
"Id": "23278",
"ParentId": "23277",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23278",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T16:56:14.337",
"Id": "23277",
"Score": "3",
"Tags": [
"python"
],
"Title": "Trying to get output of ffprobe into variable"
}
|
23277
|
<p>Trying to implement a deep-iteration function with some constraints, I've noticed the faster solution is iterating it twice! Any attempt to avoid this resulted in slower code. So, the challenge: can you redesign the function below removing the code duplicate and doubled iteration, without making it slower?</p>
<p>Constraints:</p>
<ul>
<li>It must deeply iterate through a tree, providing, for a callback function, the node value and it's path.</li>
<li>It must work for arrays and objects.</li>
<li>Arrays must be iterated by ascending numerical keys first and non-numerical keys last.</li>
<li>It must allow for early interruption by using "return", and must return that value.</li>
</ul>
<p>Code:</p>
<pre><code>function iter(obj,fn,iter_pos){
var ret, iter_pos = iter_pos || [];
for (var i=0; i<obj.length; ++i)
if (ret = typeof(obj[i]) == "object" ? iter(obj[i],fn,iter_pos.concat(i)) : fn(iter_pos.concat(i),obj[i]))
return ret;
for (var key in obj)
if (isNaN(Number(key)))
if (ret = typeof(obj[key]) == "object" ? iter(obj[key],fn,iter_pos.concat(key)) : fn(iter_pos.concat(key),obj[key]))
return ret;
};
</code></pre>
<p>Test:</p>
<pre><code>var tree = [1,2,[3,3,3],4];
tree.x = 5;
tree.y = {x:6,y:7,z:8};
tree.z = 9;
console.log(
iter(tree,function(path,val){
console.log("Value ",val," at path: ",path);
if (val==7)
return "Returned early!";
})
);
</code></pre>
<p>Output:</p>
<pre><code>Value 1 at path: [ 0 ]
Value 2 at path: [ 1 ]
Value 3 at path: [ 2, 0 ]
Value 3 at path: [ 2, 1 ]
Value 3 at path: [ 2, 2 ]
Value 4 at path: [ 3 ]
Value 5 at path: [ 'x' ]
Value 6 at path: [ 'y', 'x' ]
Value 7 at path: [ 'y', 'y' ]
Returned early!
</code></pre>
|
[] |
[
{
"body": "<p>Let me start by asking how would you like to iterate over your object? Because what you are doing is not the same as calling a function for every property of an object.</p>\n\n<blockquote>\n<pre><code>function iter(obj,fn,iter_pos){\n var ret, iter_pos = iter_pos || [];\n for (var i=0; i<obj.length; ++i)\n</code></pre>\n</blockquote>\n\n<p>The above for loop may access elements in the array that are not even defined. For example, take this array:</p>\n\n<pre><code>var a = [0, 1];\na[9] = 9;\nconsole.log(a.length); // -> 10\nconsole.log(a.hasOwnProperty(0)); // -> true\nconsole.log(a.hasOwnProperty(1)); // -> true\nconsole.log(a.hasOwnProperty(2)); // -> false !!\nconsole.log(a.hasOwnProperty(9)); // -> true\n</code></pre>\n\n<p>The above array has a length of 10, but it only has three <em>properties</em> (it has 10 <em>elements</em>, but not all are defined). If you do an <code>a.forEach()</code>, you'll iterate over the array's <em>properties</em>, only those that are defined.</p>\n\n<p>If you do a <code>for (i=0; i<a.length; i++)</code> loop over the array, you'll get properties that are not defined. To avoid those, you should check <code>a.hasOwnProperty()</code>. Or just use the native <code>forEach</code>, if you can, that will iterate over the array correctly.</p>\n\n<p>Note that checking against <code>undefined</code> would not be sufficient either, array elements can be <em>present but undefined</em>:</p>\n\n<pre><code>a[5] = undefined;\nconsole.log(a.hasOwnProperty(5)); // -> true !!\n</code></pre>\n\n<blockquote>\n<pre><code> if (ret = typeof(obj[i]) == \"object\" ? iter(obj[i],fn,iter_pos.concat(i)) : fn(iter_pos.concat(i),obj[i]))\n return ret;\n for (var key in obj)\n if (isNaN(Number(key)))\n</code></pre>\n</blockquote>\n\n<p>Here you're trying to do the opposite of <code>forEach</code>: enumerating properties that are not elements of the array.</p>\n\n<p>But this code will miss properties that still evaluate as numbers! Have a look at the following array:</p>\n\n<pre><code>var a = [0, 1, 2, 3, 4];\na[100] = 99;\na[1.5] = 'this is not an array element';\na[-1] = 'this one is not an array element either';\na['20'] = 'this one *is* an array element!';\n</code></pre>\n\n<p>Also, watch out for rounding:</p>\n\n<pre><code>a[30.00000000000001] = 'this is *not* an array element';\na[30.000000000000001] = 'this *is*, however, because it rounds to 30'\n</code></pre>\n\n<p>But also for the string representations:</p>\n\n<pre><code>a[30.000000000000001] = 'array element';\na['30.000000000000001'] = 'not array element';\n</code></pre>\n\n<p>Especially the ones that evaluate the same:</p>\n\n<pre><code>a[1e1] = 'element number ten';\na['1e1'] = 'a completely different element';\n</code></pre>\n\n<p><code>'-1'</code>, <code>'1.5'</code>, <code>'1e1'</code>, <code>'30.000000000000001'</code>, etc. can all be properties of an array, but they will all evaluate <code>false</code> for <code>isNaN(Number(key))</code>.</p>\n\n<blockquote>\n<pre><code> if (ret = typeof(obj[key]) == \"object\" ? iter(obj[key],fn,iter_pos.concat(key)) : fn(iter_pos.concat(key),obj[key]))\n return ret;\n};\n</code></pre>\n</blockquote>\n\n<p>You can easily fix your script by changing the line</p>\n\n<pre><code> if (isNaN(Number(key)))\n</code></pre>\n\n<p>to</p>\n\n<pre><code> if (!key.match(/^\\d+$/))\n</code></pre>\n\n<p>, but unfortunately that makes your code about 18% slower.</p>\n\n<h1>TL; DR</h1>\n\n<p>I've removed the double loop from your code:</p>\n\n<pre><code>function iter(obj, fn, iter_pos){\n var ret, iter_pos = iter_pos || [];\n for (var key in obj)\n if (ret = typeof(obj[key]) == \"object\" ? iter(obj[key], fn, iter_pos.concat(key)) : fn(iter_pos.concat(key), obj[key]))\n return ret;\n};\n</code></pre>\n\n<p>and it does not seem to be any slower, or at least not according to <a href=\"http://jsperf.com/iter\">jsperf.com/iter</a>.</p>\n\n<p>I tried it in a number of browsers I could find.</p>\n\n<h1>UPDATE 1:</h1>\n\n<p>Here is a version that uses two loops, but is <strong>much faster</strong>. It will fix the ordering, but only in cases where the array indexes come before other array properties.</p>\n\n<pre><code>__toString = Object.prototype.toString;\n\nfunction iter(obj, fn, iter_pos) {\n var ret, i = 0,\n iter_pos = iter_pos || [];\n if (__toString.call(obj) === '[object Array]') {\n obj.forEach(function (item) {\n if (!ret) {\n ret = typeof (obj[i]) === \"object\" ? iter(obj[i], fn, iter_pos.concat(i)) : fn(iter_pos.concat(i), obj[i]);\n i++;\n }\n });\n if (ret)\n return ret;\n }\n for (var key in obj)\n if (--i < 0)\n if (ret = typeof (obj[key]) === \"object\" ? iter(obj[key], fn, iter_pos.concat(key)) : fn(iter_pos.concat(key), obj[key])) return ret;\n};\n</code></pre>\n\n<h1>UPDATE 2:</h1>\n\n<p>This is your original version, with two loops, but using <code>forEach</code> and <code>Object.prototype.toString</code>. It seems to output the same result, but is about 2000× faster.</p>\n\n<pre><code>__toString = Object.prototype.toString;\n\nfunction iter(obj, fn, iter_pos) {\n var ret, iter_pos = iter_pos || [];\n if (__toString.call(obj) === '[object Array]') {\n obj.forEach(function (item) {\n if (!ret)\n ret = typeof (obj[i]) === \"object\" ? iter(obj[i], fn, iter_pos.concat(i)) : fn(iter_pos.concat(i), obj[i]);\n });\n if (ret)\n return ret;\n }\n for (var key in obj)\n if (!(\"\" + key).match(/^\\d+$/))\n if (ret = typeof (obj[key]) === \"object\" ? iter(obj[key], fn, iter_pos.concat(key)) : fn(iter_pos.concat(key), obj[key]))\n return ret;\n};\n</code></pre>\n\n<h1>UPDATE 3:</h1>\n\n<p>This version is about as fast as the other one, but uses only <code>Object.prototype.toString</code> and does not use <code>typeof</code>.</p>\n\n<pre><code>__toString = Object.prototype.toString;\n\nfunction iter(obj, fn, iter_pos) {\n var ret, obj_type, iter_pos = iter_pos || [];\n if (__toString.call(obj) === '[object Array]') {\n obj.forEach(function (item) {\n if (!ret)\n ret = ((obj_type = __toString.call(item)) === \"[object Object]\") || (obj_type === \"[object Array]\") ? iter(item, fn, iter_pos.concat(i)) : fn(iter_pos.concat(i), item);\n });\n if (ret)\n return ret;\n }\n for (var key in obj)\n if (!(\"\" + key).match(/^\\d+$/))\n if (ret = ((obj_type = __toString.call(item)) === \"[object Object]\") || (obj_type === \"[object Array]\") ? iter(obj[key], fn, iter_pos.concat(i)) : fn(iter_pos.concat(i), obj[key]));\n return ret\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T02:07:58.597",
"Id": "35909",
"Score": "0",
"body": "Awesome answer! I thought nobody would answer this question. Thanks! Enlightening in many aspects. I had no idea numeric keys worked that way. Yet your implementation has a problem I have faced before: it is not guaranteed to iterate numeric keys in ascending order in some implementations (the double loop is actually a bugfix for this behavior!) Sucks, no?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T02:09:45.520",
"Id": "35910",
"Score": "0",
"body": "Hmm, I've only checked that in Chrome, and there it iterated in ascending order. Let me try something else now (another double-loop idea that may be faster)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T02:12:48.273",
"Id": "35911",
"Score": "0",
"body": "I'm not sure how/when, but sometimes it just doesn't iterate in the right order. I know it have something to do with defining numeric keyvals after the array was created, on safari I think. Very specific, but broke many things."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T03:19:16.157",
"Id": "35912",
"Score": "0",
"body": "@Dokkat please look at my second update. It keeps the two loops, but uses the built-in `forEach` for arrays, and uses the regex match to correctly exclude array elements in the second loop. It is 2000× faster than the original code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T03:34:27.377",
"Id": "35913",
"Score": "0",
"body": "What the heck!? Hold on while I test. But how did you find that out? How did you even consider that regex could be faster than isNaN?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T03:38:48.680",
"Id": "35914",
"Score": "0",
"body": "I don't think the regex makes it faster. `isNaN(Number())` will pick out false positive property names like `1e1`. What probably made a difference is the `forEach`. I'm not exactly sure though. It might perform worse if you have a very long array and you break at the very beginning, because there's no way (that I know of) to break out of the `forEach` loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T04:00:39.600",
"Id": "35915",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/7717/discussion-between-attila-o-and-dokkat)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T04:50:30.043",
"Id": "35917",
"Score": "0",
"body": "sorry I was working on the conversion of some files. Oh I see, that makes sense then. Any idea why Object.prototype.toString faster than typeof?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T05:08:24.267",
"Id": "35918",
"Score": "0",
"body": "I have no clue, but [this answer](http://stackoverflow.com/a/10656437/252239) shows they don't even behave the same… Oh well, JavaScript can still surprise me after all the years :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-04T17:10:24.903",
"Id": "149597",
"Score": "0",
"body": "@AttilaO. updates 2 & 3 need `.forEach(item, i)` instead of `.forEach(item)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-02T12:39:09.387",
"Id": "279753",
"Score": "0",
"body": "I can't get the typescript compiler to compile solution 2 and 3. Solution uses a undefined variable i, and solution 3 uses a undefined variable item. Yet I see the code runs here https://jsperf.com/iter, and I don't understand how it could possibly run at all with those undefined :-/"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T01:28:06.290",
"Id": "23292",
"ParentId": "23280",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "23292",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T18:24:36.770",
"Id": "23280",
"Score": "6",
"Tags": [
"javascript",
"optimization",
"algorithm",
"design-patterns"
],
"Title": "Challenge: solution for this deep-iteration JavaScript function dilemma?"
}
|
23280
|
<p>The code realizes producer/consumer problem with multiple producers and consumers. Have this code any potential deadlock or races?</p>
<pre><code>//RandomDataProvider.cs
namespace MyNamespace.Core
{
using System;
/// <summary>
/// Provides randomly generated data.
/// </summary>
public class RandomDataProvider
{
#region constuction
/// <summary>
/// Initializes new instance of the <see cref="RandomDataProvider"/> class.
/// </summary>
/// <param name="maxSleepInterval"></param>
public RandomDataProvider(int maxSleepInterval)
{
_maxSleepInterval = maxSleepInterval;
}
#endregion // constuction
#region implementation
/// <summary>
/// Gets the random sleeping interval.
/// </summary>
public int GetSleepInterval()
{
lock (_locker)
{
return _random.Next(_maxSleepInterval);
}
}
/// <summary>
/// Gets the random value.
/// </summary>
public int GetRandomValue()
{
lock (_locker)
{
return _random.Next(1, 100);
}
}
#endregion // implementation
#region representation
private readonly Random _random = new Random();
private readonly object _locker = new object();
private readonly int _maxSleepInterval;
#endregion // representation
}
}
//Producer.cs
namespace MyNamespace.Core
{
using System.Collections.Generic;
using System.Threading;
/// <summary>
/// Reprecents <see cref="Producer"/> class.
/// </summary>
public sealed class Producer : RandomDataProvider
{
#region construction
/// <summary>
/// Initializes the new instance of <see cref="Producer"/> class.
/// </summary>
/// <param name="queue">Queue to which producers put items.</param>
/// <param name="maxSleepInterval">The maximum sleep interval.</param>
public Producer(Queue<int> queue, int maxSleepInterval)
: base(maxSleepInterval)
{
_queue = queue;
}
#endregion // construction
#region implementation
/// <summary>
/// Starts produce items and put to queue.
/// </summary>
/// <param name="token">Cancellation token.</param>
public void StartProduce(CancellationToken token)
{
while (true)
{
// If canceled stop producing.
if (token.IsCancellationRequested)
{
return;
}
Thread.Sleep(GetSleepInterval());
int item = GetRandomValue();
lock (_queue)
{
if (_isReachedMax)
{
// if producer reached max items, block and wait until count decreases 80.
while (_queue.Count > 80)
{
Monitor.Wait(_queue);
}
// now we can release thread
_isReachedMax = false;
}
_queue.Enqueue(item);
if (_queue.Count == 1)
{
// Pulse comsumres which waits on empty queue
Monitor.Pulse(_queue);
}
else if (_queue.Count >= 100)
{
// Set reached max count flag.
_isReachedMax = true;
}
}
}
}
#endregion // implementation
#region representation
private readonly Queue<int> _queue;
private bool _isReachedMax;
#endregion // representation
}
}
//Consumer.cs
namespace MyNamespace.Core
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
/// <summary>
/// Reprecents <see cref="Consumer"/> class.
/// </summary>
public sealed class Consumer : RandomDataProvider, IDisposable
{
/// <summary>
/// Initializes the new instance of <see cref="Consumer"/> class.
/// </summary>
/// <param name="queue">The queue from which consumes items.</param>
/// <param name="maxSleepInterval">The maximum sleep interval.</param>
public Consumer(Queue<int> queue, int maxSleepInterval)
:base(maxSleepInterval)
{
_queue = queue;
}
#region implementation
#region Implementation of IDisposable
/// <summary>
/// Disposes the current instance.
/// </summary>
public void Dispose()
{
StreamWriter.Close();
}
#endregion
/// <summary>
/// Starts consume items from queue.
/// </summary>
/// <param name="token">Cancellation token.</param>
public void StartConsume(CancellationToken token)
{
while (true)
{
Thread.Sleep(GetSleepInterval());
int item;
lock (_queue)
{
// If no item in queue after cancel, return.
if (_queue.Count == 0 && token.IsCancellationRequested)
{
return;
}
// Wait when queue empty.
while (_queue.Count == 0)
{
Monitor.Wait(_queue);
}
item = _queue.Dequeue();
// if count decreases and reaches 80, then inform produsers which wait.
if (_queue.Count <= 80)
{
Monitor.PulseAll(_queue);
}
}
WriteToStream(item);
}
}
#endregion // implementation
#region operations
/// <summary>
/// Writes items to the stream.
/// </summary>
/// <param name="item">Item to write.</param>
private void WriteToStream(int item)
{
lock (StreamWriter)
{
StreamWriter.Write("{0},", item);
}
}
#endregion // operations
#region representation
private readonly Queue<int> _queue;
private static readonly StreamWriter StreamWriter = new StreamWriter(FILE_PATH);
#endregion // representation
#region constants
private const string FILE_PATH = "data.txt";
#endregion // constants
}
}
//Controller.cs
namespace Root
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Timers;
using MyNamespace.Core;
/// <summary>
/// Provides functionality that controls <see cref="Producer"/> and <see cref="Consumer"/> concurency.
/// </summary>
public class Controller : IDisposable
{
#region construction
/// <summary>
/// Initializes the new instance of <see cref="Controller"/> class.
/// </summary>
/// <param name="queue">Shared Queue object.</param>
public Controller(Queue<int> queue)
{
_queue = queue;
_timer = new System.Timers.Timer(1000);
_timer.Elapsed += ShowCount;
}
#endregion // construction
#region implementation
#region Implementation of IDisposable
/// <summary>
/// Disposes the current instance.
/// </summary>
public void Dispose()
{
foreach (var consumer in _consumers)
{
consumer.Dispose();
}
}
#endregion
/// <summary>
/// Creates consumer/producer objects and ran them each in seperate thread.
/// </summary>
public void Start()
{
_consumerThreads = new Thread[_consumerCount];
_producerThreads = new Thread[_producerCount];
_consumers = new Consumer[_consumerCount];
_producers = new Producer[_producerCount];
for (int i = 0; i < ProducerCount; ++i)
{
var producer = new Producer(_queue, _maxSleepInterval);
_producers[i] = producer;
_producerThreads[i] = new Thread(() => producer.StartProduce(_source.Token));
_producerThreads[i].Start();
}
for (int i = 0; i < ConsumerCount; ++i)
{
var consumer = new Consumer(_queue, _maxSleepInterval);
_consumers[i] = consumer;
_consumerThreads[i] = new Thread(() => consumer.StartConsume(_source.Token));
_consumerThreads[i].Start();
}
_timer.Start();
}
/// <summary>
/// Cancels producing/consuming.
/// </summary>
public void Cancel()
{
_source.Cancel();
_timer.Stop();
for (int i = 0; i < ConsumerCount; ++i)
{
_consumerThreads[i].Join();
}
}
#endregion // implementation
#region properties
/// <summary>
/// Gets or sets consumers count.
/// </summary>
public int ConsumerCount
{
get { return _consumerCount; }
set { _consumerCount = value; }
}
/// <summary>
/// Gets or sets producers count.
/// </summary>
public int ProducerCount
{
get { return _producerCount; }
set { _producerCount = value; }
}
/// <summary>
/// Gets or sets maximum sleep interval.
/// </summary>
public int MaxSleepInterval
{
get { return _maxSleepInterval; }
set { _maxSleepInterval = value; }
}
#endregion // properties
#region operations
/// <summary>
/// Shows the queue size.
/// </summary>
/// <param name="sender">Sender object.</param>
/// <param name="e">Event handler argumnets.</param>
private void ShowCount(object sender, ElapsedEventArgs e)
{
int count;
lock (_queue)
{
count = _queue.Count;
}
Console.WriteLine("Items in the queue: {0}", count);
}
#endregion // operations
#region representation
/// <summary>
/// Shared between produsers and consumers queue object.
/// </summary>
private readonly Queue<int> _queue;
/// <summary>
/// Thread in which runs each consumer.
/// </summary>
private Thread[] _consumerThreads;
/// <summary>
/// Thread in which runs each producer.
/// </summary>
private Thread[] _producerThreads;
/// <summary>
/// Array of <see cref="Consumer"/> objects.
/// </summary>
private Consumer[] _consumers;
/// <summary>
/// Array of <see cref="Producer"/> objects.
/// </summary>
private Producer[] _producers;
/// <summary>
/// Timer object.
/// </summary>
private readonly System.Timers.Timer _timer;
/// <summary>
/// Provides cancellation token.
/// </summary>
private readonly CancellationTokenSource _source = new CancellationTokenSource();
private int _consumerCount = 10;
private int _producerCount = 10;
private int _maxSleepInterval = 100;
#endregion // representation
}
}
</code></pre>
<p>At the end</p>
<pre><code>//Program.cs
namespace Root
{
using System;
using System.Collections.Generic;
class Program
{
private static void Main(string[] args)
{
int prdCnt;
int conCnt;
Console.Write("Enter produsers count[1-10]:");
while (!int.TryParse(Console.ReadLine(), out prdCnt) || prdCnt < 1 || prdCnt > 10)
{
Console.WriteLine("Error");
Console.Write("Enter produsers count[1-10]:");
}
Console.Write("Enter consumers count[1-10]:");
while (!int.TryParse(Console.ReadLine(), out conCnt) || conCnt < 1 || conCnt > 10)
{
Console.WriteLine("Error");
Console.Write("Enter consumers count[1-10]:");
}
Queue<int> queue = new Queue<int>();
using (var controller = new Controller(queue))
{
controller.ConsumerCount = conCnt;
controller.ProducerCount = prdCnt;
controller.Start();
Console.ReadLine();
controller.Cancel();
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T18:50:51.570",
"Id": "35886",
"Score": "0",
"body": "What .NET framework do you use?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T19:21:10.927",
"Id": "35890",
"Score": "0",
"body": "@almaz .net 4.0 , 4.5 but using namespace `System.Collections.Concurrent` not allowed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T20:18:28.357",
"Id": "35894",
"Score": "3",
"body": "Is any particular reason why specific namespace is not allowed? I can't think of any case when `CancellationToken` would be allowed but not `BlockingCollection`..."
}
] |
[
{
"body": "<p>The main issue in this code is that several classes rely on each other's proper behaviour in order to work correctly. I'm talking about sharing the instance of <code>Queue<int></code> and requirement for proper locking on it in all places. See remarks to <a href=\"http://msdn.microsoft.com/en-us/library/c5kehkcz%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>lock</code> Statement</a> for recommendations on proper usage.</p>\n\n<p>Since you mentioned that you can't use the <code>System.Collections.Concurrent</code> \nnamespace I suggest to create a class that mimics BlockingCollection functionality to avoid first issue. It should incapsulate the thread-safe manipulation with queue, so that both <code>Consumer</code> and <code>Producer</code> don't need to handle multithreading logic.</p>\n\n<p>Also I don't see the reason for deriving <code>Producer</code>/<code>Consumer</code> from <code>RandomDataProvider</code>. They use functionality of <code>RandomDataProvider</code>, but not extend it, so classes should not derive from it and rather store the instance of <code>RandomDataProvider</code> in a field.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T21:02:17.117",
"Id": "23285",
"ParentId": "23281",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T18:46:10.763",
"Id": "23281",
"Score": "2",
"Tags": [
"c#",
"multithreading",
"synchronization",
"producer-consumer"
],
"Title": "Producer/Consumer with some limitations"
}
|
23281
|
<p>The facade pattern is used to abstract adding events. Should support IE5+ as stands.</p>
<p>Looking for minor improvements. Don't need to support prior to IE5.</p>
<p>I choose not to use a library.</p>
<pre><code>/*addEL
** dependencies - none
** browser - IE5+
** notes - improved per answer
*/
NS.addEL = (function binding() {
if (window.addEventListener) {
return function addEventListener(element, type, callNow) {
element.addEventListener(type, callNow);
};
}
if (window.attachEvent) {
return function attachEvent(element, type, callNow) {
element.attachEvent('on' + type, callNow);
};
}
}());
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Why does binding have parameters? The closure isn't passing any.</p></li>\n<li><p>As far as I know, 75% of browsers (including IE9+) actually support <code>addEventListener</code>. If you check for <code>attachEvent</code> first, you are wasting that 75% assurance. Instead, check for <code>addEventListener</code> first and 75% of the time, your code is evaluating just one condition.</p></li>\n<li><p>For better readability, use common conventions when naming. Element references can be shortened to <code>el</code>, events are usually <code>ev</code> (because <code>e</code> sometimes refer to error objects), and event handlers are usually called <code>handler</code> or <code>callback</code>.</p></li>\n<li><p>Although you might say that you are not going to support older/other browsers, that does not mean you should recklessly code. </p>\n\n<p>In your code, if you used <code>attachEvent</code> was not supported, you use <code>addEventListener</code>. But what if the browser hasn't got <code>addEventListener</code> either? The binding will crash trying to use it since <code>addEventListener</code> a last resort that is, in this case, not supported. </p>\n\n<p>So I added a third case which makes <code>NS.addEL</code> be a function that does nothing if both methods are not available.</p></li>\n</ul>\n\n<p>And so:</p>\n\n<pre><code>NS.addEL = (function binding(){\n\n if(window.addEventListener){\n return function addEventListener(el, ev, handler){\n el.addEventListener(ev, handler);\n }\n }\n\n if(window.attachEvent) {\n return function attachEvent(el, ev, handler){\n el.attachEvent('on' + ev, handler);\n }\n }\n\n return function(){/*not supported for some reason*/}\n\n}());\n</code></pre>\n\n<p>Another approach to this is the following code. It's shorter, but performs checks everytime the function is called. If the browser supports neither, then nothing is actually executed:</p>\n\n<pre><code>NS.addEL = function addEL(el,ev,handler){\n if(window.addEventListener) {\n el.addEventListener(ev,handler);\n } else if(window.attachEvent){\n el.attachEvent('on' + ev,handler);\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T15:23:13.683",
"Id": "35943",
"Score": "1",
"body": "I have to disagree about unnecessarily abbreviating variable names. Longer variable names are always better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T15:48:17.893",
"Id": "35946",
"Score": "0",
"body": "@pure_code well, in your code `type` could mean anything. It could mean type of a value (as in `typeof`) or something else. Also, when i first read the code, I had to decipher what `callNow` was and after reading further into the code, it was the event handler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T00:54:13.323",
"Id": "35978",
"Score": "2",
"body": "Is there any reason you're naming the functions you're returning? Returning anonymous functions works just fine and regardless they'll be called as `NS.addEL`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T20:45:54.033",
"Id": "41847",
"Score": "0",
"body": "@Joseph in your code, you don't need the `else if`, just `if`, as there is a return in the preceding `if`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T20:46:36.177",
"Id": "41848",
"Score": "0",
"body": "@Joseph - your second snippet is less efficient as it runs a check multiple times; however that check only needs to be run once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T00:51:33.463",
"Id": "41866",
"Score": "0",
"body": "@pure_code Yes, I did say it performs checks everytime. But it's shorter."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T13:07:31.590",
"Id": "23308",
"ParentId": "23282",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T19:27:23.820",
"Id": "23282",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "addEventListener - v0"
}
|
23282
|
<p>*Originally posted this on stackoverflow but was told that it would be better suited here. </p>
<p>So I'm looking for a better way to setup how an application talks with a database. I'm sure this question has been asked many times, and I dug through a few of the similar ones but couldn't find one that really flushed it out as much as I'd have liked.</p>
<p>I have an application that uses a database helper class to connect and retrieve records from a database. I was considering rewriting it and wanted to know what the best way to do it would be. </p>
<p>Here is roughly how it's set up now (Note: This is already in place, and there are thousands of lines of this stuff).</p>
<p><a href="http://pastie.org/6355776" rel="nofollow"><strong>DatabaseHelper.CS</strong></a></p>
<pre><code> private SqlConnection conn;
public DatabaseHelper()
{
// Create database connection
conn = new System.Data.SqlClient.SqlConnection();
SqlConnectionStringBuilder connection = new SqlConnectionStringBuilder();
connection.ConnectTimeout = 150; // Microsft fix for timeout error (known bug)
connection.MinPoolSize = 20; // Microsft fix for timeout error (known bug)
connection.DataSource = Properties.Settings.Default.DBString;
connection.InitialCatalog = Properties.Settings.Default.DBInitCatalog;
connection.IntegratedSecurity = true;
if (conn.State != ConnectionState.Connecting)
{
conn.ConnectionString = connection.ConnectionString;
}
}
public bool Open()
{
if (this.IsOpen()) // IsOpen is just a method that checks connectionstate.
{ return true; }
else
{
try
{
conn.Open();
return true;
}
catch (System.Data.SqlClient.SqlException ex)
{
// omitted for post
}
}
return false;
}
public bool Close()
{
if (!this.IsOpen())
{ return true; }
try
{
conn.Close();
return true;
}
catch (System.Data.SqlClient.SqlException ex)
{
// omitted for post
}
return false;
}
public List<string> GetTeamLeaders(string team)
{
List<string> leaders = new List<string>();
string query = "Select Leader FROM Teams WHERE Team = @team_vc";
try
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("@team_vc", SqlDbType.NVarChar).Value = team;
using (SqlDataReader sdr = cmd.ExecuteReader())
{
int column = sdr.GetOrdinal("Leader");
while (sdr.Read())
{
leaders.Add(sdr[column].ToString());
}
}
}
}
catch (Exception ex)
{
// omitted for post
}
return leaders;
}
private string GetTeamAbbrev(string team)
{
string abbrev= "";
string query = "SELECT Abbrev FROM Teams where Team = @team_vc";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("@team_vc", SqlDbType.NVarChar).Value = team;
try
{
abbrev= Convert.ToString(cmd.ExecuteScalar());
}
catch (Exception ex)
{
// omitted for post
}
}
return (string.IsNullOrEmpty(location)) ? "None" : abbrev;
}
</code></pre>
<p><a href="http://pastie.org/6355781" rel="nofollow"><strong>MainApp.CS</strong></a></p>
<pre><code> private DatabaseHelper dbHelper;
public MainApp()
{
InitializeComponent();
dbHelper= new DatabaseHelper(); // Instantiate database controller
}
private void someButton_Click(object sender, EventArgs e)
{
List<string> teamLeaders = new List<string>();
if (dbHelper.Open())
{
teamLeaders = dbConn.GetTeamLeaders(textboxTeam.Text);
dbHelper.Close();
}
else
{
return;
}
// all the code to use results
}
private void someOtherButton_Click(object sender, EventArgs e)
{
List abbreviation = string.Empty;
if (dbHelper.Open())
{
abbreviation = dbConn.GetTeamLeaders(textboxTeam.Text);
dbHelper.Close();
}
else
{
return;
}
// all the code to use results
}
</code></pre>
<p>Now I'm sure there are some very serious issues with how this is setup, but for me my biggest complaints are always having to open and close the connection.</p>
<p>My first move was to just move the open and close inside the DatabaseHelper methods, so each method (i.e. GetTeamLeaders) would call open and close in itself. But the problem was if it did actually fail to open it was really hard to feed it back up to the main program, which would try to run with whatever value the variable contained when it was made. I was thinking I would almost need an "out" bool that would tag along to see if the query completed, and could check make and check that anytime I used I needed to get something from the database, but I'm sure that has issues to.</p>
<p>Another big problem with this approach is anytime I want to make a call from another form, I have to either make another instance of the helper on that form, or pass a reference to the main one. (Currently my way around this is to retrieve all the information I would need beforehand in the <code>MainApp</code> and then just pass that to the new form). I'm not sure if when I rewrite this there's a good static way to set it up so that I can call it from anywhere.</p>
<p>So is there anything here worth keeping or does it all need to be stripped down and built back from scratch?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T20:34:18.183",
"Id": "35896",
"Score": "0",
"body": "You code does look clean on the surface but does suffer from a copy-paste problem. In the past I have written my own ORM-ish classes on top of an ODBC layer. I would gladly not have done that if I could choose any way to connect to a db. Are you able to use the Entity Framework?"
}
] |
[
{
"body": "<p>It seems that you are looking for <a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\">object-relational mapping</a> (ORM) framework. ORM framework is a recommended way to talk to the database. There are several frameworks out there including most known <a href=\"http://msdn.microsoft.com/en-us/data/ee712907\">Entity Framework</a> and <a href=\"http://en.wikipedia.org/wiki/NHibernate\">NHibernate</a>. It will require a bit of learning after direct <code>SqlConnection</code>/<code>SqlCommand</code>/<code>SqlDataReader</code>, but that would allow you to get rid of manual SQL string manipulations and concentrate on main business logic.</p>\n\n<blockquote>\n <p>anytime I want to make a call from another form, I have to either make another instance of the helper on that form, or pass a reference to the main one</p>\n</blockquote>\n\n<p>When using one of the ORMs mentioned above you will have a notion of \"session\" (NHibernate) or context (Entity Framework). Both terms refer to the same concept of unit-of-work + repository. These objects are very cheap to create, so usually you create one (sometimes more) session/context per form, and don't share them between forms.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T21:23:57.270",
"Id": "23286",
"ParentId": "23283",
"Score": "5"
}
},
{
"body": "<p>I'm going to try to attack from a perspective of <a href=\"http://rads.stackoverflow.com/amzn/click/0201485672\" rel=\"nofollow\">refactoring</a>. In my mind \"re-write\" means starting over.</p>\n\n<p>In <code>MainApp.cs</code> you want to say this:</p>\n\n<pre><code>teamLeaders = dbConn.GetTeamLeaders(textboxTeam.Text);\n</code></pre>\n\n<p>You're right that having MainApp having to know/control the sql connection is bad design. We're going to get rid of the <code>Open()</code> and <code>Close()</code> calls by being \"connection oriented\" instead of \"sql command oriented\". Keep reading for clarification...</p>\n\n<p>Then <code>GetTeamLeaders()</code> should set up the <code>SqlCommand</code> as it does now, but not execute the query. Instead pass that into some other <code>DataBaseHelper</code> method and ...</p>\n\n<p><strong>use \"using\" to get rid of Open / Close code</strong></p>\n\n<pre><code>protected bool ExecuteQuery(SqlCommand myCommand) {\n// return bool? void? I dunno. But I don't want MainApp dealing with\n// what's going on here. I suppose it depends on how you handle your exceptions.\n using (SqlConnection myconnect = new SqlConnection(myCommand)) {\n // other setup as needed \n\n try{\n myconnect.Open();\n mySqlCmd.ExecuteNonQuery(); // or whatever\n }catch (Exception except) { // really? catch specific SqlConnection exceptions to gather better \"telemetry\"\n\n }catch (Exception except) {} // but also have a catch-all.\n }finally{\n myconnect.Close(); // it's automatic, but i do this anyway.\n }\n } // using\n}\n</code></pre>\n\n<p>It's my understanding that .NET handles connection pooling automatically and I've never worried about it in my experience.</p>\n\n<p>My spidey sense tells me that with proper refactoring, all your exception handling will be right here.</p>\n\n<p><strong>Follow-on Refactoring - getting business logic out of DataBaseHelper</strong></p>\n\n<p>With the above in place, I can see the query string in <code>GetTeamLeaders</code>, and similar methods you must have in <code>DataBaseHelper.cs</code> pulled out. Now <code>DataBaseHelper.cs</code> is free of all \"business context\". </p>\n\n<p>If the SqlCommand setup is very customized for each query, then perhaps <code>GetTeamLeaders</code> becomes a whole new class; very possibly derived from an abstract class with standard/common <code>SqlCommand</code> setup. Oh, you can use the same <code>SqlCommand</code> object with different parameter settings; Remember that parameters is a collection on <code>SqlCommand</code> and so you can have have custom methods to set up <code>ParameterCollection</code>s and pass that into a <code>SqlCommand</code> object used over and over, living in that abstract class I mentioned.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:00:51.747",
"Id": "36128",
"Score": "0",
"body": "I like this a lot, as I don't think the rest of the developers would appreciate switching everything to a new ORM.\n\nMy one concern would still be when the database connection fails (network issues are a bit commonplace around here, which is why MainApp is currently in charge of opening the connection so it verify before running a slew of things against a default return value.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T20:21:58.723",
"Id": "36175",
"Score": "0",
"body": "@Wrightboy, try/catch-n-rethrow! Catch \"at the source\", add detail to the `Exception.Data` property. Rethrow it and all exceptions, and catch them at the top of your code, ideally in one spot. I wrote a `Main()` that just wrapped a call to the \"MainApp\" in a try catch. I liked that a lot... Log error, display message, give option to continue or quit; as appropriate. Don't over engineer with exceptional exception handling on an exception by exception basis."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T17:02:50.773",
"Id": "36242",
"Score": "0",
"body": "I always hear about this centralized exception handling, but have never actually seen it or how to easily set it up. I guess this is as good as time as any to finally undertake it. Thank you!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T18:19:26.093",
"Id": "23360",
"ParentId": "23283",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23360",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T20:09:21.517",
"Id": "23283",
"Score": "2",
"Tags": [
"c#",
".net",
"sql"
],
"Title": "Improving the way a C# application communicates with a SQL database (Via SqlConnection)"
}
|
23283
|
<p>I have recently implemented my SQLite helper class that supports SQLite in a memory class to be opened to not to be lost. Please review it and tell me if there is a coding problem and tell me what to do to prevent\fix it.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
namespace SQLite
{
public class SqLiteDatabase : IDisposable
{
private readonly SQLiteConnection _dbConnection;
/// <summary>
/// Default Constructor for SQLiteDatabase Class.
/// </summary>
public SqLiteDatabase()
{
_dbConnection = new SQLiteConnection("Data Source=default.s3db");
}
/// <summary>
/// Single Param Constructor to specify the datasource.
/// </summary>
/// <param name="datasource">The data source. Use ':memory:' for in memory database.</param>
public SqLiteDatabase(String datasource)
{
_dbConnection = new SQLiteConnection(string.Format("Data Source={0}", datasource));
}
/// <summary>
/// Single Param Constructor for specifying advanced connection options.
/// </summary>
/// <param name="connectionOpts">A dictionary containing all desired options and their values.</param>
public SqLiteDatabase(Dictionary<String, String> connectionOpts)
{
String str = connectionOpts.Aggregate("",
(current, row) =>
current + String.Format("{0}={1}; ", row.Key, row.Value));
str = str.Trim().Substring(0, str.Length - 1);
_dbConnection = new SQLiteConnection(str);
}
#region IDisposable Members
public void Dispose()
{
if (_dbConnection != null)
_dbConnection.Dispose();
GC.Collect();
GC.SuppressFinalize(this);
}
#endregion
public bool OpenConnection()
{
try
{
if (_dbConnection.State == ConnectionState.Closed)
_dbConnection.Open();
return true;
}
catch (Exception e)
{
Console.WriteLine("SQLite Exception : {0}", e.Message);
}
return false;
}
public bool CloseConnection()
{
try
{
_dbConnection.Close();
_dbConnection.Dispose();
}
catch (Exception e)
{
Console.WriteLine("SQLite Exception : {0}", e.Message);
}
return false;
}
/// <summary>
/// Gets the specified table from the Database.
/// </summary>
/// <param name="sql">The table to retrieve from the database.</param>
/// <returns>A DataTable containing the result set.</returns>
public DataTable GetDataTable(string sql)
{
var table = new DataTable();
try
{
using (SQLiteTransaction transaction = _dbConnection.BeginTransaction())
{
using (var cmd = new SQLiteCommand(_dbConnection) {Transaction = transaction, CommandText = sql})
{
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
table.Load(reader);
transaction.Commit();
}
}
}
return table;
}
catch (Exception e)
{
Console.WriteLine("SQLite Exception : {0}", e.Message);
}
finally
{
table.Dispose();
}
return null;
}
/// <summary>
/// Executes a NonQuery against the database.
/// </summary>
/// <param name="sql">The SQL to execute.</param>
/// <returns>A double containing the time elapsed since the method has been executed.</returns>
public double? ExecuteNonQuery(string sql)
{
Stopwatch s = Stopwatch.StartNew();
try
{
using (SQLiteTransaction transaction = _dbConnection.BeginTransaction())
{
using (var cmd = new SQLiteCommand(_dbConnection) {Transaction = transaction})
{
foreach (string line in new LineReader(() => new StringReader(sql)))
{
cmd.CommandText = line;
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
}
s.Stop();
return s.Elapsed.TotalMinutes;
}
catch (Exception e)
{
Console.WriteLine("SQLite Exception : {0}", e.Message);
}
return null;
}
/// <summary>
/// Gets a single value from the database.
/// </summary>
/// <param name="sql">The SQL to execute.</param>
/// <returns>Returns the value retrieved from the database.</returns>
public string ExecuteScalar(string sql)
{
try
{
using (SQLiteTransaction transaction = _dbConnection.BeginTransaction())
{
using (var cmd = new SQLiteCommand(_dbConnection) {Transaction = transaction, CommandText = sql})
{
object value = cmd.ExecuteScalar();
transaction.Commit();
return value != null ? value.ToString() : "";
}
}
}
catch (Exception e)
{
Console.WriteLine("SQLite Exception : {0}", e.Message);
}
return null;
}
/// <summary>
/// Updates specific rows in the database.
/// </summary>
/// <param name="tableName">The table to update.</param>
/// <param name="data">A dictionary containing Column names and their new values.</param>
/// <param name="where">The where clause for the update statement.</param>
/// <returns>A boolean true or false to signify success or failure.</returns>
public bool Update(String tableName, Dictionary<String, String> data, String where)
{
string vals = "";
if (data.Count >= 1)
{
vals = data.Aggregate(vals,
(current, val) =>
current +
String.Format(" {0} = '{1}',", val.Key.ToString(CultureInfo.InvariantCulture),
val.Value.ToString(CultureInfo.InvariantCulture)));
vals = vals.Substring(0, vals.Length - 1);
}
try
{
ExecuteNonQuery(String.Format("update {0} set {1} where {2};", tableName, vals, where));
return true;
}
catch (Exception e)
{
Console.WriteLine("SQLite Exception : {0}", e.Message);
}
return false;
}
/// <summary>
/// Deletes specific rows in the database.
/// </summary>
/// <param name="tableName">The table from which to delete.</param>
/// <param name="where">The where clause for the delete.</param>
/// <returns>A boolean true or false to signify success or failure.</returns>
public bool Delete(String tableName, String where)
{
try
{
ExecuteNonQuery(String.Format("delete from {0} where {1};", tableName, where));
return true;
}
catch (Exception e)
{
Console.WriteLine("SQLite Exception : {0}", e.Message);
}
return false;
}
/// <summary>
/// Inserts new data to the database.
/// </summary>
/// <param name="tableName">The table into which the data will be inserted.</param>
/// <param name="data">A dictionary containing Column names and data to be inserted.</param>
/// <returns>A boolean true or false to signify success or failure.</returns>
public bool Insert(String tableName, Dictionary<String, String> data)
{
string columns = "";
string values = "";
foreach (var val in data)
{
columns += String.Format(" {0},", val.Key);
values += String.Format(" '{0}',", val.Value);
}
columns = columns.Substring(0, columns.Length - 1);
values = values.Substring(0, values.Length - 1);
try
{
ExecuteNonQuery(String.Format("insert into {0}({1}) values({2});", tableName, columns, values));
return true;
}
catch (Exception e)
{
Console.WriteLine("SQLite Exception : {0}", e.Message);
}
return false;
}
/// <summary>
/// Wipes all the data from the database.
/// </summary>
/// <returns>A boolean true or false to signify success or failure.</returns>
public bool WipeDatabase()
{
DataTable tables = null;
try
{
tables = GetDataTable("select NAME from SQLITE_MASTER where type='table' order by NAME;");
foreach (DataRow table in tables.Rows)
{
WipeTable(table["NAME"].ToString());
}
return true;
}
catch (Exception e)
{
Console.WriteLine("SQLite Exception : {0}", e.Message);
}
finally
{
if (tables != null) tables.Dispose();
}
return false;
}
/// <summary>
/// Wipes all the data from the specified table.
/// </summary>
/// <param name="table">The table to be wiped.</param>
/// <returns>A boolean true or false to signify success or failure.</returns>
public bool WipeTable(String table)
{
try
{
ExecuteNonQuery(String.Format("delete from {0};", table));
return true;
}
catch (Exception e)
{
Console.WriteLine("SQLite Exception : {0}", e.Message);
}
return false;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T20:56:50.047",
"Id": "35899",
"Score": "1",
"body": "`throw new Exception(e.Message);` is just bad. I no longer have Visual Studio, so I cannot list all of the problems. You do have a few."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T20:58:55.413",
"Id": "35900",
"Score": "0",
"body": "@Leonid So what do you suggest instead ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T21:00:14.150",
"Id": "35901",
"Score": "0",
"body": "In some places you should not catch it at all; otherwise read this carefully - http://stackoverflow.com/questions/178456/what-is-the-proper-way-to-re-throw-an-exception-in-c"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T21:03:48.873",
"Id": "35902",
"Score": "0",
"body": "@Leonid : Srry but i can't get the point you are talking about... you mean that there is some errors for sqlite that i might ignore and don't catch ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T21:05:44.830",
"Id": "35903",
"Score": "2",
"body": "The following code is useless: `catch (Exception e) { throw new Exception(e.Message); }`. It has almost the same effect as not having the try/catch at all (unless you also have a finally clause - in that case you do need a `try`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T21:07:42.583",
"Id": "35904",
"Score": "0",
"body": "@Leonid : now i got your point you mean that if i am throwing the exception why am i using try catch at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T12:55:38.033",
"Id": "45314",
"Score": "1",
"body": "`catch (Exception e) { Console.WriteLine(\"SQLite Exception : {0}\", e.Message);` This is bad. If it is reused in a GUI application then there is no console attached (and only can be attached via some API calls). You should either throw those exceptions or accept some sort of Logger."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:33:47.290",
"Id": "80285",
"Score": "0",
"body": "Any final solution with full source code sample ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-09T22:09:49.440",
"Id": "269615",
"Score": "0",
"body": "Just wondering if you could share what you ended up using, it would be a great help for all."
}
] |
[
{
"body": "<p>In <code>Dispose()</code>:</p>\n\n<ol>\n<li>You are calling <code>GC.Collect()</code> which isn't necessarily need unless it is very important to collect all inaccessible memory when disposing.</li>\n<li><code>GC.SuppressFinalize(this)</code> isn't need because the class don't have a finalizer/deconstructor</li>\n</ol>\n\n<p>In <code>CloseConnection()</code> you are always returning false. Why not make it void?</p>\n\n<p>You are handling a lot of exceptions in this \"framework\", why not let the \"client\" handle the errors? It will make you code more maintainable and easy to read. It would remove a bunch of return and try..catch statements (as discussed in the comments), and allows the \"client\" to handle the exceptions differently if needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T23:00:22.597",
"Id": "35907",
"Score": "0",
"body": "You mean that i remove the try catch from the database sided codes ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T23:16:02.053",
"Id": "35908",
"Score": "2",
"body": "Yes, fx. in `OpenConnection()` why not remove the try..catch completely and let the user handle the exception the way they want to?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T22:52:07.567",
"Id": "23290",
"ParentId": "23284",
"Score": "3"
}
},
{
"body": "<p>It looks to be a reasonable design and I am reworking mine a bit based on some ideas I have seen here. But I don't like the idea of not being able to unit test, which this design would not allow for. </p>\n\n<p>I also do not like to see hardcoded values in the helper class. Those should come in from the outside. I do agree with the other posts that are saying not to do the try catch here, as it hides it from the call code. At this level in a framework, you'd not have try/catch blocks and you let the errors simply roll up. </p>\n\n<p>I'd recommend adding dependency injection. Then in your application that uses this framework, simply define the objects there, and everything will pass in. This will allow you to mock the class and add true unit tests. Currently you cannot do that.</p>\n\n<p>Also, if you wanted to use this helper for an application with multiple database files, you'd have to create multiple helpers like this. A better approach would be to pass it in through construction injection, and allow the helper to be used with any database.</p>\n\n<p>Also, I am not sure what the point is of a transaction on the GetDataTable() method. When you commit this, what is being committed? It is a read-only process.</p>\n\n<p>Here's my winForm code I used to setup the database. This is the only place in the code where the database is defined. If I wanted a second database as well, I could simply create a second _dbConnection object using a different name.</p>\n\n<p>I am using a DAO class per database I am connecting to. So my form talks to the DAO, my DAO is the only way to get to the SQLite helper class. I setup the db connection in the form, and pass it in. That way I can mock the DAO class for unit testing without dependencies on the database itself. I have not, but I will implement interfaces as needed. But I still need more time to work through this is bit.</p>\n\n<p>So this is my current approach after about 12-hours of working with SQLite. So take that for what it is worth, as I am new to SQLite.</p>\n\n<p>UPDATE: As I was writing this I desided to change my connection to just a connection string, that way my forms could work with Access, SQLite, or SQL Server by just using different DAO or Helper classes.</p>\n\n<pre><code> private readonly SQLiteConnection _dbConnection = new SQLiteConnection(\"Data Source=LanguageTutor.db;Version=3;New=False;Compress=True;\"); \n private readonly Dao _dao;\n\n public Form2()\n {\n InitializeComponent();\n _dao = new Dao(_dbConnection);\n }\n</code></pre>\n\n<p>Then my DAO class</p>\n\n<pre><code> public class Dao\n {\n\n private readonly SqLiteHelper _sql;\n private readonly SQLiteConnection _dbConnection;\n\n public Dao(SQLiteConnection dbConnection)\n {\n _dbConnection = dbConnection;\n _sql = new SqLiteHelper(_dbConnection);\n }\n</code></pre>\n\n<p>Now here's how I reworked my own SQLite helper class. This just covers the constructors and dependency injection and I took the dictionary one from you as well.</p>\n\n<pre><code> private readonly SQLiteConnection _dbConnection; \n\n #region Constructors\n\n /// <summary>\n /// Default Constructor for SQLiteDatabase Class.\n /// </summary>\n public SqLiteHelper(SQLiteConnection sqLiteConnection)\n {\n _dbConnection = sqLiteConnection;\n }\n\n public SqLiteHelper(SQLiteConnection sqLiteConnection, Dictionary<String, String> connectionOpts)\n {\n String str = connectionOpts.Aggregate(\"\", (current, row) => current + String.Format(\"{0}={1}; \", row.Key, row.Value));\n str = str.Trim().Substring(0, str.Length - 1);\n\n _dbConnection = sqLiteConnection;\n _dbConnection.ConnectionString = str;\n }\n\n #endregion\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-07-22T02:49:23.200",
"Id": "28800",
"ParentId": "23284",
"Score": "3"
}
},
{
"body": "<p><strong>IDisposable implementation</strong></p>\n\n<p>Implementing IDisposable is a little more complicated than just Dispose(). You will want to override at least the protected virtual void Dispose(bool disposing) method. For details see Jon Skeet's answer here: <a href=\"https://stackoverflow.com/questions/574019/calling-null-on-a-class-vs-dispose/574659#574659\">https://stackoverflow.com/questions/574019/calling-null-on-a-class-vs-dispose/574659#574659</a></p>\n\n<p><strong>Exception handling</strong></p>\n\n<p>I personally dislike bool return values to report success or error. It makes me write:</p>\n\n<pre><code>using (SqLiteDatabase db = new SqLiteDatabase())\n{\n if (!db.OpenConnection())\n // handle error\n return;\n\n DataTable table = db.GetDataTable(\"table\");\n if (table == null)\n // handle error\n return;\n\n string value = db.ExecuteScalar(statement);\n if (value == null)\n // handle error\n return;\n\n if (!db.Update(...))\n // handle error\n return\n}\n</code></pre>\n\n<p>Not only the error conditions are inconsistent (sometimes false is returned, other times null), it's quite easy to ignore the return values.</p>\n\n<p>I prefer</p>\n\n<pre><code>try\n{\n using (SqLiteDatabase db = new SqLiteDatabase())\n {\n db.OpenConnection();\n DataTable table = db.GetDataTable(\"table\");\n string value = db.ExecuteScalar(statement);\n db.Update(...)\n }\n}\ncatch (SqLite.FailedToOpenDatabaseException e)\n{\n // handle\n}\ncatch (SqLite.TableDoesNotExistException e)\n{\n // handle\n}\ncatch (SqLite.FailedToUpdateTable e)\n{\n // handle\n}\n</code></pre>\n\n<p>(given that Dispose closes the connection)</p>\n\n<p><strong>Loose ends</strong></p>\n\n<ul>\n<li>I would't include timing/profiling in ExecuteNonQuery as it does not really fit with the rest of the interface. </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T06:49:39.687",
"Id": "28805",
"ParentId": "23284",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T20:42:05.087",
"Id": "23284",
"Score": "3",
"Tags": [
"c#",
"sqlite"
],
"Title": "SQLite helper class"
}
|
23284
|
<p>I'm going to have a lot of integer values, and at any value change I might need to update any number of UI elements, other values which are computed from the first ones, etc. Sounds like time for the Visitor pattern, but I'm new to Java (more comfortable in C++). I have:</p>
<pre><code>import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
public abstract class Value {
static public interface Listener {
public abstract void valueChanged(Value val);
};
public Value(int init_val) {
mVal = init_val;
mListeners = new ArrayList<WeakReference<Listener>>();
}
public int getValue() { return mVal; }
public void setValue(int val) {
mVal = val;
Iterator<WeakReference<Listener>> iter = mListeners.iterator();
while (iter.hasNext()) {
Listener listen = iter.next().get();
if (listen == null)
iter.remove();
else
listen.valueChanged(this);
}
}
public void addListener(Listener listen) {
cleanListeners();
mListeners.add(new WeakReference<Listener>(listen));
}
private void cleanListeners() {
Iterator<WeakReference<Listener>> iter = mListeners.iterator();
while (iter.hasNext()) {
if (iter.next().get() == null)
iter.remove();
}
}
private int mVal;
private ArrayList<WeakReference<Listener>> mListeners;
};
</code></pre>
<p>I'm wondering if there are technical, style, or common practice issues, specifically relating to:</p>
<ul>
<li>Is this a good and correct way to use <code>WeakReference</code>s, or is there a simpler way? I don't want the <code>Value</code> to prevent its listeners from getting cleaned up, or to manually break links when a listener is no longer needed by the UI/calculations/whatever.</li>
<li>Use the interface <code>List<...></code> or the actual implementation type <code>ArrayList<...></code> when declaring the member <code>mListeners</code>?</li>
<li>Initialize <code>mListeners</code> with an empty list at the member declaration, or in the constructor?</li>
</ul>
<p>Other comments and suggestions are welcome too.</p>
|
[] |
[
{
"body": "<p><strong>Addressing your specific questions</strong></p>\n\n<blockquote>\n <ul>\n <li>Is this a good and correct way to use WeakReferences, or is there a simpler way? I don't want the Value to prevent its listeners from getting cleaned up, or to manually break links when a listener is no longer needed by the UI/calculations/whatever.</li>\n </ul>\n</blockquote>\n\n<p>See <a href=\"https://stackoverflow.com/questions/6337760/pros-and-cons-of-listeners-as-weakreferences\">\"Pros and Cons of Listeners as WeakReferences\"</a> on StackOverflow. BegemoT's <a href=\"https://stackoverflow.com/a/6451114/277307\">answer</a> explains how using weak references changes the semantics. To prevent anyone from being surprised when using an anonymous class listener (which are common in UI frameworks like SWT), I recommend clearly documenting this semantic on the <code>addListener</code> method. Also, in my experience, weak references are not as well known by many developers which further reiterates the need for documentation.</p>\n\n<p>There's other fascinating corners to explore in weak references including <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/WeakHashMap.html\" rel=\"nofollow noreferrer\"><code>WeakHashMap</code></a>, which uses a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/ref/ReferenceQueue.html\" rel=\"nofollow noreferrer\"><code>ReferenceQueue</code></a> to cleanup, as discussed another SO <a href=\"https://stackoverflow.com/questions/9166610/weakhashmap-and-strongly-referenced-value\">question</a> with some facinating links. If you dive into WeakHashMap (perhaps wrapped as a Set using <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#newSetFromMap(java.util.Map)\" rel=\"nofollow noreferrer\"><code>Collections.newSetFromMap</code></a>) at some point, as noted, Guava (Google's common java library) makes a case for using their <a href=\"http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/MapMaker.html\" rel=\"nofollow noreferrer\"><code>MapMaker</code></a> instead.</p>\n\n<p>Because of their relative obscurity and behavior depending on when the GC will run, I personally shy away from weak references and use them sparingly. </p>\n\n<blockquote>\n <ul>\n <li>Use the interface List<...> or the actual implementation type ArrayList<...> when declaring the member mListeners?</li>\n </ul>\n</blockquote>\n\n<p>See <a href=\"https://stackoverflow.com/questions/2279030/type-list-vs-type-arraylist-in-java\">\"Type List vs type ArrayList in Java\"</a> on StackOverflow. Declaring to the interface (<code>List<...></code>) is to be preferred.</p>\n\n<blockquote>\n <ul>\n <li>Initialize mListeners with an empty list at the member declaration, or in the constructor?</li>\n </ul>\n</blockquote>\n\n<p>See <a href=\"https://stackoverflow.com/questions/3918578/should-i-initialize-variable-within-constructor-or-outside-constructor\">\"Should I initialize variable within constructor or outside constructor\"</a> on StackOverflow. Where you can, I recommend initializing at declaration for clarity.</p>\n\n<p><strong>Additional Thoughts</strong></p>\n\n<ul>\n<li>Java already has an implementation for the Observer pattern in <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Observable.html\" rel=\"nofollow noreferrer\"><code>java.util.Observable</code></a>. This has found to be wanting in that you have to extend <code>Observable</code>. As suggested in <a href=\"https://stackoverflow.com/questions/10218895/alternative-to-javas-observable-class\">\"Alternative to Java's Observable class?\"</a>, Guava's <a href=\"http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/eventbus/EventBus.html\" rel=\"nofollow noreferrer\"><code>EventBus</code></a> is a good alternative. I've used it before and recommend it for its ease of use and aide in decoupling code.</li>\n<li>Declare fields as final where you can. Use final fields where you can to help prevent potential issues in mutability. Qualify <code>mListeners</code> as <code>final</code>.</li>\n<li>I was surprised to see the fields at the bottom of the class. For customary readability, fields are typically declared prior to the constructors.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T06:50:09.923",
"Id": "23300",
"ParentId": "23288",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T21:59:31.163",
"Id": "23288",
"Score": "2",
"Tags": [
"java",
"design-patterns",
"weak-references"
],
"Title": "Observer pattern in Java"
}
|
23288
|
<p>I am working on a multithreaded project in which each thread will <code>randomly find columns for that table</code> and I will be using those columns in my <code>SELECT sql query</code> and then I will be executing that SELECT sql query. AFter exectuing that query, I will be looping through the result set and will add the data for each columns into <code>List<String></code>.</p>
<p>Here <code>columnsList</code> will contains <code>columns</code> delimited by <code>comma</code>. For example-</p>
<p><code>col1, col2, col3</code></p>
<p>Below is my code. </p>
<pre><code>class ReadTask implements Runnable {
public ReadTask() {
}
@Override
public run() {
...
while ( < 60 minutes) {
.....
final int id = generateRandomId(random);
final String columnsList = getColumns(table.getColumns());
final String selectSql = "SELECT " + columnsList + " from " + table.getTableName() + " where id = ?";
resultSet = preparedStatement.executeQuery();
List<String> colData = new ArrayList<String>(columnsList.split(",").length);
boolean foundData = false;
if (id >= startValidRange && id <= endValidRange) {
if (resultSet.next()) {
foundData = true;
for (String column : columnsList.split(",")) {
colData.add(resultSet.getString(column.trim()));
}
resultSet.next();//do I need this here?
}
} else if (resultSet.next()) {
addException("Data Present for Non Valid ID's", Read.flagTerminate);
}
....
}
}
private static void addException(String cause, boolean flagTerminate) {
AtomicInteger count = exceptionMap.get(cause);
if (count == null) {
count = new AtomicInteger();
AtomicInteger curCount = exceptionMap.putIfAbsent(cause, count);
if (curCount != null) {
count = curCount;
}
}
count.incrementAndGet();
if(flagTerminate) {
System.exit(1);
}
}
}
</code></pre>
<p><strong>Problem Statement:-</strong></p>
<p>After executing the <code>SELECT</code> sql query. Below are my two scenarios-</p>
<ol>
<li>I need to see whether the id is between the valid range. If it is between the Valid Range then check whether <code>resultSet</code> has any data or not. If it has data then loop around the <code>resultSet</code> using the <code>columns</code> from the <code>columnsList</code> and start adding it in <code>coldData</code> list of String.</li>
<li>else if id is not in the valid range then I need to check I am not getting any data back from the <code>resultSet</code>. But somehow if I am getting the data back and flag is true to stop the program, then exit the program. Else if I am getting the data back but flag is false to stop the program, then count how many of those happening. So for this, I have created <code>addException</code> method.</li>
</ol>
<p>Can anyone help me out whether the way I am doing here for my above two <code>scenarios</code> is right or not? It looks like, I can improve the <code>if/else loop</code> code more I guess for my above two scenario.</p>
|
[] |
[
{
"body": "<p>I am not that familiar with JDBC, but I think the method you search for is: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#isBeforeFirst%28%29\" rel=\"nofollow\">isBeforeFirst</a>: \"true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no rows\"</p>\n\n<p>This does not modify the results cursor then.</p>\n\n<hr>\n\n<pre><code>if (id >= startValidRange && id <= endValidRange)\n</code></pre>\n\n<p>I would change it to:</p>\n\n<pre><code>if (startValidRange <= id && id <= endValidRange)\n</code></pre>\n\n<p>Only a small change, but increase readability a lot (at least for me)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T17:14:11.683",
"Id": "23326",
"ParentId": "23293",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23326",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T02:30:37.170",
"Id": "23293",
"Score": "1",
"Tags": [
"java",
"optimization",
"multithreading"
],
"Title": "Looping through the ResultSet efficiently and the add the values for columns in List<String>"
}
|
23293
|
<p>I am tring to <code>count</code> the number of <code>exceptions</code> happening and log those <code>exceptions</code> as well. So what I did is, I created one method <code>addException</code> in which I am counting all the exceptions. </p>
<p><code>addException</code> method accepts two parameters, <code>one is the String</code>, and other is the <code>boolean flag</code> which means whether we want to terminate the program or not because of any exceptions. Meaning, if that flag is true, then I need to terminate the program whenever there are any exceptions.</p>
<p>So if you take a look into my below <code>catch</code> block, I have <code>addException</code> method call for counting the exceptions and below that method call I am logging the exceptions as well.</p>
<pre><code>catch (ClassNotFoundException e) {
addException(e.getCause() != null ? e.getCause().toString() : e.toString(), Read.flagTerminate);
LOG.error("Threw a ClassNotFoundException in " + getClass().getSimpleName(), e);
} catch (SQLException e) {
addException(e.getCause() != null ? e.getCause().toString() : e.toString(), Read.flagTerminate);
//DAMN! I'm not....
LOG.error("Threw a SQLException while making connection to database in " + getClass().getSimpleName(), e);
}
/**
* A simple method that will add the count of exceptions and name of
* exception to a map
*
* @param cause
* @param flagTerminate
*/
private static void addException(String cause, boolean flagTerminate) {
AtomicInteger count = exceptionMap.get(cause);
if (count == null) {
count = new AtomicInteger();
AtomicInteger curCount = exceptionMap.putIfAbsent(cause, count);
if (curCount != null) {
count = curCount;
}
}
count.incrementAndGet();
if(flagTerminate) {
System.exit(1);
}
}
</code></pre>
<p><strong>Problem Statement:-</strong></p>
<p>Now what I am looking for is- </p>
<p>Is there any more cleaner way of doing the same thing? Meaning right now I am counting the exceptions in a method and then printing out the exceptions in the next line inside the catch block. </p>
<p>Is it possible to do the both of the things in the same <code>addException</code> method? And if the flag is true to terminate the program, then terminate the program with the proper logging as well.</p>
<p>What could be the best way to re write <code>addException method</code> do this?</p>
|
[] |
[
{
"body": "<blockquote>\n <p>Is there any more cleaner way of doing the same thing? Meaning right now I am counting the exceptions in a method and then printing out the exceptions in the next line inside the catch block. \n Is it possible to do the both of the things in the same addException method?</p>\n</blockquote>\n\n<p>It depends. You could configure the logger and add a new a appender. Then your logger serves two appenders: The (probably) println and the counting.<br>\nOtherwise, you could add the log call inside the addException method (could be renamed to <code>handleException(...)</code> then).</p>\n\n<blockquote>\n <p>And if the flag is true to terminate the program, then terminate the program with the proper logging as well.</p>\n</blockquote>\n\n<p>I highly suggest to avoid boolean flag arguments. If you have a public api, this suggestion is a must. Look at java for a lot of bad examples.<br>\nUse two methods:</p>\n\n<pre><code>private static void addException(String cause) {\n ...\n}\n\nprivate static void addExceptionAndTerminate(String cause) {\n addException(...);\n System.exit(1);\n}\n</code></pre>\n\n<p>(And I do not see the point of adding the exception if you terminate anyway, but it could be for some multithreading things.)</p>\n\n<blockquote>\n <p>What could be the best way to re write addException method do this?</p>\n</blockquote>\n\n<p>I would change the method signature from <code>String, Boolean</code> to <code>Exception</code> and put all exceptions inside a synchronized list.<br>\nOnly if I want to get some statistics, I would start to parse them. Which makes the live easier for everyone who is using this.<br>\nAt the moment, the functionality depends on the format of the string. If you or someone else, does not use the correct format, it does not work.\ntherefore, you sould document this at least in the javadoc. And the correct formatting is a pain, noone will like to write like this.<br>\nAnd I am not sure if the implementation for concurrent map access is correct.</p>\n\n<p>If you just allow an exception object, noone has to care about formatting, the synchronization is a lot easier (just add to the list) and you have all the freedom in some other method how to count, parse \nand do whatever you want with this exceptions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T16:54:47.560",
"Id": "23325",
"ParentId": "23296",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23325",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T05:20:10.977",
"Id": "23296",
"Score": "1",
"Tags": [
"java",
"multithreading"
],
"Title": "Log and Count the exception in a Single method"
}
|
23296
|
<p>This question was put forward by my senior to draw a hollow rectangle in C#, and with the condition that the rows and column would be specified by the user. I was stuck at first, but tried to code and after several hours I realized how it would be done, and then I accomplished the task.</p>
<p>I would like to share my code, as the beginners may get help out of it, and the experts can also look and propose, if they know any other alternative solution which would be composed of less code.</p>
<pre><code>class Program
{
static void Main(string[] args)
{
int arg1;
int arg2;
arg1 =Convert.ToInt16(Console.ReadLine());
Console.ReadLine();
arg2 = Convert.ToInt16(Console.ReadLine());
// Console.WriteLine(arg1 + " " + arg2);
for (int row = 1; row <= arg1; row++)
{
if (row == 1 || row == arg1)
{
for (int col = 1; col <= arg2; col++)
{
Console.Write("*");
}
Console.WriteLine();
}
if (row < arg1 && row < arg1-1)
{
Console.Write("*");
for (int i = 0; i < arg2-2; i++)
{
Console.Write(" ");
}
Console.Write("*");
Console.WriteLine();
}
}
Console.ReadKey();
// Console.ReadKey();
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code> static void DrawLine(int w, char ends, char mids)\n {\n Console.Write(ends);\n for (int i = 1 ; i < w-1 ; ++i)\n Console.Write(mids);\n Console.WriteLine(ends);\n }\n\n static void DrawBox(int w, int h)\n {\n DrawLine(w, '*', '*');\n for (int i = 1; i < h-1; ++i)\n DrawLine(w, '*', ' ');\n DrawLine(w, '*', '*');\n }\n\n static void Main()\n {\n DrawBox(10, 10);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T06:42:05.583",
"Id": "35919",
"Score": "0",
"body": "Thats quite a good code, composed of less number of lines, and reusable too. Good one jaket ! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T07:01:20.317",
"Id": "35925",
"Score": "3",
"body": "@jaket I think it would be better if you explained what does your code improve and how."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T07:18:20.837",
"Id": "35927",
"Score": "0",
"body": "@svick Thats a good comment you posted, for understanding the code of jaket further."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T14:26:59.760",
"Id": "35936",
"Score": "3",
"body": "Instead of using a `for` loop in the `DrawLine` method, I would recommend simply calling `Console.Write(new string(mids, w-2));`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T06:36:10.267",
"Id": "23299",
"ParentId": "23298",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23299",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T05:41:41.690",
"Id": "23298",
"Score": "3",
"Tags": [
"c#",
"console"
],
"Title": "Drawing a hollow rectangle of rows and column provided by the console application"
}
|
23298
|
<p>I'm new to PHP and I would like to redirect the visitors of my website based on their operating system.
Below is my solution. Is there anything that needs to be optimized?</p>
<pre><code><?php
// MOBILE
$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
$blackberry = strpos($_SERVER['HTTP_USER_AGENT'],"BB10");
$ios = strpos($_SERVER['HTTP_USER_AGENT'],"iOS");
// DESKTOP
$windows = strpos($_SERVER['HTTP_USER_AGENT'],"Windows");
$mac = strpos($_SERVER['HTTP_USER_AGENT'],"Mac");
// REDIRECTS
// MOBILE
if ($android == true)
{
header('Location: http://www.example.com/android');
}
else if ($blackberry == true)
{
header('Location: http://www.example.com/blackberry');
}
else if ($ios == true)
{
header('Location: http://www.example.com/ios');
}
// DESKTOP
else if ($windows == true)
{
header('Location: http://www.example.com/windows');
}
else if ($mac == true)
{
header('Location: http://www.example.com/mac');
}
?>
</code></pre>
<p>Thanks. Patrick</p>
|
[] |
[
{
"body": "<p>Before anything, I'll let you search on the web why this might not be such a good idea and I'll just focus on the code.</p>\n\n<ul>\n<li>You probably should retrieve <code>$_SERVER['HTTP_USER_AGENT']</code> and store it in a variable in order to avoid repeated code. Also, you might want to check if the variable is set properly before accessing it to avoid warnings/errors.</li>\n<li>You can rewrite <code>if ($variable == true)</code> as <code>if ($variable)</code></li>\n<li>You could avoid the boilerplate and repeated code if you were storing the interesting parts of your logic in an array and write the common parts only once :</li>\n</ul>\n\n<pre>\n $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';\n $redir = array(\n \"Android\" => 'android',\n \"BB10\" => 'blackberry',\n \"iOS\" => 'ios',\n \"Windows\" => 'windows',\n \"Mac\" => 'mac'\n );\n if (isset($redir[$ua]))\n {\n header('Location: http://www.example.com/' . $redir[$ua]);\n }\n</pre>\n\n<p>I hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T01:26:13.513",
"Id": "36078",
"Score": "0",
"body": "I agree with Josay, this is not a good idea. You might want to look into responsive webdesign."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T12:43:30.010",
"Id": "23307",
"ParentId": "23306",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23307",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T12:20:17.967",
"Id": "23306",
"Score": "1",
"Tags": [
"php",
"optimization"
],
"Title": "PHP - Redirect based on OS optimization"
}
|
23306
|
<p>I wrote something to the effect of a <code>try</code> <code>catch</code> <code>finally</code> statement helper in functional style so that I can shorten much of the code I'm writing for my Service Layer that connects to an SQL database.</p>
<p>Because of that, I found myself needing to code up a lot of <code>try</code> <code>catch</code> statements. I found <a href="http://blog.markrendle.net/2011/02/06/ddd9-teaching-jon-skeet-c-and-fun-with-exceptions/" rel="noreferrer">this article</a> this article on a functional exception handling and looked at <a href="https://bitbucket.org/markrendle/functionalalchemy" rel="noreferrer">the author's Bitbucket source</a> and was inspired to write the following with a differing style from that of the author but, suiting my purposes. I'm certainly not an expert and I could be totally wrong in my approach here. I'm looking for "yes" or "no" and "here is why".</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common.Helper
{
public static class FunctionalHelpers
{
public static void TryCatch<TE>(Action tryAction, Action<Exception> handler)
where TE : Exception
{
try { tryAction(); }
catch (TE ex)
{
handler(ex);
}
}
public static void TryCatch<TArg, TE>(Action<TArg> tryAction, TArg args, Action<Exception> handler)
where TE : Exception
{
try { tryAction(args); }
catch (TE ex)
{
handler(ex);
}
}
public static void TryCatchFinally<TE>(Action tryAction, Action<Exception> CatchAction, Action FinallyAction)
where TE : Exception
{
try
{
tryAction();
}
catch (TE t)
{
CatchAction(t);
}
finally
{
FinallyAction();
}
}
public static void TryCatchFinallyUsing<TE, TUsing>(Action<TUsing> tryAction, Action<Exception> CatchAction, Action<TUsing> FinallyAction, TUsing arg)
where TE : Exception
where TUsing : IDisposable
{
using (arg)
{
try
{
tryAction(arg);
}
catch (TE t)
{
CatchAction(t);
}
finally
{
FinallyAction(arg);
}
}
}
public static void TryCatchFinallyUsing<TE1, TE2, TUsing>(Action<TUsing> tryAction, Action<TE1> CatchHandler1, Action<TE2> CatchHandler2, Action<TUsing> FinallyAction, TUsing arg)
where TE1 : Exception
where TE2 : Exception
where TUsing : IDisposable
{
using (arg)
{
try
{
tryAction(arg);
}
catch (TE1 t)
{
CatchHandler1(t);
}
catch (TE2 t)
{
CatchHandler2(t);
}
finally
{
FinallyAction(arg);
}
}
}
public static void TryCatchFinallyUsing<TE1, TE2, TE3, TUsing>(Action<TUsing> tryAction, Action<Exception> CatchHandler1, Action<Exception> CatchHandler2, Action<Exception> CatchHandler3, Action<TUsing> FinallyAction, TUsing arg)
where TE1 : Exception
where TE2 : Exception
where TE3 : Exception
where TUsing : IDisposable
{
using (arg)
{
try
{
tryAction(arg);
}
catch (TE1 t)
{
CatchHandler1(t);
}
catch (TE2 t)
{
CatchHandler2(t);
}
catch (TE3 t)
{
CatchHandler3(t);
}
finally
{
FinallyAction(arg);
}
}
}
public static void TryCatchFinally<TArg, TE>(Action<TArg> tryAction, TArg arg, Action<Exception> CatchAction, Action FinallyAction)
where TE : Exception
{
try
{
tryAction(arg);
}
catch (TE t)
{
CatchAction(t);
}
finally
{
FinallyAction();
}
}
public static void TryCatch<T1>(Action tryAction, Action<Exception> handler, Action FinallyAction)
where T1 : Exception
{
try
{
tryAction();
}
catch (T1 ex)
{
handler(ex);
}
finally
{
FinallyAction();
}
}
public static void TryCatchFinally<T1, TF>(Action tryAction, Action<Exception> handler, Action<TF> finallyAction, TF FinallyArg)
where T1 : Exception
{
try
{
tryAction();
}
catch (T1 ex)
{
handler(ex);
}
finally
{
finallyAction(FinallyArg);
}
}
public static void TryCatchFinally<TE1, TE2, TF>(Action tryAction, Action<Exception> handler1, Action<Exception> handler2, Action<TF> finallyAction, TF FinallyArg)
where TE1 : Exception
where TE2 : Exception
{
try
{
tryAction();
}
catch (TE1 ex)
{
handler1(ex);
}
catch (TE2 ex)
{
handler2(ex);
}
finally
{
finallyAction(FinallyArg);
}
}
public static void TryCatchFinally<TE1, TE2, TE3, TF>(Action tryAction, Action<Exception> handler1, Action<Exception> handler2, Action<Exception> handler3, Action<TF> finallyAction, TF FinallyArg)
where TE1 : Exception
where TE2 : Exception
where TE3 : Exception
{
try
{
tryAction();
}
catch (TE1 ex)
{
handler1(ex);
}
catch (TE2 ex)
{
handler2(ex);
}
catch (TE3 ex)
{
handler3(ex);
}
finally
{
finallyAction(FinallyArg);
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There are some smaller issues in your code, which I will mention later. But the main issue I see is that it's quite useless, since it doesn't make your code any shorter.</p>\n\n<p>If you compare:</p>\n\n<pre><code>try\n{\n /* some code */\n}\ncatch (SomeException ex)\n{\n /* more code */\n}\n</code></pre>\n\n<p>with</p>\n\n<pre><code>FunctionalHelpers.TryCatch<SomeException>(\n () => /* some code */,\n ex => /* more code */);\n</code></pre>\n\n<p>then the latter might look shorter, but that's mostly an illusion. It's more complicated, it's actually longer (if you count the characters) and you could also write the original code like this:</p>\n\n<pre><code>try { /* some code */ }\ncatch (SomeException ex)\n{ /* more code */ }\n</code></pre>\n\n<p>Though I'm not saying you should do that, this code looks terrible.</p>\n\n<p>The point of the article you linked to was to be able to handle several different exceptions with the same code without repeating. Your methods can't do that.</p>\n\n<hr>\n\n<p>Now to the minor points:</p>\n\n<pre><code>public static void TryCatch<TE>(Action tryAction, Action<Exception> handler)\n</code></pre>\n\n<p>You should use <code>Action<TE></code> instead. This way, you can easily access properties that are specific to that type of exception.</p>\n\n<pre><code>public static void TryCatch<TArg, TE>(Action<TArg> tryAction, TArg args, Action<Exception> handler)\n</code></pre>\n\n<p>I don't see much point in having overloads with <code>args</code>. It's usually much easier to use closures (though slightly less performant).</p>\n\n<pre><code>public static void TryCatchFinallyUsing<TE, TUsing>(Action<TUsing> tryAction, Action<Exception> CatchAction, Action<TUsing> FinallyAction, TUsing arg)\n</code></pre>\n\n<p>It seems you missed another point the article made. If you have <code>TUsing</code> as a simple parameter and the code that creates that object throws, it won't be caught by your <code>CatchAction</code>. You should have <code>Func<TUsing></code> instead.</p>\n\n<p>Also, you should consistently name parameters using <code>camelCase</code>, not <code>PascalCase</code>.</p>\n\n<pre><code>public static void TryCatch<T1>(Action tryAction, Action<Exception> handler, Action FinallyAction)\n</code></pre>\n\n<p>This method should be called <code>TryCatchFinally</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T18:59:57.520",
"Id": "35999",
"Score": "2",
"body": "+1. For \"doesn't make it shorter.\" And I'd throw in \"doesn't make it easier\" for good measure. Further, to quote the ref. article: `The idea is that it saves copy-and-paste on the code in the catch block, where that code is all the same.' BF deal. How about a good IDE, code snippets, code completion, typing skills, good OO class design, etc., etc., and etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-29T16:28:26.667",
"Id": "366149",
"Score": "2",
"body": "I know this is an old post but with the recent changes to .net support a more functional approach to development something \"like\" this might make sense. If you are unable to make the full switch to F# you can at least get some semblance of a functional chaining style."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-17T14:39:50.493",
"Id": "388965",
"Score": "0",
"body": "Not sure we can directly say it wont reduce the code. Below code is reducing so much code for me when I want to disable button then execute handler and enable after that. Functions.ExecuteButtonClickWithEnableAndDisable(TestConnectionButton, () =>{\n\n });"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-17T16:40:41.207",
"Id": "388985",
"Score": "0",
"body": "@JoyGeorgeKunjikkuru I wasn't talking about that style of code in general, I was talking about the specific code above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T15:31:22.510",
"Id": "400525",
"Score": "0",
"body": "With c# 6 it is shorter, with using static."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T17:22:25.847",
"Id": "23327",
"ParentId": "23310",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "23327",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T14:51:57.853",
"Id": "23310",
"Score": "7",
"Tags": [
"c#",
"functional-programming",
"error-handling"
],
"Title": "Functional exception handling with TryCatchFinally statement helpers"
}
|
23310
|
<p>A console is an interactive text-mode or text-based user interface to a software application or operating system. It may be implemented as a character-mode application or embedded in a graphical user interface. </p>
<p>It may be used as the main user interface or as a secondary interface for debugging and administrative tasks. The degree of interactivity varies widely between consoles.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T15:01:47.980",
"Id": "23314",
"Score": "0",
"Tags": null,
"Title": null
}
|
23314
|
A mechanism for interacting with a computer operating system or software by typing commands to perform specific tasks.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T15:01:47.980",
"Id": "23315",
"Score": "0",
"Tags": null,
"Title": null
}
|
23315
|
<p>I have three sliders with different min, max values, everything is working fine from following the tutorials on the jQuery UI website.</p>
<pre><code>$("#yield").slider({
range: true,
min: 15.2,
max: 308,
step: 0.3,
values: [75.8, 241.4],
slide: function (event, ui) {
$("#yield-value").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#yield-value").val($("#yield").slider("values", 0) + " - " + $("#yield").slider("values", 1));
$("#tensile").slider({
range: true,
min: 37.7,
max: 345,
step: 0.3,
values: [81.2, 243.3],
slide: function (event, ui) {
$("#tensile-value").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#tensile-value").val($("#tensile").slider("values", 0) + " - " + $("#tensile").slider("values", 1));
$("#elongation").slider({
range: true,
min: 1.0,
max: 77,
step: 0.1,
values: [14.5, 43.2],
slide: function (event, ui) {
$("#elongation-value").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#elongation-value").val($("#elongation").slider("values", 0) + " - " + $("#elongation").slider("values", 1));
</code></pre>
<p>here is my working fiddle here - <a href="http://jsfiddle.net/barrycorrigan/Sqg8A/1/" rel="nofollow">http://jsfiddle.net/barrycorrigan/Sqg8A/1/</a></p>
<p>My problem is that I think my jQuery is written badly for multiple sliders. </p>
<p>Can anyone help me write this code better. Because there is only 3 sliders in the example but on the actual client website there is still 10 to go.</p>
<p>Any help to make my code cleaner somehow would be greatly appreciated.</p>
|
[] |
[
{
"body": "<p>When you have code that repeats itself like that, you want to try and separate the logic from the values. Something like this would work, and you just have to add more to the settings object when needed. It's not jQuery that's badly written, you just have to change the way you're using it. <a href=\"http://jsfiddle.net/Sqg8A/5/\" rel=\"nofollow\">http://jsfiddle.net/Sqg8A/5/</a></p>\n\n<pre><code>$(function() {\n var settings = {\n \"yield\" : {\n range: true,\n min : 15.2,\n max : 308,\n step : 0.3,\n values : [75.8, 241.4]\n },\n \"tensile\" : {\n range: true,\n min : 37.7,\n max : 345,\n step : 0.3,\n values : [81.2, 243.3]\n },\n \"elongation\" : {\n range: true,\n min: 1.0,\n max: 77,\n step: 0.1,\n values: [14.5, 43.2]\n } //Add more if needed\n }\n\n $.each(settings, function(key, value){\n var _key = key;\n $( \"#\" + _key ).slider(\n $.extend(value, { \n slide: function( event, ui ) {\n $( \"#\" + _key + \"-value\" ).val( ui.values[ 0 ] + \" - \" + ui.values[ 1 ] );\n }\n })\n );\n $( \"#\" + _key + \"-value\" ).val( $( \"#\" + _key ).slider(\"values\", 0) + \" - \" + $( \"#\" + _key ).slider(\"values\", 1));\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T16:51:40.817",
"Id": "36157",
"Score": "0",
"body": "For an alternative, you could use a constructor function which takes the parameters that change, and sets the ones that are the same for all. That would work too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T16:26:31.710",
"Id": "23322",
"ParentId": "23316",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23322",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T15:12:40.347",
"Id": "23316",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"jquery-ui"
],
"Title": "Multi jQuery Sliders, Help me write this in better code"
}
|
23316
|
<p>By <code>browser unknown</code>, i mean i don't know how far back support goes for this.</p>
<p>Also, I'm wondering when I can delegate to typeof.</p>
<p>I've heard typeof is faster but the method below is more widely supported and also mentioned in ES5. </p>
<pre><code>/*isType
** dependencies - none
** browser - unknwon
**
*/
NS.isType = function (type, o) {
return (Object.prototype.toString.call(o).slice(8,1) === type);
};
/*getType
** dependencies - none
** browser - unknown
**
*/
NS.getType = function (o) {
return (Object.prototype.toString.call(o).slice(8,1);
};
</code></pre>
<p><strong>Clarification:</strong></p>
<p>Not interested in detecting array like objects....just the language objects defined in ES 5.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-16T21:52:58.437",
"Id": "37006",
"Score": "0",
"body": "http://jsperf.com/constructor-vs-typeof-vs-tostring"
}
] |
[
{
"body": "<p>I think you can run into issues when checking arrays across frames in IE 7 and older, so if you want to make it accurate for that case, check out <a href=\"https://stackoverflow.com/a/4029057\">this answer on StackOverflow</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T16:07:49.307",
"Id": "23319",
"ParentId": "23317",
"Score": "1"
}
},
{
"body": "<p>How about:</p>\n\n<pre><code>NS.CheckType = function (o,test) {\n // implements both\n return test ? o.constructor.name === test : o.constructor.name;\n};\n// usage\nNS.CheckType(false); //=> 'Boolean'\nNS.CheckType(false,Array); //=> false\nNS.CheckType({},Object); //=> true\nNS.CheckType({},Array); //=> false\nNS.CheckType([],Object); //=> false\nNS.CheckType([],Array); //=> true\nNS.CheckType(/[a-z]/); //=> 'RegExp'\nNS.CheckType(0); //=> 'Number'\n// etc...\n</code></pre>\n\n<p>Because most js-things 'inherit' from <code>Object</code> you can also use:</p>\n\n<pre><code>Object.prototype.is = function (test) {\n return test ? this.constructor === test : this.constructor.name;\n};\n// usage\n'string'.is(); //=> 'String'\n'string'.is(Object); //=> false\n (function(){}).is(); //=> Function\n var f = function(){};\n f.is(Function); //=> true\n // also\n function Animal(name){this.name = name || 'some animal';}\n var dog = new Animal('Bello');\n dog.is(Animal); //=> true\n // etc...\n</code></pre>\n\n<p>[<strong>Edit</strong>] tested this in IE7-10:</p>\n\n<pre><code>Object.prototype.is = function (test) {\n return test \n ? this.constructor === test \n : (this.constructor.name || \n String(this.constructor)\n .match ( /^function\\s*([^\\s(]+)/im)[1] );\n};\n</code></pre>\n\n<p>for completeness: if the constructor function is anonymous the method will fail. Here's a solution for that:</p>\n\n<pre><code>Object.prototype.is = function (test) {\n return test \n ? this.constructor === test \n : (this.constructor.name || \n ( String(this.constructor).match ( /^function\\s*([^\\s(]+)/im) \n || ['','ANONYMOUS_CONSTRUCTOR'] ) [1] );\n};\n// usage\nvar Some = function(){ /* ... */}\n some = new Some;\nsome.is(); //=> 'ANONYMOUS_CONSTRUCTOR'\n</code></pre>\n\n<p>And as bonus:</p>\n\n<pre><code>Object.prototype.is = function() {\n var test = arguments.length ? [].slice.call(arguments) : null\n ,self = this.constructor;\n return test ? !!(test.filter(function(a){return a === self}).length)\n : (this.constructor.name ||\n (String(self).match ( /^function\\s*([^\\s(]+)/im)\n || [0,'ANONYMOUS_CONSTRUCTOR']) [1] );\n}\n// usage\nvar Some = function(){ /* ... */}\n ,Other = function(){ /* ... */}\n ,some = new Some;\n2..is(String,Function,RegExp); //=> false\n2..is(String,Function,Number,RegExp); //=> true\nsome.is(); //=> 'ANONYMOUS_CONSTRUCTOR'\nsome.is(Other); //=> false\nsome.is(Some); //=> true\n// note: you can't use this for NaN (NaN === Number)\n(+'ab2').is(Number); //=> true\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T22:16:41.690",
"Id": "36013",
"Score": "0",
"body": "Where can I find more information on constructor.name? Is it more or less compatible as Object.prototype.toString.call(o)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T11:48:01.660",
"Id": "36034",
"Score": "0",
"body": "I suppose its less compatible when it concerns IE. But well, everything is [less compatible when it concerns IE], right? Maybe, if it has to be IE-compatible, you should rewrite the method to use `Object.prototype.toString.call(o)` when `constructor.name` fails. Or just ditch IE-compatibility, that browser will never be up to standards."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T23:41:35.570",
"Id": "36075",
"Score": "0",
"body": "I've added a working IE tweak. The browser may not deserve it, the user does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T20:57:13.647",
"Id": "41849",
"Score": "0",
"body": "Can you consolidate this into one or two methods. Check our http://underscorejs.org/ as one go-by."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T18:02:51.783",
"Id": "23329",
"ParentId": "23317",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "23329",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T15:45:26.073",
"Id": "23317",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "isType(obj) / getType(obj) - v0"
}
|
23317
|
<p>I've coded this function where you read all text file in a directory and you save in a temporary file all values. The text files are <code>x</code>, <code>y</code> and <code>z</code> format. The function returns </p>
<ul>
<li>the name of the temporary file</li>
<li>the bounding box</li>
<li>the origin (top-left corner)</li>
<li>and the bottom (bottom-right corner). </li>
</ul>
<p>I wish for some comments or suggestion on how to improve my working code.</p>
<pre><code>import os
import tempfile
import glob
class LaserException(Exception):
"""Laser exception, indicates a laser-related error."""
pass
sepType = {
"space": ' ',
"tab": '\t',
"comma": ',',
"colon": ':',
"semicolon": ';',
"hyphen": '-',
"dot": '.'
}
def tempfile_merge(path,separator,wildcard= '*.txt'):
file_temp = tempfile.NamedTemporaryFile(delete=False,dir=path)
name = file_temp.name
minx = float('+inf')
maxx = float('-inf')
miny = float('+inf')
maxy = float('-inf')
for file in glob.glob(os.path.join(path,wildcard)):
for line in open(file, "r"):
element = line.split(sepType[separator])
if len(element) < 3:
raise TypeError("not enough arguments: %s has only %s columns" % (inFile_name_suffix,len(element)))
try:
maxx = max(maxx, float(element[0]))
minx = min(minx, float(element[0]))
maxy = max(maxy, float(element[1]))
miny = min(miny, float(element[1]))
except ValueError:
raise LaserException("x,y,z are not float-values")
newelement = " ".join([str(e) for e in element])+ "\n"
file_temp.write(newelement)
file_temp.close()
return(name, ((minx,maxy),(maxx,maxy),(maxx,miny),(minx,miny)),(minx,maxy),(maxx,miny))
</code></pre>
|
[] |
[
{
"body": "<p>Without going into implementation details, I would suggest looking into the following performance optimisations.</p>\n\n<ol>\n<li>Use buffered reads. If you actually read a line at the time it's pretty time consuming.</li>\n<li>Use buffered writes. Instead of writing each new line, collect in a buffer and write in chunks.</li>\n</ol>\n\n<p>For coding review comments, this might be applicable.</p>\n\n<ul>\n<li>The method does 3 different things - merging, syntax checking and bounding rectangle. It might be simpler to maintain and extend the code, if this was refactored into minor helper methods.</li>\n<li>Based on the method name, I would be be able to guess what it does.</li>\n<li>The initial comments say the method calculates the bounding box, but as the files contain 3d data, would it not be more correct to include the z value.</li>\n<li>If the method only need to calculate the bounding rectangle (x,y), is there a need for the merged file to contain the third dimension data ?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T02:39:03.747",
"Id": "68232",
"Score": "0",
"body": "Using some code snippets to *show* what you mean would be a really nice addition to this answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T16:18:41.480",
"Id": "38704",
"ParentId": "23318",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T15:52:54.100",
"Id": "23318",
"Score": "3",
"Tags": [
"python",
"optimization"
],
"Title": "Merge all text files in a directory and save a temp file"
}
|
23318
|
<p>My main method (<code>remove-random-edge</code>) looks quite difficult to read. I'm new to list, so would appreciate <em>any</em> advice on how to improve the code.</p>
<pre><code>(defun find-node (node graph)
(find-if #'(lambda (i) (eql node (first i))) graph))
;; Input, graph, is in form ((from-1 to-1 to-2 to-3 ...)
;; (from-2 to-4 to-5 to-6 ...) ...)
;; where from-n and to-n are integers.
(defun remove-random-edge (graph)
"Remove one random edge from a graph given as adjacency list."
(let* ((node-list-1 (elt graph (random (length graph))))
(node-1 (first node-list-1))
(destinations (remove-duplicates (rest node-list-1)))
(node-2 (elt destinations (random (length destinations))))
(node-list-2 (find-node node-2 graph)))
(flet ((replace-tail-for-head (node) (if (eql node node-2) node-1 node))
(is-head-p (node) (eql node-1 node))
(is-tail-p (node) (eql node-2 node))
(starts-with-tail-p (nodes) (eql node-2 (first nodes))))
(setf (rest node-list-1) (concatenate 'list
(rest node-list-1)
(remove-if #'is-head-p (rest node-list-2))))
(loop for node in (remove-duplicates (rest node-list-2))
with match
with repcd
do (setf match (find-node node graph))
do (setf repcd (if (eql node node-1)
(remove-if #'is-tail-p (rest match))
(map 'list #'replace-tail-for-head (rest match))))
do (setf (rest match) (sort repcd #'<)))
(remove-if #'starts-with-tail-p graph))))
</code></pre>
<p><em>UPD</em>: With review comments applied:</p>
<pre><code>(defun remove-random-edge (graph)
"Remove one random edge from a graph given as adjacency list."
(let* ((head-list (elt graph (random (length graph))))
(head (first head-list))
(destinations (remove-duplicates (rest head-list)))
(tail (elt destinations (random (length destinations))))
(tail-list (assoc tail graph)))
(flet ((replace-tail-for-head (node) (if (eql node tail) head node)))
(setf (rest head-list) (concatenate 'list
(rest head-list)
(remove head (rest tail-list))))
(loop for node in (remove-duplicates (rest tail-list))
for match = (assoc node graph)
do (setf (rest match) (if (eql node head)
(remove tail (rest match))
(mapcar #'replace-tail-for-head (rest match)))))
(remove tail graph :key #'first))))
</code></pre>
<p>Before:</p>
<pre><code>15.109 seconds of real time
50,245,719,578 processor cycles
767,039,256 bytes consed
</code></pre>
<p>After:</p>
<pre><code>2.312 seconds of real time
7,665,669,728 processor cycles
778,172,816 bytes consed
</code></pre>
|
[] |
[
{
"body": "<h2>Superficial</h2>\n\n<p>Your <code>find-node</code> is actually (almost) <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_assocc.htm\" rel=\"nofollow\"><code>assoc</code></a> or, if you prefer, <code>(find node graph :key #'first)</code>.</p>\n\n<p>Use <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_mapc_.htm\" rel=\"nofollow\"><code>mapcar</code></a> instead of <code>map 'list</code> because it makes the intent clearer (the difference is that <code>mapcar</code> takes only lists and <code>map</code> any sequence).</p>\n\n<p>You need just one <code>do</code> in <code>loop</code>; you can even fold all your <code>setf</code>s into one <code>(setf a b c d e f)</code>.</p>\n\n<p>In <code>loop</code>, <code>with</code> should (stylistically) come before <code>for</code>.</p>\n\n<h2>Deep</h2>\n\n<p>Your code looks too complicated for what it does.</p>\n\n<p>None of your <code>flet</code> local functions is really necessary.\nE.g., <code>(remove-if #'is-head-p ...)</code> should be <code>(remove node-1 ...)</code>, \nand <code>(remove-if #'starts-with-tail-p ...)</code> should be <code>(remove node-2 ... :key #'first)</code>;\nthis would make the code both faster and cleaner.</p>\n\n<p>Your <code>loop</code> should be</p>\n\n<pre><code>(loop for node in (remove-duplicates (rest node-list-2))\n for match = (find-node node graph)\n for repcd = (if (eql node node-1)\n (remove-if #'is-tail-p (rest match))\n (map 'list #'replace-tail-for-head (rest match))))\n do (setf (rest match) (sort repcd #'<))) \n</code></pre>\n\n<h2>General</h2>\n\n<p>Usually it is better to use the most specific function you need. E.g., use <code>setq</code> on simple variables (instead of <code>setf</code> which also supports general references). Use <code>mapcar</code> instead of <code>map 'list</code> when working with lists (as opposed to vectors). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T18:16:05.060",
"Id": "36056",
"Score": "0",
"body": "Thank you, very informative. I missed the fact that `setf` can be folded, and the fact that `flet` is redundant is totally clear now, after you pointed that out. Why is `mapcar` preferable over `map` here, also, is `with` before `for` a stylistic preference?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T18:41:01.793",
"Id": "36058",
"Score": "2",
"body": "@zzandy: `with` before `for` is stylistic. `mapcar` make your intent clearer. See edits"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T21:22:26.030",
"Id": "23342",
"ParentId": "23320",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "23342",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T16:11:09.943",
"Id": "23320",
"Score": "2",
"Tags": [
"lisp",
"common-lisp"
],
"Title": "How to improve readability of a big lisp function"
}
|
23320
|
<p>I made my first script of MySQLi. I have just learnt it from 3rd party website. So, I am not sure I am using functions which are not deprecated or outdated. I should start to practice good scripts to access databases. So, I have posted here. Any mistake you see, please point it out.</p>
<pre><code><?php
include "functions.php";
$a = checkLogin();
if($a==1) {
$id = $_COOKIE['id'];
include "databaseConnector.php";
$query = $mysqli->query("SELECT * FROM users WHERE id = '$id'") or die($mysqli->error.__LINE__);
if($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
?>
<?php echo stripslashes($row['firstname'])." ".stripslashes($row['lastname']); ?>
<?php
}
}
else {
return false;
}
}
else {
redirectIndex();
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>mysqli is somewhat outdated, you should see PDO that is much better both with security and database support (12 drivers vs. 1).</p>\n\n<p>You can see here details of mysqli vs. PDO: <a href=\"http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/\" rel=\"nofollow\">http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-17T20:32:30.903",
"Id": "450070",
"Score": "0",
"body": "If MySQL is all you need, then I honestly don't think sticking with `mysqli` is that bad. It's also not marked as deprecated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T17:30:51.743",
"Id": "23576",
"ParentId": "23321",
"Score": "-2"
}
},
{
"body": "<p>You are vulnerable to SQL injection. Always use prepared statements with parameterized queries.</p>\n\n<p>The below example fixes these issues. In this example I am using PDO instead, which is similar to <code>mysqli</code> but more powerful and supports other databases than just MySQL.</p>\n\n<pre><code><?php\n\ninclude \"functions.php\";\n\n$a = checkLogin();\n\nif ($a == 1) {\n $id = $_COOKIE['id'];\n\n // include \"databaseConnector.php\";\n // --------------------------------------------------------------------------------------------------\n try {\n $handle = new PDO(\"mysql:host=$host_addr;dbname=$database\", $username, $password);\n $handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n } catch(PDOException $e) {\n echo 'ERROR: ' . $e->getMessage();\n }\n // --------------------------------------------------------------------------------------------------\n\n // UNBOUND PARAMETERS VERSION\n $query = \"SELECT * FROM users WHERE id = '$id'\";\n $statement = $handle->prepare($query);\n $statement->execute();\n\n // BOUND PARAMETERS VERSION\n $query = \"SELECT * FROM users WHERE id = :id\";\n $statement = $handle->prepare($query);\n $params = array(\":id\" => $id);\n $statement->execute($params);\n\n $row_count = $statement->rowCount();\n $result = $statement->fetchAll(PDO::FETCH_ASSOC);\n\n if($row_count > 0) {\n foreach ($result as $row => $col) {\n echo $col['firstname'].\" \".$col['lastname']; \n }\n } else {\n return false; \n }\n} else {\n redirectIndex();\n}\n\n?>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-03-07T18:59:59.610",
"Id": "23580",
"ParentId": "23321",
"Score": "3"
}
},
{
"body": "<p>Functions used in your code are not deprecated. </p>\n\n<p>However, most of them are highly <strong>not recommended</strong> in your use case, namely</p>\n\n<ul>\n<li><code>die()</code> should never be used to report errors. There are much better ways. See <a href=\"https://stackoverflow.com/a/15320411/285587\">this answer</a> on Stack Overflow for the details.</li>\n<li><code>$mysqli->query</code> should never be used to run a query that includes a variable or your site is busted through an infamous SQL injection. See <a href=\"https://stackoverflow.com/a/60496/285587\">this answer</a> on Stack Overflow for the details.</li>\n</ul>\n\n<p>Besides, your code is just generally not optimal and untidy, with many unnecessary conditions. To avoid them you must have the <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">mysqli connection properly configured</a> in your <code>databaseConnector.php</code> file. After than you can make your code much simpler, cleaner and safer.</p>\n\n<p>Last but not least. Always separate your database interactions from the output. It will make your code even more cleaner and versatile.</p>\n\n<pre><code><?php\n\ninclude \"functions.php\";\n\nif(checkLogin(){\n\n $id = $_COOKIE['id'];\n\n include \"databaseConnector.php\";\n\n $stmt = $conn->prepare(\"SELECT * FROM users WHERE id=?\");\n $stmt->bind_param(\"i\", $id);\n $Stmt->execute();\n $result = $stmt->get_result(); //get mysqli result\n $row = $result->fetch_assoc(); // fetch data \n} else {\n redirectIndex();\n}\n</code></pre>\n\n<p>here your PHP part should stop and then in the HTML part you can continue</p>\n\n<pre><code><?php if($row): ?>\n <?= htmlspecialchars($row['firstname']) ?>\n <?= htmlspecialchars($row['lastname']) ?>\n<?php endif ?>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T08:59:21.730",
"Id": "230941",
"ParentId": "23321",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-03-01T16:18:32.143",
"Id": "23321",
"Score": "1",
"Tags": [
"beginner",
"php",
"mysqli"
],
"Title": "MySQLi script to print the name of a user"
}
|
23321
|
<p>I'm implementing a checkers engine for a scientific experiment. I found out through profiling that this is one of the functions that takes up a lot of time. I'm not looking for an in-depth analysis, because I don't expect you to dive super deep into my code.</p>
<p>Just: <strong>are there any obvious inefficiencies here?</strong> Like, is it slow to do those starting for loops (<code>dx, dy</code>) just for 2 values each?</p>
<pre><code>def captures(self, (py, px), piece, board, captured=[], start=None):
""" Return a list of possible capture moves for given piece in a
checkers game.
:param (py, px): location of piece on the board
:param piece: piece type (BLACK/WHITE|MAN/KING)
:param board: the 2D board matrix
:param captured: list of already-captured pieces (can't jump twice)
:param start: from where this capture chain started.
"""
if start is None:
start = (py, px)
# Look for capture moves
for dx in [-1, 1]:
for dy in [-1, 1]:
dist = 1
while True:
jx, jy = px + dist * dx, py + dist * dy # Jumped square
# Check if piece at jx, jy:
if not (0 <= jx < 8 and 0 <= jy < 8):
break
if board[jy, jx] != EMPTY:
tx, ty = px + (dist + 1) * dx, py + (dist + 1) * dy # Target square
# Check if it can be captured:
if ((0 <= tx < 8 and 0 <= ty < 8) and
((ty, tx) == start or board[ty, tx] == EMPTY) and
(jy, jx) not in captured and
((piece & WHITE) and (board[jy, jx] & BLACK) or
(piece & BLACK) and (board[jy, jx] & WHITE))
):
# Normal pieces cannot continue capturing after reaching last row
if not piece & KING and (piece & WHITE and ty == 0 or piece & BLACK and ty == 7):
yield (NUMBERING[py, px], NUMBERING[ty, tx])
else:
for sequence in self.captures((ty, tx), piece, board, captured + [(jy, jx)], start):
yield (NUMBERING[py, px],) + sequence
break
else:
if piece & MAN:
break
dist += 1
yield (NUMBERING[py, px],)
</code></pre>
|
[] |
[
{
"body": "<p>A couple of little things that caught my eye:</p>\n\n<p>You could simplify this</p>\n\n<pre><code>dist = 1 \nwhile True:\n jx, jy = px + dist * dx, py + dist * dy \n dist += 1\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>jx, jy = px, py\nwhile True:\n jx += dx\n jy += dy\n</code></pre>\n\n<hr>\n\n<p>You don't need this range check</p>\n\n<pre><code>if not (0 <= jx < 8 and 0 <= jy < 8):\n break\nif board[jy, jx] != EMPTY:\n</code></pre>\n\n<p>because, assuming <code>board</code> is a dict indexed by tuple, you can just catch <code>KeyError</code> when out of bounds:</p>\n\n<pre><code>try:\n if board[jy, jx] != EMPTY:\n ...\nexcept KeyError:\n break\n</code></pre>\n\n<hr>\n\n<p>Instead of</p>\n\n<pre><code>((piece & WHITE) and (board[jy, jx] & BLACK) or\n (piece & BLACK) and (board[jy, jx] & WHITE))\n</code></pre>\n\n<p>you could use <code>board[jy, jx] & opponent</code> if you determine the opponent's color in the beginning of the function:</p>\n\n<pre><code>opponent = BLACK if piece & WHITE else WHITE\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-08T17:19:11.613",
"Id": "23626",
"ParentId": "23323",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T16:31:35.090",
"Id": "23323",
"Score": "3",
"Tags": [
"python",
"recursion",
"generator",
"checkers-draughts"
],
"Title": "Efficiency of Recursive Checkers Legal Move Generator"
}
|
23323
|
<p>I made a Python function that takes an XML file as a parameter and returns a JSON.
My goal is to convert some XML get from an old API to convert into Restful API.</p>
<p>This function works, but it is really ugly. I try to clean everything, without success.</p>
<p>Here are my tests:</p>
<pre class="lang-python prettyprint-override"><code> def test_one_node_with_more_than_two_children(self):
xml = '<a id="0" name="foo"><b id="00" name="moo" /><b id="01" name="goo" /><b id="02" name="too" /></a>'
expected_output = {
"a": {
"@id": "0",
"@name": "foo",
"b": [
{
"@id": "00",
"@name": "moo"
},
{
"@id": "01",
"@name": "goo"
},
{
"@id": "02",
"@name": "too"
}
]
}
}
self.assertEqual(expected_output, self.parser.convertxml2json(xml))
</code></pre>
<p>And my function:</p>
<pre class="lang-python prettyprint-override"><code>from xml.dom.minidom import parseString, Node
class Parser(object):
def get_attributes_from_node(self, node):
attributes = {}
for attrName, attrValue in node.attributes.items():
attributes["@" + attrName] = attrValue
return attributes
def convertxml2json(self, xml):
parsedXml = parseString(xml)
return self.recursing_xml_to_json(parsedXml)
def recursing_xml_to_json(self, parsedXml):
output_json = {}
for node in parsedXml.childNodes:
attributes = ""
if node.nodeType == Node.ELEMENT_NODE:
if node.hasAttributes():
attributes = self.get_attributes_from_node(node)
if node.hasChildNodes():
attributes[node.firstChild.nodeName] = self.recursing_xml_to_json(node)[node.firstChild.nodeName]
if node.nodeName in output_json:
if type(output_json[node.nodeName]) == dict:
output_json[node.nodeName] = [output_json[node.nodeName]] + [attributes]
else:
output_json[node.nodeName] = [x for x in output_json[node.nodeName]] + [attributes]
else:
output_json[node.nodeName] = attributes
return output_json
</code></pre>
<p>Can someone give me some tips to improve this code?<br>
<code>def recursing_xml_to_json(self, parsedXml)</code> is really bad.<br>
I am ashamed to produce it :)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T19:07:29.333",
"Id": "36326",
"Score": "0",
"body": "Could you explain the intent, and add some comments?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T14:33:47.853",
"Id": "36596",
"Score": "0",
"body": "i updated my question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-19T17:22:17.250",
"Id": "62799",
"Score": "0",
"body": "What about [XMLtoDict](https://github.com/martinblech/xmltodict) ?\nIt seems similar to what you created, no?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T11:15:27.707",
"Id": "62800",
"Score": "0",
"body": "After studying the source code of this application, I thought there was an easier way to do. It allowed me to improve myself."
}
] |
[
{
"body": "<p>There is a structural issue with your code: the recursive function works at two levels. 1) It constructs a dict representing a node, and 2) it does some work in constructing the representation for the children. This makes it unnecessarily complicated. Instead, the function should focus on handling one node, and delegate the creation of child nodes to itself via recursion.</p>\n\n<p>You seem to have requirements such as:</p>\n\n<ol>\n<li>A node that has no children nor attributes converts to an empty string. My implementation: <code>return output_dict or \"\"</code></li>\n<li>Multiple children with same nodeName convert to a list of dicts, while a single one converts to just a dict. My implementation makes this explicit by constructing lists first, then applying this conversion: <code>v if len(v) > 1 else v[0]</code></li>\n<li>A node with children but no attributes raises a TypeError. I suspect this is an oversight and did not reproduce the behavior.</li>\n</ol>\n\n<p>Note that (2) means that a consumer of your JSON that expects a variable number of nodes must handle one node as a special case. I don't think that is good design.</p>\n\n<pre><code>def get_attributes_from_node(self, node):\n attributes = {}\n if node.attributes:\n for attrName, attrValue in node.attributes.items():\n attributes[\"@\" + attrName] = attrValue\n return attributes\n\ndef recursing_xml_to_json(self, node):\n d = collections.defaultdict(list)\n for child in node.childNodes:\n if child.nodeType == Node.ELEMENT_NODE:\n d[child.nodeName].append(self.recursing_xml_to_json(child))\n\n output_dict = self.get_attributes_from_node(node)\n output_dict.update((k, v if len(v) > 1 else v[0])\n for k, v in d.iteritems())\n\n return output_dict or \"\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T14:33:26.653",
"Id": "36595",
"Score": "0",
"body": "This answer is really amazing"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T20:44:52.960",
"Id": "23551",
"ParentId": "23324",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23551",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T16:36:00.630",
"Id": "23324",
"Score": "5",
"Tags": [
"python",
"unit-testing",
"xml",
"json",
"recursion"
],
"Title": "Recursive XML2JSON parser"
}
|
23324
|
Constants in programming are definitions whose value is fixed throughout a program's execution. Literals in most languages are constants, for example. In referentially transparent programming styles, all definitions are constant.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T18:10:09.720",
"Id": "23332",
"Score": "0",
"Tags": null,
"Title": null
}
|
23332
|
<p>I have a text file with lines that look like this:</p>
<pre><code>Robot(479.30432416307934|98.90610653676828)
Robot(186.42081184420528|213.11277688981409)
Robot(86.80794277768825|412.1359734884495)
</code></pre>
<p>or, more general:</p>
<pre><code>Robot(DOUBLE|DOUBLE)
</code></pre>
<p>How should I parse it in Java?</p>
<p>I have written the following (tested and working) code:</p>
<pre><code>private static List<Position> getPositions(File myFile)
throws FileNotFoundException, IOException {
List<Position> result = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(myFile));
try {
String line = br.readLine();
while (line != null) {
String coordinates = line.substring(6, line.length() - 1);
int splitpoint = coordinates.indexOf('|');
double x = Double.parseDouble(coordinates.substring(0,
splitpoint));
double y = Double.parseDouble(coordinates
.substring(splitpoint + 1));
result.add(new Position(x, y));
line = br.readLine();
}
} finally {
br.close();
}
return result;
}
</code></pre>
<p>It looks a too complicated for such a simple task for me. I mean, with the RegEx </p>
<pre><code>Robot\(\d+\.\d+|\d+\)
</code></pre>
<p>I can match a line. According to <a href="http://www.myregextester.com/index.php" rel="nofollow">Regextester</a> my regex is correct. But how can I get the interesting part (the two doubles) from the regex?</p>
<h2>Result after answer</h2>
<pre><code>/**
* Read a file with positions of roboters.
* @param file the file with positions
* @return the list with roboter positions
* @throws FileNotFoundException
* @throws IOException
*/
private static List<Position> getPositions(final File file)
throws FileNotFoundException, IOException {
if (file == null || !file.canRead()) {
throw new IllegalArgumentException("file not readable: " + file);
}
final Scanner s = new Scanner(file).useDelimiter("Robot\\(|\\||\\)\n?");
final List<Position> positions = new ArrayList<Position>();
while (s.hasNext()) {
positions.add(new Position(s.nextDouble(), s.nextDouble()));
s.nextLine();
}
return positions;
}
</code></pre>
|
[] |
[
{
"body": "<p>I would suggest the use of parethensis to store these values:</p>\n\n<pre><code>String regexp = \"Robot\\((\\d+\\.\\d+)|(\\d+\\.\\d+))\";\n\nPattern pattern = Pattern.compile(regexp);\nMatcher m1 = pattern.match(line);\n\nwhile (m1.find()) {\n final int count = m1.groupCount();\n // group 0 is the whole pattern matched,\n // loops runs from from 0 to gc, not 0 to gc-1 as is traditional.\n for ( int i = 0; i <= gc; i++ ) {\n out.println( i + \" : \" + m1.group( i ) );\n }\n}\n</code></pre>\n\n<p>Source: <a href=\"http://www.mindprod.com/jgloss/regex.html\" rel=\"nofollow\">http://www.mindprod.com/jgloss/regex.html</a> #Finding</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T18:51:59.687",
"Id": "35951",
"Score": "0",
"body": "Please take it as a hint, I haven't had the time to test it thoroughly right now :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T20:37:04.907",
"Id": "35959",
"Score": "0",
"body": "This does not work this way. Even if we fix the small typos, the regexp is declared as a group with the numbers inside. This wont work and will catch at most the last number. It could be fixed with some work, but I do not think this makes it easier to understand or to apply."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T18:50:15.087",
"Id": "23335",
"ParentId": "23333",
"Score": "0"
}
},
{
"body": "<p><code>java.util.Scanner</code> provides a nice way to split a given string by regex:</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\n\n\nclass Robot {\n\n final double d1;\n final double d2;\n\n public Robot(final double d1, final double d2) {\n this.d1 = d1;\n this.d2 = d2;\n }\n\n @Override\n public String toString() {\n return \"Robot(\" + d1 + \"|\" + d2 + \")\";\n }\n}\n\npublic class Test {\n\n public static void main(final String[] args) {\n final String str =\n \"Robot(479.30432416307934|98.90610653676828)\\n\"\n + \"Robot(186.42081184420528|213.11277688981409)\\n\"\n + \"Robot(86.80794277768825|412.1359734884495)\";\n final Scanner s = new Scanner(str).useDelimiter(\"Robot\\\\(|\\\\||\\\\)\\n?\");\n final List<Robot> robots = new ArrayList<Robot>();\n while (s.hasNext()) {\n robots.add(new Robot(s.nextDouble(), s.nextDouble()));\n s.nextLine();\n }\n System.out.println(robots);\n }\n}\n</code></pre>\n\n<p>The only flaw is that after each line an empty string is read. I couldn't find out why - thus, I discarded it manually.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T21:19:09.727",
"Id": "35960",
"Score": "1",
"body": "The flaw is not easily visible in your representation. If you write he string in one line, it is easier to see. If we look at this part: `28)\\nRobot(186` and think about your regexp, we will see, that `\\)\\n?` happily matches `)\\n`. But then, the Scanner is at position after this. Before `Robot(186`. If you want to avoid this, you have to catch the following `Robot(`, too. One easy way would be to catch all non-digits, because the next interesting char is a digit: `Robot\\\\(|\\\\||\\\\)\\\\D*`. But I would not suggest to use this regexp, this is already hardly unreadable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T21:23:58.063",
"Id": "35961",
"Score": "0",
"body": "@tb: Thanks for the explanation, I see the problem now. I agree, the regex is difficult to read and the single `s.nextLine()` isn't that bad to obfuscate it further..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T19:26:11.210",
"Id": "23336",
"ParentId": "23333",
"Score": "1"
}
},
{
"body": "<p>As this is posted on codereview, let us take a look at the whole function.</p>\n\n<pre><code>private static List<Position> getPositions(File myFile)\n throws FileNotFoundException, IOException {\n</code></pre>\n\n<p>I would suggest to do a check for the file (and rename it to file, I do not think there is a herFile, hisFile and so on):</p>\n\n<pre><code> if (file == null || !file.canRead())\n throw new IllegalArgumentException(\"file not readable: \" + file);\n</code></pre>\n\n<p>Which could make error handling a bit easier. We will see later.</p>\n\n<hr>\n\n<pre><code> List<Position> result = new ArrayList();\n BufferedReader br = new BufferedReader(new FileReader(myFile));\n try {\n String line = br.readLine();\n while (line != null) {\n ...\n line = br.readLine();\n</code></pre>\n\n<p>I would keep the typical pattern, so everyone can recognize it:</p>\n\n<pre><code> String line;\n while ((line = bufferedReader.readLine()) != null) {\n</code></pre>\n\n<hr>\n\n<pre><code> String coordinates = line.substring(6, line.length() - 1);\n int splitpoint = coordinates.indexOf('|');\n double x = Double.parseDouble(coordinates.substring(0, splitpoint));\n double y = Double.parseDouble(coordinates.substring(splitpoint + 1));\n result.add(new Position(x, y));\n line = br.readLine();\n }\n</code></pre>\n\n<p>For me, this is nearly fine. Just to a <code>split(\"|\")</code> and you are done in the easy way:</p>\n\n<pre><code> final String[] coordinatesArray = line.substring(6, line.length() - 1).split(\"|\");\n final double x = Double.parseDouble(coordinatesArray[0]);\n final double y = Double.parseDouble(coordinatesArray[1]);\n result.add(new Position(x, y));\n</code></pre>\n\n<p>And I suggest to add an example in a comment, to help the next reader.</p>\n\n<hr>\n\n<pre><code> } finally {\n br.close();\n }\n</code></pre>\n\n<p>If you have Java7, you could change this to try-with statement:</p>\n\n<pre><code> try (final BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {\n ...\n } \n</code></pre>\n\n<p>And you could catch the error. The most problematic ones are cought by the file checks. Everything else is probably something you can not do anything about.<br>\nThen it is fine to catch it, show it and continue:</p>\n\n<pre><code> } catch (NumberFormatException | IOException e) {\n e.printStackTrace(); // handle the exception or rethrow it. It could be safe to do nothing here\n }\n</code></pre>\n\n<hr>\n\n<p>If you put everything together, it could look like this:</p>\n\n<pre><code>private static List<Position> getPositions(final File file) {\n if (file == null || !file.canRead())\n throw new IllegalArgumentException(\"file not readable: \" + file);\n\n final List<Position> result = new ArrayList<>();\n try (final BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {\n String line;\n while ((line = bufferedReader.readLine()) != null) {\n // example: Robot(479.30432416307934|98.90610653676828)\n final String[] coordinatesArray = line.substring(6, line.length() - 1).split(\"|\");\n final double x = Double.parseDouble(coordinatesArray[0]);\n final double y = Double.parseDouble(coordinatesArray[1]);\n result.add(new Position(x, y));\n }\n } catch (NumberFormatException | IOException e) {\n e.printStackTrace(); // handle the exception or rethrow it. It could be safe to do nothing here\n }\n return result;\n}\n</code></pre>\n\n<hr>\n\n<p>If you try the way with the scanner, you shoudl just tell him which characters to ignore. Please do not try a complex regular expression. They are unreadable.<br>\nWhat we have there? </p>\n\n<blockquote>\n <p>Robot(479.30432416307934|98.90610653676828)</p>\n</blockquote>\n\n<p>Well, everything which is not a number or a point. To save some typing, we do not place every character alone, we put them together as <code>\\p{Alpha}</code> (any alphabetic character): <code>[\\p{Alpha}()|\\]</code>. And we want this to happen for one or more times: <code>[\\p{Alpha}()|]+</code>. \nAnd we should not forget about multiple lines, then there is a newline: <code>[\\p{Alpha}()|\\\\n]+</code>. </p>\n\n<p>It is still mostly readable if you have a basic understanding of regular expressions, so we are fine in this case. You could also use <code>[a-zA-Z()|\\\\n]+</code> which would be more common outside the java world.</p>\n\n<p>The complete function could look like this:</p>\n\n<pre><code>private static List<Position> getPositions(final File file) {\n if (file == null || !file.canRead())\n throw new IllegalArgumentException(\"file not readable: \" + file);\n\n final List<Position> result = new ArrayList<>();\n\n try (Scanner scanner = new Scanner(file)) {\n // example: Robot(479.30432416307934|98.90610653676828)\n scanner.useDelimiter(\"[\\p{Alpha}()|\\\\n]+\");\n while (scanner.hasNext())\n result.add(new Position(scanner.nextDouble(), scanner.nextDouble()));\n } catch (final FileNotFoundException e1) {\n e1.printStackTrace(); // handle the exception or rethrow it. It could be safe to do nothing here\n }\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T20:20:06.643",
"Id": "23339",
"ParentId": "23333",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23336",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T18:13:20.143",
"Id": "23333",
"Score": "1",
"Tags": [
"java",
"parsing",
"regex"
],
"Title": "How should I read coordinates from a text file?"
}
|
23333
|
<p>This my 3rd question on the same exercise, but by no means a duplicate. The two previous questions were posted on <strong>StackOverflow</strong> <a href="https://stackoverflow.com/questions/15100254/sql-query-for-time-intervals-syntax-errors">here</a> and <a href="https://stackoverflow.com/questions/15123351/oracle-syntax-error-on-join-to-sub-query">here</a>.</p>
<p>Now I'm posting my Oracle solution (below) that works. I wonder if the same could've been simpler and/or much more efficient. Not in terms of CTE or analytic expressions but with basic simple logic.</p>
<p><strong>Data</strong>:</p>
<pre><code>CREATE TABLE Readings (
user_id varchar(10),
reading_time int ,
x decimal(10,2),
y decimal(10,2)
);
INSERT ALL
INTO Readings (user_id, reading_time, x, y) VALUES ('u1', 60, 345, 400)
INTO Readings (user_id, reading_time, x, y) VALUES ('u1', 100, 560, 300)
INTO Readings (user_id, reading_time, x, y) VALUES ('u2', 35, 1024, 250)
INTO Readings (user_id, reading_time, x, y) VALUES ('u1', 90, 450, 450)
INTO Readings (user_id, reading_time, x, y) VALUES ('u3', 150, 600, 100)
INTO Readings (user_id, reading_time, x, y) VALUES ('u3', 100, 500, 125)
SELECT * FROM dual;
</code></pre>
<p><strong>Intermediate script</strong>:</p>
<pre><code>SELECT r.user_id, rm.reading_time start_time, r.reading_time end_time,
(r.reading_time-rm.reading_time) time_spent,
(TO_CHAR(rm.x)||' ; '||TO_CHAR(rm.y)) start_point,
(TO_CHAR(r.x)||' ; '||TO_CHAR(r.y)) end_point,
SQRT(POWER(r.x-rm.x, 2)+POWER(r.x-rm.y, 2)) distance
FROM Readings r
JOIN Readings rm ON (r.user_id = rm.user_id and
rm.reading_time = (SELECT MAX(r2.reading_time) FROM Readings r2 WHERE r2.reading_time < r.reading_time))
ORDER BY 1,2;
</code></pre>
<p><strong>Final script</strong>:</p>
<pre><code>SELECT rr.user_id, SUM(rr.distance) "Total Distance",
SUM(rr.time_spent) "Total Time", SUM(rr.distance)/SUM(rr.time_spent) "Average Speed"
FROM
(SELECT r.user_id, (r.reading_time-rm.reading_time) time_spent,
SQRT(POWER(r.x-rm.x, 2)+POWER(r.x-rm.y, 2)) distance
FROM Readings r
JOIN Readings rm ON (r.user_id = rm.user_id and
rm.reading_time = (SELECT MAX(r2.reading_time) FROM Readings r2 WHERE r2.reading_time < r.reading_time))) rr
GROUP BY rr.user_id
ORDER BY 1;
</code></pre>
<p><strong>Exercise Description</strong> </p>
<p>Multiple <em>users</em> roam a plain and at irregular time intervals report their <em>coordinates</em> (x, y). This information (user id, time-stamp and the coordinates) populate table <code>Readings</code>. </p>
<p>For each user that reported more than one set of coordinates we need to find <em>total distance traveled</em>, <em>total time spent</em>, and their <em>average speed</em>.</p>
<p>For the sake of simplicity coordinates are Cartesian and time-stamps are integers. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T22:00:09.840",
"Id": "35968",
"Score": "0",
"body": "Always put your units. Never reference columns numerically, always do it by name (this saves you from re-ordered columns in the select surprising you). Recent versions of Oracle support additional analysis functions that might help you (like [LAG/LEAD](http://docs.oracle.com/cd/E11882_01/server.112/e25554/analysis.htm#autoId18)) - see if any of those might help you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T13:42:58.043",
"Id": "35991",
"Score": "0",
"body": "what are you actually trying to compute? What is the problem statement of the exercise?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T00:53:17.700",
"Id": "36024",
"Score": "0",
"body": "@abuzittin gillifirca - added to the post (at the bottom)"
}
] |
[
{
"body": "<ul>\n<li><p>You have a bug. Change the row <code>('u3', 100, 500, 125)</code> to <code>('u3', 99, 500, 125)</code>, and try again. You will see that <code>u3</code> row disappears.</p>\n\n<p>You can fix it with the following minimal change:</p>\n\n<pre><code>rm.reading_time = (SELECT MAX(r2.reading_time) \n FROM Readings r2 \n WHERE r2.user_id=r.user_id -- you have to join on ids first\n and r2.reading_time < r.reading_time)\n</code></pre></li>\n<li><p>There is another bug here:\n<code>r.x-rm.y</code> should have been <code>r.y-rm.y</code>.</p></li>\n<li><p><code>user_id, reading_time</code> is a unique key by problem definition. Having it declared will enable us to detect some invalid inputs. What is the average speed of an object that can be at more than one place?</p></li>\n<li><p>I would go along with something like this for the intermediate script:</p>\n\n<pre><code>SELECT t.*, t2.*\nFROM (SELECT r.user_id,r.reading_time, \n max(r.x) AS x1, max(r.y) AS y1, \n max(rm.reading_time) AS prev\nFROM Readings r\nJOIN Readings rm ON (r.user_id = rm.user_id AND rm.reading_time < r.reading_time)\nGROUP BY r.user_id,r.reading_time) t\nINNER JOIN Readings t2\nON t.user_id = t2.user_id AND t2.reading_time = t.prev;\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T05:19:05.187",
"Id": "23377",
"ParentId": "23341",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23377",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T21:03:40.540",
"Id": "23341",
"Score": "3",
"Tags": [
"sql",
"oracle"
],
"Title": "Self Join Exercise. Have I over-complicated it?"
}
|
23341
|
<p>Question</p>
<blockquote>
<p>Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists)</p>
</blockquote>
<p>Here is my attempt at a solution. I haven't test it, but I was trying to get feedback on whether or not this would be an appropriate approach to such solution.</p>
<pre><code>public class solution {
ArrayList<LinkedList<Node>> makeArrayList(Node n) {
int level = 0;
return addLists(new ArrayList<LinkedList<Node>>(), n, level);
}
ArrayList<LinkedList<Node>> addLists(ArrayList<LinkedList<Node>> arr, Node n, int level) {
if (n != null) {
if (arr.get(level) == null) {
LinkedList<Node> newList = new LinkedList<Node>();
arr.add(level, newList);
}
LinkedList<Node> nodeList = arr.get(level);
nodeList.add(n);
addLists(arr, n.leftChild, level + 1);
addLists(arr, n.rightChild, level + 1);
}
return arr;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T22:32:36.163",
"Id": "35970",
"Score": "9",
"body": "`I haven't test it` then do it."
}
] |
[
{
"body": "<p>Your return types and the types left of the assignments should be as general as possible, so you only need to change the instantiation if you want to change the implementation to an other type of list.</p>\n\n<pre><code>List<Node> \nList<List<Node>>\n</code></pre>\n\n<p>In general it is a good idea to replace ifs that covers the whole function by a guard condition. So you get rid of a level of nesting.</p>\n\n<pre><code>{\n if (n == null) return arr;\n if (arr.get(level) == null) arr.add(level, new LinkedList<Node>());\n\n arr.get(level).add(n);\n addLists(arr, n.leftChild, level + 1);\n addLists(arr, n.rightChild, level + 1);\n\n return arr;\n}\n</code></pre>\n\n<p>I only checked your code layout. If you want to see if it works, write a test as tb suggested.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T08:00:31.860",
"Id": "23351",
"ParentId": "23343",
"Score": "7"
}
},
{
"body": "<p>This section:</p>\n\n<pre><code>if (arr.get(level) == null) {\n LinkedList<Node> newList = new LinkedList<Node>();\n arr.add(level, newList);\n}\n</code></pre>\n\n<p>is going to throw an <code>IndexOutOfBoundsException</code> every single time, since you never do <code>arr.add</code> before doing <code>arr.get</code>. The proper way to do it (incorporating some good suggestions from @mnhg's answer):</p>\n\n<pre><code>{\n if (n == null) return arr;\n if (arr.size() <= level) arr.add(new LinkedList<Node>());\n\n arr.get(level).add(n);\n addLists(arr, n.leftChild, level + 1);\n addLists(arr, n.rightChild, level + 1);\n\n return arr;\n}\n</code></pre>\n\n<p>This, of course, is why we test code <em>before</em> sending it for review.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T09:21:13.137",
"Id": "38216",
"ParentId": "23343",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "38216",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T21:23:52.547",
"Id": "23343",
"Score": "2",
"Tags": [
"java",
"algorithm"
],
"Title": "Creating an Array of Linked Lists from a BST"
}
|
23343
|
<p>I have a list of boxes, and wish to group them into unconnected sets of overlapping boxes. (Note that two boxes A and B may not overlap each other, but if they are both overlapped by a box C, they will still be grouped together).</p>
<p>The following works ok, but I feel like it could be made a lot more concise with LINQ, or possibly made faster.</p>
<pre><code>private List<List<Box>> FindUnconnectedSets(List<Box> boxes)
{
List<List<Box>> unconnectedSets = new List<List<Box>>();
while (boxes.Count() != 0)
{
List<Box> set = new List<Box>();
bool found = true;
while (found)
{
found = false;
foreach (Box newBox in boxes)
{
if (set.Count != 0)
{
foreach (Box setBox in set)
{
if (newBox.Overlaps(setBox))
{
set.Add(newBox);
boxes.Remove(newBox);
found = true;
break;
}
}
}
else
{
set.Add(newBox);
boxes.Remove(newBox);
found = true;
}
if (found)
break;
}
}
unconnectedSets.Add(set);
}
return unconnectedSets;
}
</code></pre>
<p>Edit: added the Box class. It's not all that interesting really.</p>
<pre><code>private class Box
{
public Box(int xOrigin, int yOrigin, int size)
{
XOrigin = xOrigin;
YOrigin = yOrigin;
Size = size;
}
public int XOrigin;
public int YOrigin;
public int Size;
public override string ToString()
{
string s = "Box: "
+ "(" + XOrigin.ToString() + ", " + YOrigin.ToString() + ")"
+ " " + Size.ToString();
return s;
}
public bool Overlaps(Box b2)
{
if (XOrigin >= b2.XOrigin + b2.Size)
return false;
if (b2.XOrigin >= XOrigin + Size)
return false;
if (YOrigin >= b2.YOrigin + b2.Size)
return false;
if (b2.YOrigin >= YOrigin + Size)
return false;
return true;
}
}
</code></pre>
<p>Comments welcome, both on the LINQifying side, and algorithm suggestions if you think I'm going about this the wrong way, as well as any other feedback. :)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T23:33:03.650",
"Id": "35975",
"Score": "3",
"body": "Can you please add the `Box` implementation, and maybe a few examples of input and expected output? This could be quite helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T00:29:15.087",
"Id": "35977",
"Score": "0",
"body": "You call them sets but they are actually lists. You can use a `HashSet<T>` instead. Your function should accept a HashSet. Then write another function that accepts `IEnumerable<T>` and converts it to `HashSet<T>` and then calls the implementing function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T03:22:34.363",
"Id": "35981",
"Score": "0",
"body": "@Leonid: I don't see how that adds any concrete value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T11:21:33.293",
"Id": "35986",
"Score": "0",
"body": "@GCATNM added the Box class - it's just x origin, y origin and a size value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T11:48:26.267",
"Id": "35987",
"Score": "0",
"body": "@user673679 Thanks - I was just confused initially, but then realized the exact functionality didn't matter and I could just build something myself to use for testing. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-08T14:30:34.533",
"Id": "36410",
"Score": "0",
"body": "I had a similar problem, making sure a set of rectangles did not overlap. (Oddly it was for range validation) I ended up using the .NET rectangle object in System.Drawing and it's intersect method. Based off this http://stackoverflow.com/questions/5842836/linq-find-rectangles-positioned-over-each-other/5844918#5844918"
}
] |
[
{
"body": "<p>I've made a first attempt at shortening and simplifying the code with LINQ. First, I created a helper method for moving items from one <code>List</code> to another based on this <a href=\"https://stackoverflow.com/a/1029297/116614\">StackOverflow question</a>.</p>\n\n<pre><code>private int MoveItemsWhere<T>(Func<T, bool> predicate, List<T> source, List<T> target)\n{\n var selected = new HashSet<T>(source.Where(predicate));\n target.AddRange(selected);\n source.RemoveAll(selected.Contains);\n return selected.Count;\n}\n</code></pre>\n\n<p>Then I modified the <code>FindUnconnectedSets</code> to use LINQ for finding overlapping boxes:</p>\n\n<pre><code>private List<List<Box>> FindUnconnectedSets(List<Box> boxes)\n{\n var unconnectedSets = new List<List<Box>>();\n while (boxes.Count > 0)\n {\n var set = boxes.Take(1).ToList();\n boxes = boxes.Skip(1).ToList();\n\n int numAdded;\n do\n {\n numAdded = MoveItemsWhere(b => set.Any(s => s.Overlaps(b)), boxes, set);\n } while (numAdded > 0);\n\n unconnectedSets.Add(set);\n }\n return unconnectedSets;\n}\n</code></pre>\n\n<p>Some notes on the above code:</p>\n\n<ul>\n<li>I'm using implicit declarations with <code>var</code>. Personal preference, but I find it a little cleaner than repeating long types like <code>List<List<Box>></code>.</li>\n<li>I changed the criteria from a <code>bool found</code> to <code>int numAdded</code> because I think it's a little clearer about the purpose.</li>\n<li>The core LINQ logic is <code>b => set.Any(s => s.Overlaps(b))</code>; this looks up every item from <code>boxes</code> where any item in <code>set</code> overlaps with the box.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T09:29:18.180",
"Id": "35982",
"Score": "2",
"body": "`boxes = boxes.Skip(1).ToList()` Doing that in a loop is very inefficient (O(n²))."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T12:58:49.697",
"Id": "35990",
"Score": "1",
"body": "This works well. There also doesn't seem to be any difference in performance between `boxes = boxes.Skip(1).ToList()` and `boxes.RemoveAt(0)`, which is surprising, but nice..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T17:27:08.690",
"Id": "35995",
"Score": "0",
"body": "Some of that actually makes me think this might be a good application for F#, from the examples I've seen of that language. Don't speak that myself, but it might be interesting."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T02:37:22.540",
"Id": "23348",
"ParentId": "23347",
"Score": "1"
}
},
{
"body": "<p>The general approach seems fine; I couldn't think of a radically different algorithm - but LINQ does help indeed.</p>\n\n<p>I used it to improve your code in two respects:</p>\n\n<ul>\n<li>The distinction between an empty list and one that contains elements overlapping the current box at the innermost level was executing the same code in both cases; using LINQ for the checks (especially replacing the <code>foreach</code>) allowed me to write this in a much more concise manner and remove the code duplication.</li>\n<li>The while-found-break kludge that was necessary because removing items from the target list of an iteration breaks the iterator was quite hard to fully wrap one's head around. This could be eliminated with a simple but effective trick: I iterate over a 'snapshot' copy of the <code>boxes</code> list while still removing the items from the original list. That prevents the iterator from breaking while still removing all the boxes from future checks that have already found their home (the <code>ToList()</code> call after the <code>Select()</code> query is very important for that to work). As a result, I only need to iterate through the current remaining boxes list once per set instead of needing to restart as many times as I find a box that belongs in the current set. Because I'm only removing items we've already left behind in the current iteration, that is not a problem for the correctness of the algorithm.</li>\n</ul>\n\n<p>I also replaced the condition in the remaining <code>while</code> loop with a call to <code>Any()</code> instead of checking <code>Count()</code>; the effect is the same, but it has slightly better performance, especially on longer lists.\nIt would be nice to get rid of the <code>while</code> completely in favor of another LINQ construct, but I don't see a way to do that.</p>\n\n<pre><code>public IList<IList<Box>> FindUnconnectedSets(IList<Box> boxes)\n{\n IList<IList<Box>> unconnectedSets = new List<IList<Box>>();\n\n while (boxes.Any())\n {\n IList<Box> set = new List<Box>();\n\n foreach (Box newBox in boxes.Select(b => b).ToList())\n {\n if ((!set.Any()) || (set.Any(b => newBox.Overlaps(b))))\n {\n set.Add(newBox);\n boxes.Remove(newBox);\n }\n }\n\n unconnectedSets.Add(set);\n }\n\n return unconnectedSets;\n}\n</code></pre>\n\n<p>Oh, and I replaced <code>List<></code> with <code>IList<></code> where possible, mainly out of a general preference for abstractions over concrete implementations; this changes nothing functionally.</p>\n\n<p>By the way: If you use ReSharper, it will suggest pulling up the innermost <code>if</code> condition into a <code>Where()</code> call instead of the <code>Select()</code> in the <code>foreach</code> parameter; while that is technically correct and a more 'proficient' use of the possibilities of LINQ, it obscures the meaning of the condition and makes it harder to understand. Goes to show that shortest way to write something is not always the best.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T12:07:01.317",
"Id": "35988",
"Score": "0",
"body": "Unfortunately this doesn't quite work. I should have explained the original code better: the \"found\" bool has another purpose too. When a box is added to the set, we have to restart iteration over the box list anyway, as the new box may add more area, and overlap with boxes we've already passed over."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T12:23:28.573",
"Id": "35989",
"Score": "0",
"body": "True, didn't think of that, and my test cases weren't unordered enough to catch it. That's what I meant when I said it was hard to get one's head around. Let's see what I can do about that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T17:23:58.130",
"Id": "35994",
"Score": "0",
"body": "This was my test case, sketched out on a napkin :) http://i.imgur.com/n1Rx7mm.jpg"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T03:20:32.377",
"Id": "23349",
"ParentId": "23347",
"Score": "1"
}
},
{
"body": "<p>Since we are talking about <em>sets</em>, it's probably better to use collection types that represent a set: <code>HashSet<T></code> and <code>ISet<T></code>.</p>\n\n<p>Another improvement you can make is to keep track of the boxes you've added to current set at the last iteration (horizon of your expansion), and try to match candidate boxes only with them.</p>\n\n<p>Note that resulting solution doesn't use the knowledge about box matching logic, so it might be a good idea to extract the interface that defines the connection between elements (i.e. a method that checks for the presence of link between nodes).</p>\n\n<p>As a result I've got the following solution:</p>\n\n<pre><code>public interface IConnected<in T>\n{\n bool IsConnectedTo(T other);\n}\n\npublic class Box: IConnected<Box>\n{\n ....\n\n public bool IsConnectedTo(Box other)\n {\n return Overlaps(other);\n }\n}\n</code></pre>\n\n<p>And the <code>FindUnconnectedSets</code>:</p>\n\n<pre><code>public static List<ISet<T>> FindUnconnectedSets<T>(IEnumerable<T> boxes) where T : IConnected<T>\n{\n var remainingBoxes = new HashSet<T>(boxes);\n var unconnectedSets = new List<ISet<T>>();\n\n while (remainingBoxes.Count > 0)\n {\n var newBoxes = new[] { remainingBoxes.First() }; //on each iteration will contain newly added boxes to current set\n var currentSet = new HashSet<T>();\n unconnectedSets.Add(currentSet);\n\n do\n {\n currentSet.UnionWith(newBoxes);\n remainingBoxes.ExceptWith(newBoxes);\n newBoxes = remainingBoxes\n .Where(remainingBox => newBoxes.Any(setBox => setBox.IsConnectedTo(remainingBox)))\n .ToArray();\n } while (newBoxes.Length > 0);\n }\n\n return unconnectedSets;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T13:17:58.200",
"Id": "36096",
"Score": "1",
"body": "Shouldn't it be `remainingBoxes.First()` instead of `Single()`? `Single()`would throw an exception if there is more than one box left in the list."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T12:46:32.713",
"Id": "23427",
"ParentId": "23347",
"Score": "2"
}
},
{
"body": "<p>Actually, your <code>Box</code> class itself interests me a bit. From the way it seems to be used, I'd make it immutable, as such:</p>\n\n<pre><code>public sealed class Box\n{\n private readonly int xOrigin;\n private readonly int yOrigin;\n\n private readonly int size;\n\n public Box(int xOrigin, int yOrigin, int size)\n {\n this.xOrigin = xOrigin;\n this.yOrigin = yOrigin;\n\n this.size = size;\n }\n\n public int XOrigin { get { return this.xOrigin; } }\n public int YOrigin { get { return this.yOrigin; } }\n\n public int Size { get { return this.size; } }\n\n public override string ToString()\n {\n return \"Box: \"\n + \"(\" + this.xOrigin + \", \" + this.yOrigin + \")\"\n + \" \" + this.size;\n }\n\n public bool Overlaps(Box b2)\n {\n if (b2 == null)\n throw new ArgumentNullException(\"b2\");\n if (this.xOrigin >= b2.XOrigin + b2.Size)\n return false;\n if (b2.XOrigin >= this.xOrigin + this.size)\n return false;\n if (this.yOrigin >= b2.YOrigin + b2.Size)\n return false;\n if (b2.YOrigin >= this.yOrigin + this.size)\n return false;\n\n return true;\n }\n}\n</code></pre>\n\n<p>This may also be a decent candidate for being turned into a <code>struct</code>, if your <code>Box</code>es can be happy with an XOrigin, YOrigin and Size of <code>0</code> by default.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T16:02:10.283",
"Id": "23490",
"ParentId": "23347",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23348",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T23:22:59.360",
"Id": "23347",
"Score": "3",
"Tags": [
"c#",
"algorithm",
"linq"
],
"Title": "Finding unconnected sets"
}
|
23347
|
<p>I want to create a program(in Java) which simulates the functionality of Arithmetic Logistic Unit(ALU). </p>
<p>Here is my code. Please check is this correct. Can I implement it better? </p>
<pre><code> public class ALU {
public static final int NOP = 0;
public static final int SEQ = 1;
public static final int SNE = 2;
public static final int SGT = 3;
public static final int SLE = 4;
public static final int SLT = 5;
public static final int ADD = 6;
public static final int ADDU = 7;
public static final int SUB = 8;
public static final int SUBU = 9;
public static final int MULT = 10;
public static final int MULTU = 11;
public static final int DIV = 12;
public static final int DIVU = 13;
public static final int AND = 14;
public static final int OR = 15;
public static final int XOR = 16;
public static final int SLL = 17;
public static final int SRL = 18;
public static final int SRA = 19;
public boolean[] getResult(boolean[] srcValue1, boolean[] srcValue2, int ope){
boolean [] result = new boolean[32];
int shift = 0; //ÒÆÎ»Êý
long src1 = 0;
long src2 = 0;
switch(ope){
case NOP: break;
case SEQ:
if(toSigned(srcValue1,0,31) == toSigned(srcValue2,0,31))
result[31] = true;
break;
case SNE:
if(toSigned(srcValue1,0,31) != toSigned(srcValue2,0,31))
result[31] = true;
break;
case SGT:
if(toSigned(srcValue1,0,31) > toSigned(srcValue2,0,31))
result[31] = true;
break;
case SLE:
if(toSigned(srcValue1,0,31) <= toSigned(srcValue2,0,31))
result[31] = true;
break;
case SLT:
if(toSigned(srcValue1,0,31) < toSigned(srcValue2,0,31))
result[31] = true;
break;
case ADD:
result = ADD(srcValue1,srcValue2);
break;
case ADDU:
result = ADD(srcValue1,srcValue2);
break;
case SUB:
result = SUB(srcValue1,srcValue2);
break;
case SUBU:
result = SUB(srcValue1,srcValue2);
break;
case MULT:
src1 = toSigned(srcValue1,0,31);
src2 = toSigned(srcValue2,0,31);
result = long2Boolean(src1*src2);
break;
case MULTU:
src1 = toUnsigned(srcValue1,0,31);
src2 = toUnsigned(srcValue2,0,31);
result = long2Boolean(src1*src2);
break;
case DIV:
src1 = toSigned(srcValue1,0,31);
src2 = toSigned(srcValue2,0,31);
result = long2Boolean(src1/src2);
break;
case DIVU:
src1 = toUnsigned(srcValue1,0,31);
src2 = toUnsigned(srcValue2,0,31);
result = long2Boolean(src1/src2);
break;
case AND:
for(int i=0;i<32;i++)
result[i] = srcValue1[i]&srcValue2[i];
break;
case OR:
for(int i=0;i<32;i++)
result[i] = srcValue1[i]|srcValue2[i];
break;
case XOR:
for(int i=0;i<32;i++){
result[i] = XOR(srcValue1[i],srcValue2[i]);
}
break;
case SLL:
shift = (int)toUnsigned(srcValue2,27,31);
for(int i=0;i<32-shift;i++)
result[i] = srcValue1[i+shift];
for(int i=32-shift;i<32;i++)
result[i] = false;
break;
case SRL:
shift = (int)toUnsigned(srcValue2,27,31);
for(int i=0;i<shift;i++)
result[i] = false;
for(int i=shift;i<32;i++)
result[i] = srcValue1[i-shift];
break;
case SRA:
shift = (int)toUnsigned(srcValue2,27,31);
boolean sign = srcValue1[0];
for(int i=0;i<shift;i++)
result[i] = sign;
for(int i=shift;i<32;i++)
result[i] = srcValue1[i-shift];
break;
}
return result;
}
private long toUnsigned(boolean[] data, int pos1, int pos2) {
long number = 0;
for (int i = pos1; i <= pos2; i++) {
if (data[i] == true)
number += (int) Math.pow(2, pos2 - i);
}
return number;
}
private long toSigned(boolean[] data, int pos1, int pos2) {
long number = 0;
for (int i = (pos1 + 1); i <= pos2; i++) {
if (data[i] == true)
number += (long) Math.pow(2, pos2 - i);
}
if (data[pos1] == true)
number = number - (long) Math.pow(2, pos2 - pos1);
return number;
}
private boolean[] long2Boolean(long number){
boolean[] result = new boolean[32];
for(int i=0;i<32;i++){
int bit = (int) (number&1);
if(bit == 1)
result[31-i] = true;
number = number>>1;
}
return result;
}
private boolean XOR(boolean src1,boolean src2){
boolean result = true;
if(src1 == src2 )
result = false;
return result;
}
private boolean[] ADD(boolean[] srcValue1,boolean[] srcValue2){
boolean Ci = false;
boolean[] result = new boolean[32];
for(int i=31;i>=0;i--){
result[i] = XOR(XOR(srcValue1[i],srcValue2[i]),Ci);
Ci = (srcValue1[i]&srcValue2[i])|(XOR(srcValue1[i],srcValue2[i])&Ci);
}
return result;
}
private boolean[] SUB(boolean[] srcValue1,boolean[] srcValue2){
boolean[] result = new boolean[32];
//¼ÆËãsrcValue2µÄ²¹Âë
for(int i=0;i<32;i++)
srcValue2[i] = !srcValue2[i];
boolean[] one = new boolean[32];
one[31] = true;
srcValue2 = ADD(srcValue1,srcValue2);
result = ADD(srcValue1,srcValue2);
return result;
}
public static void main(String[] args) {
long a = (long)Math.pow(2, 33);
boolean [] b = new ALU().long2Boolean(a);
System.out.print(b.length+"\n");
for(int i=0;i<32;i++)
System.out.println(b[i]);
}
}
</code></pre>
<p>Does this code satisfy all the functionality of Arithmetic Logistic Unit? . I just want to simulate the ALU functionality in my program. How to insert control bits in my program? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T12:35:39.587",
"Id": "36224",
"Score": "0",
"body": "Please consider using a BitSet. It is provided by Java and you can abstract from all of this booleans. Then, you should only work with universal gates. For example, a NAND is universal. At the moment, you just do some more fancy looking way of the normal java arithmetic operations. And please, an ALU is a logic unit, it has nothing to do with logistic. Even if some electrons and bits are transported. This is just a comment, to make a complete answer would take days, or probably weeks, sorry."
}
] |
[
{
"body": "<ol>\n<li>Enum might be the real solution to define the different possible operations.</li>\n<li>The implementation of the XOR method could be more concise :\n<code>private boolean XOR(boolean src1,boolean src2){ return (src1 != src2 );}</code> and you probably don't need it anyway because Java has a <a href=\"http://www.leepoint.net/notes-java/data/expressions/bitops.html\" rel=\"nofollow\">bitwise xor operator</a>. Also, that would make your cases AND,OR and XOR more consistent.</li>\n<li><p>You should try to make your code a bit more consistent : sometimes you store <code>toSigned(srcValue1,0,31)</code> in a variable before using it, sometimes you don't. My feeling is that even though it's not great from a performance point of view because it makes you compute stuff you may not need, it might make things easier to do :</p>\n\n<pre><code> long usrc1 = toUnsigned(srcvalue1,0,31);\n long usrc2 = toUnsigned(srcvalue2,0,31);\n long ssrc1 = toSigned(srcvalue1,0,31);\n long ssrc2 = toSigned(srcvalue2,0,31);\n</code></pre>\n\n<p>to avoid the boring repetition in the rest of the method.</p></li>\n<li><p>On the other hand, shift could probably be declared and defined only when you need it : <code>int shift = (int)toUnsigned(srcValue2,27,31);</code></p></li>\n<li>It might be worth pointing out that according to <a href=\"http://docs.oracle.com/javase/specs/#4.2\" rel=\"nofollow\">the Java specs</a>, integers are 32 bits so you probably don't need to do everything with arrays of 32 booleans. My feeling is that it would make everything much easier and you'd be able to do things in a straighforward way. For instance, case SEQ: would become : `case SEQ: return (src1==src2);'. If you do so, I think most of the loops you write might not be useful anymore.</li>\n</ol>\n\n<p>I don't have much time to go through the end of the code but I hope this is a good beginning.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T19:53:17.267",
"Id": "36003",
"Score": "0",
"body": "Good stuff. About #5 I think the whole point of the exercise is to implement the bit-level operations without using Java's built-in arithmetic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T23:49:56.133",
"Id": "36020",
"Score": "0",
"body": "David: You are right and your answer's much more relevant if this is a learning exercise :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T09:51:16.967",
"Id": "23353",
"ParentId": "23352",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p><strong>Note:</strong> I would have reversed the bits in the array (sign bit in the last element) so the bit in position <code>i</code> represents <code>2 ^ i</code>. The code below assumes this is the case.</p>\n</blockquote>\n\n<p>Since you're writing this in Java, you should encapsulate it all into a new <code>Int</code> class. Assuming this is a learning exercise, you could even go so far as to model it as an array of thirty-two <code>Bit</code>s.</p>\n\n<pre><code>class Int\n{\n public static final int SIZE = 32;\n\n private Bit[] bits = new Bit[SIZE];\n\n public Int add(Int other) {\n Bit[] result = new Bit[SIZE];\n Bit carry = new Bit();\n for (int i = 0; i < SIZE; i++) {\n Bit bit1 = this.bits[i];\n Bit bit2 = other.bits[i];\n result[i] = bit1.xor(bit2).xor(carry);\n carry = bit1.and(bit2).or(bit1.xor(bit2)).and(carry);\n }\n return new Int(result);\n }\n}\n</code></pre>\n\n<p>Here are some smaller tips:</p>\n\n<ul>\n<li><p>You should use the boolean operators (<code>&&</code> and <code>||</code>) with boolean values instead of the bitwise operators (<code>&</code> and <code>|</code>). Using the latter causes a lot of needless casting between <code>int</code> and <code>boolean</code> and depends on Java's turning <code>true</code> into <code>1</code> and <code>false</code> into <code>0</code>.</p></li>\n<li><p>Pre-calculate the thirty-two <code>long</code> bit positions using <code><<</code> up front and reuse them throughout instead of using <code>Math.pow</code>.</p>\n\n<pre><code>public static final LONG_BITS = new long[32];\nstatic {\n for (int b = 0; b < 32; b++)\n LONG_BITS[b] = 1 << b;\n}\n</code></pre></li>\n<li><p>Testing a <code>boolean</code> value for truth can be shortened: <code>if (data[i] == true)</code> becomes <code>if (data[i])</code>.</p></li>\n<li><p>The <code>toSigned</code> and <code>toUnsigned</code> methods are cheating a little by using <code>+=</code> and <code>-=</code>. You should use the <code>|=</code>, <code>&=</code>, and <code>~</code> bit operators throughout. Of course, <code>MUL</code> and <code>DIV</code> are cheating a lot! ;)</p></li>\n<li><p>Add overloaded versions of <code>toSigned</code> and <code>toUnsigned</code> for the most common case:</p>\n\n<pre><code>public long toSigned(boolean[] data) { return toSigned(data, 0, 31); }\npublic long toUnsigned(boolean[] data) { return toUnsigned(data, 0, 31); }\n</code></pre></li>\n<li><p><code>pos1</code> and <code>pos2</code> are <em>horrible</em> names for these parameters. Is one the sign bit? Another the number of bits? Do they form a range of bits to convert to a <code>long</code>? Meaningful variable names will go a long way toward compensating for the lack of comments.</p></li>\n<li><p>I would name the arrays (<code>src1</code>, <code>data</code>, etc.) for what they are: <code>bits</code>.</p></li>\n<li><p>Do you need a <code>NOT</code> operand for taking the <a href=\"http://en.wikipedia.org/wiki/Two%27s_complement\" rel=\"nofollow\">two's complement</a>?</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T06:52:55.557",
"Id": "36030",
"Score": "0",
"body": "Do you need a NOT operand for taking the two's complement? Yes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T09:00:01.740",
"Id": "36031",
"Score": "0",
"body": "@SuchZen - Actually, that should be `NEG` operator for the two's complement. A `NOT` operator would also be useful. Is there an official definition of what makes a *complete* ALU?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T21:12:31.710",
"Id": "23366",
"ParentId": "23352",
"Score": "3"
}
},
{
"body": "<p>Just a minor note (as far as I see nobody has mentioned it): <code>31</code>, <code>32</code>, <code>27</code> etc. are magic numbers here and the code uses them multiple times. They should be named constants. It would make the code easier to maintain (and you can easily switch to 64 or 16 bit).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T11:54:10.410",
"Id": "23424",
"ParentId": "23352",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T09:08:33.360",
"Id": "23352",
"Score": "3",
"Tags": [
"java"
],
"Title": "Simulating ALU in java"
}
|
23352
|
<p>I wrote a tail-recursive list-flattening function, but I'm not too happy with it.</p>
<p>a) Is tail-recursion necessary here, or will the function be optimized without it?<br>
b) It's ugly how many clauses there are, and that I have to call out to <code>flatten</code> in the expression of the first clause of <code>flatten_acc</code></p>
<p>So, how could I do better?</p>
<p>(To be clear, this is a function that completely flattens the list -- e.g. <code>flatten([foo, [[[bar]], [baz]]])</code> == <code>[foo, bar, baz]</code>)</p>
<pre><code>flatten(List) ->
lists:reverse(flatten_acc(List, [])).
flatten_acc([[[H|T0]|T1]|T2], Acc) ->
flatten_acc([flatten([[H|T0]|T1])|T2], Acc);
flatten_acc([[H|T0]|T1], Acc) ->
flatten_acc([T0|T1], [H|Acc]);
flatten_acc([[]|T], Acc) ->
flatten_acc(T, Acc);
flatten_acc([H|T], Acc) ->
flatten_acc(T, [H|Acc]);
flatten_acc([], Acc) ->
Acc.
</code></pre>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>Little smaller than yours.</p>\n\n<pre><code>% flatten a list\nmy_flatten([])->\n [] ;\nmy_flatten([[]|T])->\n my_flatten(T);\nmy_flatten([[H|T]|T2])->\n my_flatten([H|[T|T2]]);\nmy_flatten([H|T])->\n [H|my_flatten(T)].\n</code></pre>\n\n<p><a href=\"http://erlang99.wordpress.com/2009/01/19/p07-flatten-a-nested-list-structure/\" rel=\"nofollow\">http://erlang99.wordpress.com/2009/01/19/p07-flatten-a-nested-list-structure/</a></p>\n\n<pre><code>my_flatten_rec(L)->\n lists:reverse(my_flatten_rec([],L)).\nmy_flatten_rec(Acc,[[]|T])->\n my_flatten_rec(Acc,T);\nmy_flatten_rec(Acc,[[H|T]|T2])->\n my_flatten_rec(Acc,[H|[T|T2]]);\nmy_flatten_rec(Acc,[H|T])->\n my_flatten_rec([H|Acc],T);\nmy_flatten_rec(Acc,[])->\n Acc.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T19:13:25.297",
"Id": "36000",
"Score": "0",
"body": "So, this isn't tail-recursive. Does it not need to be?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T20:54:37.463",
"Id": "36005",
"Score": "0",
"body": "Tail recursion is really only necessary when the recursion could go on indefinitely. In this case, unless it's a list of staggering size/depth, hard to see how you'd blow up the stack."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T15:18:44.563",
"Id": "23359",
"ParentId": "23354",
"Score": "2"
}
},
{
"body": "<p>How about this:</p>\n\n<pre><code>flatten(L) -> lists:reverse(flatten(L, [])).\n\nflatten([], Acc) -> Acc;\nflatten([H | T], Acc) when is_list(H) -> flatten(T, flatten(H, Acc));\nflatten([H | T], Acc) -> flatten(T, [H | Acc]).\n</code></pre>\n\n<p>The tail recursion is not necessary in this case but makes it much more easy to read and clarity is king. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-02T09:04:04.853",
"Id": "26891",
"ParentId": "23354",
"Score": "1"
}
},
{
"body": "<p>I think if you're serious about learning the best way to do this, you should take a look at the <a href=\"https://github.com/erlang/otp/blob/maint/lib/stdlib/src/lists.erl#L593\" rel=\"nofollow\">source</a>:</p>\n\n<pre><code>%% flatten(List)\n%% flatten(List, Tail)\n%% Flatten a list, adding optional tail.\n\n-spec flatten(DeepList) -> List when\n DeepList :: [term() | DeepList],\n List :: [term()].\n\nflatten(List) when is_list(List) ->\n do_flatten(List, []).\n\n-spec flatten(DeepList, Tail) -> List when\n DeepList :: [term() | DeepList],\n Tail :: [term()],\n List :: [term()].\n\nflatten(List, Tail) when is_list(List), is_list(Tail) ->\n do_flatten(List, Tail).\n\ndo_flatten([H|T], Tail) when is_list(H) ->\n do_flatten(H, do_flatten(T, Tail));\ndo_flatten([H|T], Tail) ->\n [H|do_flatten(T, Tail)];\ndo_flatten([], Tail) ->\n Tail.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-02T11:13:15.840",
"Id": "26892",
"ParentId": "23354",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T10:07:13.633",
"Id": "23354",
"Score": "1",
"Tags": [
"functional-programming",
"recursion",
"erlang"
],
"Title": "List-flattening function in erlang feels too wordy"
}
|
23354
|
Git is an open-source DVCS (Distributed Version Control System).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T11:59:27.170",
"Id": "23356",
"Score": "0",
"Tags": null,
"Title": null
}
|
23356
|
<p>This question is about code style.</p>
<p>I have this line in one of my models:</p>
<pre><code>has_many :owning_artists, :through => :artist_tracks, :source => :artist, :conditions => { :artist_tracks => { :artistic_role_id => 1, :another_memeber => 42 } }
</code></pre>
<p>What is the best way to break this up on multiple lines, and indented of course, and what would it would look like?</p>
<p>I'd love to hear a more general recommendation/guideline for how to break up and indent nested hashes too.</p>
|
[] |
[
{
"body": "<p>This is what I would do:</p>\n\n<pre><code>has_many :owning_artists, {\n :through => :artist_tracks,\n :source => :artist,\n :conditions => {\n :artist_tracks => {\n :artistic_role_id => 1,\n :another_memeber => 42\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:56:33.737",
"Id": "35996",
"Score": "1",
"body": "Can't really add to this other than to say that if the `artist_tracks` hash had more than one member I would break those on to individual lines as well, indented accordingly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:55:22.913",
"Id": "23362",
"ParentId": "23361",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "23362",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:50:09.330",
"Id": "23361",
"Score": "1",
"Tags": [
"ruby-on-rails",
"ruby"
],
"Title": "What is the best way to format a large has_many through line?"
}
|
23361
|
<p>I believe this is essentially the same method as the <code>itertools.combinations</code> function, but is there any way to make this code more more perfect in terms of speed, code size and readability :</p>
<pre><code>def all_subsets(source,size):
index = len(source)
index_sets = [()]
for sz in xrange(size):
next_list = []
for s in index_sets:
si = s[len(s)-1] if len(s) > 0 else -1
next_list += [s+(i,) for i in xrange(si+1,index)]
index_sets = next_list
subsets = []
for index_set in index_sets:
rev = [source[i] for i in index_set]
subsets.append(rev)
return subsets
</code></pre>
<p>Yields:</p>
<pre><code>>>> Apriori.all_subsets(['c','r','i','s'],2)
[['c', 'r'], ['c', 'i'], ['c', 's'], ['r', 'i'], ['r', 's'], ['i', 's']]
</code></pre>
<p>There is probably a way to use generators or functional concepts, hopefully someone can suggest improvements.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T23:53:25.477",
"Id": "36021",
"Score": "0",
"body": "Why aren't you using itertools.combinations? It's reasonable to do this for learning purposes, but if you are actually doing a bigger project you'll want to use the itertools version."
}
] |
[
{
"body": "<p>This type of problems lend themselves very well to <a href=\"http://en.wikipedia.org/wiki/Recursion\" rel=\"nofollow\">recursion</a>. A possible implementation, either in list or generator form could be:</p>\n\n<pre><code>def all_subsets(di, i) :\n ret = []\n for j, item in enumerate(di) :\n if i == 1 :\n ret = [(j,) for j in di]\n elif len(di) - j >= i :\n for subset in all_subsets(di[j + 1:], i - 1) :\n ret.append((item,) + subset)\n return ret\n\ndef all_subsets_gen(di, i) :\n for j, item in enumerate(di) :\n if i == 1 :\n yield (j,)\n elif len(di) - j >= i :\n for subset in all_subsets(di[j + 1:], i - 1) :\n yield (item,) + subset\n\n>>> all_subsets(range(4), 3)\n[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]\n>>> list(all_subsets_gen(range(4), 3))\n[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]\n</code></pre>\n\n<p>If you are going to run this on large sets, you may want to <a href=\"http://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow\">memoize</a> intermediate results to speed things up.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T16:14:46.120",
"Id": "36045",
"Score": "0",
"body": "RE the memorization, do you mean if the function is going to be run more than once? Otherwise I don't see how memorization would help here, since isn't there only *one path* down through the recursion, with each size of subsets being created just once?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T16:47:23.860",
"Id": "36047",
"Score": "0",
"body": "@CrisStringfellow In my example above, the `(0, 2, 3)` and the `(1, 2, 3)` are both calling `all_subsets([2, 3], 2)` and it gets worse for larger sets, especially with a small `i`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T16:50:22.550",
"Id": "36049",
"Score": "0",
"body": "Got it. I was wrong. But couldn't that be subtly changed by making the call to 2,3 and then prepending the first element/s? Is this what you mean by memorization?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T23:54:14.707",
"Id": "23371",
"ParentId": "23363",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23371",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T19:38:14.427",
"Id": "23363",
"Score": "1",
"Tags": [
"python",
"functional-programming",
"combinatorics"
],
"Title": "Any way to optimize or improve this python combinations/subsets functions?"
}
|
23363
|
<p>I am new to Python and not very familiar with advanced Python data structures.</p>
<p>I have written a function to receive data from a socket in Python and perform string manipulations on it. The basic purpose of the code is to get the metadata from an Icecast radio stream based on suggestions I found elsewhere.</p>
<p>The function seems to work but it would be great it someone can help me optimize the string operation.</p>
<pre><code>def radioPoller():
msg1="GET / HTTP/1.1"+'\r'+'\n'+"Host: sc.buddharadio.com"+'\r'+'\n'+"User-Agent: VLC/2.0.5 LibVLC/2.0.5"+'\r'+'\n'+"Range: bytes=0-"+'\r'+'\n'+"Connection: close"+'\r'+'\n'+"Icy-MetaData: 1"+'\r'+'\n'+'\r'+'\n'
if os.path.exists("/media/hdd1/data.txt"):
os.unlink("/media/hdd1/data.txt")
HOST = 'sc.buddharadio.com' # The remote host
PORT = 80 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
f=open("/media/hdd1/data.txt","w")
s.send(msg1) #sending http request
data=""
while len(data)<1024:
data=s.recv(1024) #recieving a few characters
t=data.find("metaint") #finding the metaint response header which contains interval after which metadata will be visible in data stream eg:-icy-metaint:32768
data=data[t+8:] #jumping 8 characters to the end of the string
splitter="\r\n" # to split the contents and find when header ends and
data1=data.split(splitter) #data1 stores the splitted data. First list has length and last has data
metaInt=int(data1[0]) #find the metadata interval byte length
#print metaInt
string12=data1[len(data1)-1] #contains only the data part
lengthTotal= len(string12) #length of data we have
print "total data is", lengthTotal,"\n"
print "TOtal bytes we should get is", (metaInt+4080),"\n"
while lengthTotal<(metaInt+4080):
data = s.recv(8192)
lengthTotal=lengthTotal+len(data)
print "Total length now is", lengthTotal
string12=string12+data
#The first character after MetaInterval number of characters define the length of actual metadata/16
metaLen=ord(string12[metaInt])
print "This is multiplier", metaLen, "No of characters to read ", (metaLen*16)
metaString=string12[metaInt+1:metaInt+1+(metaLen*16)]+'\n'
print "Extracted String is \n", metaString
f.write(str(metaString))
s.close
f.close
</code></pre>
<p>The code sends a request header to the radio stream and then receives a response like this:</p>
<blockquote>
<p>ICY 200 OK
icy-notice1:<BR>This stream requires <a href="http://www.winamp.com/" rel="nofollow">Winamp</a><BR>
icy-notice2:SHOUTcast Distributed Network Audio Server/Linux v1.9.8<BR>
icy-name:Buddha<BR>
icy-genre:<BR>
icy-url:<a href="http://www.buddharadio.com" rel="nofollow">http://www.buddharadio.com</a><BR>
content-type:audio/aac<BR>
icy-pub:0<BR>
icy-metaint:32768<BR>
icy-br:32<BR></p>
</blockquote>
<p>The icy-metaint defines the data interval after the metadata appears in the data stream.</p>
<p>I use a <code>while</code> loop to read in the <strong>Meta Data Interval+Max Meta Data Length</strong> of data and then slice the metadata and save it in a file.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T19:53:31.587",
"Id": "36004",
"Score": "0",
"body": "Repeated string concatenations are a bad idea - instead build a list and then use `\"\".join()`."
}
] |
[
{
"body": "<pre><code>def radioPoller():\n</code></pre>\n\n<p>Python convention says that function names should be lowercase_with_undescores. Also, they should be verb, so: <code>poll_radio</code> would be better</p>\n\n<pre><code> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((HOST, PORT))\n</code></pre>\n\n<p>I recommend not using <code>s</code> as its not obvious what that means. </p>\n\n<pre><code> finalData=[]\n</code></pre>\n\n<p>Python convention, local names should be <code>lowercase_with_underscores</code>.</p>\n\n<pre><code> f=open(\"/media/hdd1/data.txt\",\"a\")\n</code></pre>\n\n<p>Again, don't use single letter variable names.</p>\n\n<pre><code> s.send(msg1) #sending http request\n</code></pre>\n\n<p>Instead of doing HTTP requests yourself, it'd make more sense to use urllib2 to do it for you. That way it'd take care of parsing etc.\nWhere is msg1 coming from? Also, you don't know that this sent all the data. To be sure all data was sent, use s.sendall</p>\n\n<pre><code> data=\"\"\n while len(data)<1024:\n data=s.recv(1024) #recieving a few characters\n</code></pre>\n\n<p>Shouldn't you be using <code>+=</code>? </p>\n\n<pre><code> t=data.find(\"metaint\") #finding the metaint response header\n data=data[t+8:] #jumping 8 characters to the end of the string\n\n splitter=\"\\r\\n\" # to split the contents and find when header ends and \n data1=data.split(splitter) #data1 stores the splitted data. First list has length and last has data \n</code></pre>\n\n<p>Why assign splitter to a local variable? just pass the constant.</p>\n\n<pre><code> metaInt=int(data1[0]) #find the metadata interval byte length\n #print metaInt \n</code></pre>\n\n<p>Rather then mucking with this use, use python's tool to parse the headers for you.</p>\n\n<pre><code> finalData.append(data1[len(data1)-1]) #contains only the data part\n</code></pre>\n\n<p>You can use <code>data1[-1]</code> for the same result. </p>\n\n<pre><code> lengthTotal= len(finalData[0]) #length of data we have\n\n #print \"total data is\", lengthTotal,\"\\n\"\n\n #print \"TOtal bytes we should get is\", (metaInt+4080),\"\\n\"\n</code></pre>\n\n<p>Don't leave dead code in comments</p>\n\n<pre><code> while lengthTotal<(metaInt+4080):\n data = s.recv(8192)\n\n lengthTotal=lengthTotal+len(data)\n #print \"Total length now is\", lengthTotal \n finalData.append(data)\n</code></pre>\n\n<p>In this case I suggest using StringIO rather than a list.</p>\n\n<pre><code> print finalData\n string12=''.join(finalData)\n</code></pre>\n\n<p>Don't use meaningless names</p>\n\n<pre><code> metaLen=ord(string12[metaInt])\n #print \"This is multiplier\", metaLen, \"No of characters to read \", (metaLen*16)\n\n metaString=string12[metaInt+1:metaInt+1+(metaLen*16)]\n metaString=metaString+\"\\r\\n\"\n\n #print \"Extracted String is \\n\", metaString\n\n f.write(str(metaString))\n</code></pre>\n\n<p>It's already a string, don't pass it to str</p>\n\n<pre><code> s.close\n f.close\n</code></pre>\n\n<p>These last two don't do anything.</p>\n\n<p>Here's my reworking of your code:</p>\n\n<pre><code>def parse_headers(response):\n headers = {}\n while True:\n line = response.readline()\n if line == '\\r\\n':\n break # end of headers\n if ':' in line:\n key, value = line.split(':', 1)\n headers[key] = value\n return headers\n\ndef poll_radio():\n request = urllib2.Request(\"http://sc.buddharadio.com:80/\", headers = {\n 'User-Agent' : 'User-Agent: VLC/2.0.5 LibVLC/2.0.5',\n 'Icy-MetaData' : '1',\n 'Range' : 'bytes=0-',\n })\n # the connection will be close on exit from with block\n with contextlib.closing(urllib2.urlopen(request)) as response:\n\n headers = parse_headers(response)\n\n meta_interval = int(headers['icy-metaint'])\n response.read(meta_interval) # throw away the data until the meta interval\n\n length = ord(response.read(1)) * 16 # length is encoded in the stream\n metadata = response.read(length)\n print metadata\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T00:03:47.330",
"Id": "36022",
"Score": "0",
"body": "This is amazingly neat.My code was no way near good compared to this.However could you explain me the usage of contextlib.closing in the code and difference it makes without it.Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T00:16:20.783",
"Id": "36023",
"Score": "1",
"body": "@SteveIrwin, a `with` block automatically closes its object when exiting the `with`. (Yes, that way over-simplifid, as it can do other things depending on the object). However, the object returned by `urlopen` doesn't support the with statement. The `contextlib.closing` takes care of that, causing it to call the `.close()` method upon exiting the block."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T20:50:10.647",
"Id": "23365",
"ParentId": "23364",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23365",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T19:47:51.017",
"Id": "23364",
"Score": "4",
"Tags": [
"python",
"strings",
"parsing",
"networking"
],
"Title": "Get metadata from an Icecast radio stream"
}
|
23364
|
<p>Is there a better way to get the underscore-case version of an ActiveRecord model's name? So far this works, but it's far from ideal:</p>
<pre><code>my_active_record_instance.class.name.underscore
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T22:36:22.963",
"Id": "36017",
"Score": "0",
"body": "What do you need the name for? For certain situations, there may be shortcuts. Nothing wrong with your solution though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T01:07:20.503",
"Id": "36025",
"Score": "0",
"body": "I have several models that have associated files, stored in the public directory like this: `/pdf/#{ model_name }/#{ pubdate }/#{ filename }`. `model_name` is the variable I'm looking for to have one single method for all models. Thanks for the feedback."
}
] |
[
{
"body": "<p>You can use the <code>singular</code> method of <a href=\"http://api.rubyonrails.org/classes/ActiveModel/Naming.html\">ActiveModel::Naming</a>:</p>\n\n<pre><code>ActiveModel::Naming.singular(my_active_record_instance)\n</code></pre>\n\n<p>Alternatively, you can use the <code>model_name</code> method that's mixed in to ActiveRecord by the same <code>ActiveModel::Naming</code> module. However, it's not available on a record <em>instance</em>, so you still have to go through its class:</p>\n\n<pre><code>my_active_record_instance.class.model_name.singular\n</code></pre>\n\n<p>or call it directly on the class:</p>\n\n<pre><code>MyActiveRecord.model_name.singular\n</code></pre>\n\n<p>The <code>ActiveModel::Name</code> instance returned by <code>model_name</code> <a href=\"http://api.rubyonrails.org/classes/ActiveModel/Name.html\">contains many other inflections and name-related stuff</a>.</p>\n\n<p>You might consider making a module or concern that defines a <code>name_for_path</code> (or something) method, and which you can then include in the relevant models, so you can just call that.</p>\n\n<p>By the way, your solution is not uncommon. I looked at the source for the <a href=\"https://github.com/thoughtbot/paperclip\">Paperclip gem</a>, which constructs file paths from model names, and it does pretty much the same thing to get the model's name, (though I don't know if there's a specific reason for it, or if they too could just as well use the approaches above).</p>\n\n<p>However, if you keep your version, you should probably use <code>to_s</code> like Paperclip does:</p>\n\n<pre><code>my_active_record_instance.class.to_s.underscore\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T10:30:06.413",
"Id": "36033",
"Score": "0",
"body": "This is exactly what I was looking for. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T05:11:04.473",
"Id": "23376",
"ParentId": "23369",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "23376",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T21:30:49.583",
"Id": "23369",
"Score": "5",
"Tags": [
"ruby",
"ruby-on-rails",
"formatting",
"active-record"
],
"Title": "Underscore-case version of ActiveRecord model's name"
}
|
23369
|
<p>I made a program that allows you to assign stats. However it uses some fairly complex if-else statements. Also, someone told me that <code>goto</code> statements were bad, but why is that? I know that switch might have been a better solution, but I cannot get <code>switch</code> statements to work for string variables.</p>
<pre><code>#include <iostream>
int main()
{
using namespace std;
int strength,agility,perception,endurance,intelligence,rem_statpoints;
cout << "Please distribute you stat points" << endl;
cout << "Avaivable stat points: 10 \n" << endl;
statreset:{}
strength = 5; //Strength is set to 5 by default
agility = 5; //Agility is set to 5 by default
perception = 5; //Perception is set to 5 by default
endurance = 5; //Endurance is set to 5 by default
intelligence = 5; //Intelligence is set to 5 by default
rem_statpoints = 10; //The avaivable number of stat points
stat:{}
cout << "Strength " << strength << endl;
cout << "Agility " << agility << endl;
cout << "Perception " << perception << endl;
cout << "Endurance " << endurance << endl;
cout << "Intelligence " << intelligence << "\n" << endl;
cout << "What stat do you want to increase?" << endl;
string inc;
cin >> inc;
if (inc == "strength" or "agility" or "perception" or "endurance" or "intelligence") {
goto increase;
} else {
cout << "Please enter a valid stat, also remember to type in lower case letters" << endl;
goto stat;
}
increase:{}
cout << "How much do you want to increase " << inc << " with?" << endl;
cout << "avaivable skill points: " << rem_statpoints << endl;
int ass_statpoints;
cin >> ass_statpoints;
if (ass_statpoints > rem_statpoints) {
cout << "Insufficient stat points" << endl;
goto stat;
} else {
if (inc == "strength") {
strength = strength + ass_statpoints;
rem_statpoints = rem_statpoints - ass_statpoints;
} else {
if (inc == "agility") {
agility = agility + ass_statpoints;
rem_statpoints = rem_statpoints - ass_statpoints;
} else {
if (inc == "perception") {
perception = perception + ass_statpoints;
rem_statpoints = rem_statpoints - ass_statpoints;
} else {
if (inc == "endurance") {
endurance = endurance + ass_statpoints;
rem_statpoints = rem_statpoints - ass_statpoints;
} else {
intelligence = intelligence + ass_statpoints;
rem_statpoints = rem_statpoints - ass_statpoints;
}
}
}
}
}
cout << "Increased " << inc << " with " << ass_statpoints << "\n" << endl;
red:{}
if (rem_statpoints == 0) {
cout << "You have distributed all your stat points, are you happy with your selection?" << endl;
cout << "If you're not, you can redistribute them by typing unhappy" << endl;
cout << "To start playing, simply type play!" << endl;
} else {
goto stat;
}
string red;
cin >> red;
string statreset; //string statreset is placed here because I could not place it next to the relevant cin for some reason.
if (red == "play!") {
goto game;
} else {
cout << "Are you sure you want to reset your stat points?" << endl;
cin >> statreset; //string statreset is placed here
if (statreset == "yes") {
cout << "Resetting stats" << endl;
goto statreset;
} else {
cout << "Do you want to start playing then?" << endl;
string statresetno;
cin >> statresetno;
if (statresetno == "yes") {
goto game;
} else {
cout << "Make up you mind!" << endl;
goto red;
}
}
}
goto stat;
game:{}
{
cout << "Initializing game" << endl;
cout << "game coming soon!" << endl;
cout << "Thank you for playing!" << endl;
}
return 0;
}
/* Some one told me once that is was bad to use alot of goto statements,
* however, I can not see what damage they are causing here.
* Then again, I am not familiar with any alternatives for goto and labels,
* so I am forced to use goto!
* I really hoped you enjoyed using my program, and if this program for
* some reason helped someone else, I am glad.
* Feel free to use this code for yourself if you really found it that
* good
*
*
* Happy Trails!
* - Lemonizer
*/
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T01:57:25.323",
"Id": "36026",
"Score": "4",
"body": "Please copy/paste your code into the question as per the FAQ. Otherwise, we'll be forced to close your question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T02:30:29.173",
"Id": "36027",
"Score": "0",
"body": "Using goto is [this bad](http://imgs.xkcd.com/comics/goto.png). Further reading on it, [head over to SO](http://stackoverflow.com/a/52307)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T04:21:22.430",
"Id": "36029",
"Score": "0",
"body": "I'm not sure about this case, but it's usually recommended that you use functions instead of `goto` statements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T20:08:31.420",
"Id": "36062",
"Score": "0",
"body": "Learn to format your code. Websites don;t like tabs so remove them before posting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T20:09:05.977",
"Id": "36064",
"Score": "0",
"body": "Yes. goto in this context is very bad. It makes the code really hard to read. Break this into functions. The above was re-formatted with a real cod eeditor `vim`. Sequence `<ctrl-v>0G=` redoes indent correctly. `:% s/^/ /g` adds 4 space to the front of each line."
}
] |
[
{
"body": "<p>You would have to refactor this a few times to make it perfect, these are my suggestions for starters.</p>\n\n<ul>\n<li><p>Naming your variables a,b,c,d,e,s is bad form. You could have called them strength, agility, endurance, etc.</p></li>\n<li><p>One way to avoid your long if statement is using a 'stat' array instead of having separate variables. This way you could ask the user which stat to increase</p>\n\n<ul>\n<li>1) Strength</li>\n<li>2) Dexterity</li>\n<li>3) Strength\netc.</li>\n</ul></li>\n</ul>\n\n<p>The entered numbered minus 1 would be the stat to enhance. Also typing a number is funner than typing stat names.</p>\n\n<ul>\n<li>Finally, google 'functions' and instead of using labels, create functions and call those.</li>\n</ul>\n\n<p>T.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T03:31:40.313",
"Id": "23374",
"ParentId": "23372",
"Score": "6"
}
},
{
"body": "<p>Please put one variable per line:</p>\n\n<pre><code> int strength,agility,perception,endurance,intelligence,rem_statpoints;\n</code></pre>\n\n<p>That is really hard to read:<br>\nIt would be even better to wrap this in a structure (one day you may have 2 players at the same time).</p>\n\n<pre><code>struct Player\n{\n int strength;\n int agility;\n int perception;\n int endurance;\n int intelligence;\n};\nint rem_statpoints; // not part of a player.\n // as it is just used during player creation\n</code></pre>\n\n<p>Would it not be easier to make this a function/method:</p>\n\n<pre><code>statreset:{}\n strength = 5; //Strength is set to 5 by default\n agility = 5; //Agility is set to 5 by default\n perception = 5; //Perception is set to 5 by default\n endurance = 5; //Endurance is set to 5 by default\n intelligence = 5; //Intelligence is set to 5 by default\n rem_statpoints = 10; //The avaivable number of stat points\n\nvoid Player::statreset(int& rem_statpoints)\n{\n strength = 5; //Strength is set to 5 by default\n agility = 5; //Agility is set to 5 by default\n perception = 5; //Perception is set to 5 by default\n endurance = 5; //Endurance is set to 5 by default\n intelligence = 5; //Intelligence is set to 5 by default\n rem_statpoints = 10; //The avaivable number of stat points\n}\n</code></pre>\n\n<p>This looks like another mehtod to me:</p>\n\n<pre><code>stat:{}\n cout << \"Strength \" << strength << endl;\n cout << \"Agility \" << agility << endl;\n cout << \"Perception \" << perception << endl;\n cout << \"Endurance \" << endurance << endl;\n cout << \"Intelligence \" << intelligence << \"\\n\" << endl;\n cout << \"What stat do you want to increase?\" << endl;\n</code></pre>\n\n<p>This is not doing what you think it is doing.<br>\nI am surprised if this even works as it should always return true.</p>\n\n<pre><code> string inc;\n cin >> inc;\n if (inc == \"strength\" or \"agility\" or \"perception\" or \"endurance\" or \"intelligence\")\n\n // what you really want is:\n if (inc == \"strength\" || inc == \"agility\" || inc == \"perception\" ... etc\n</code></pre>\n\n<p>The comment at the end: </p>\n\n<pre><code>/* Some one told me once that is was bad to use alot of goto statements,\n * however, I can not see what damage they are causing here.\n</code></pre>\n\n<p>I can.\nYou are tightly binding your control flow logic.<br>\nThis makes it hard to introduce new steps or alter the logic.<br>\nFollowing the logic in this code is even worse. It is the perfect example of spaghetti. If it works fine then great. But try following the logic when something breaks. This becomes a maintenance nightmare.</p>\n\n<pre><code> * Then again, I am not familiar with any alternatives for goto and labels,\n * so I am forced to use goto!\n</code></pre>\n\n<p>Alternatives:<br>\nCombine the following:</p>\n\n<pre><code> if (<test>) {<code>} else {<code>}\n for(<init>;<test>;<upd>) {<code>}\n while(<test>) {<code>}\n do {<code>} while(<test>)\n\n <function name>(<Parameter list>) \n</code></pre>\n\n<p>You can reduce the complexity of you of tree like this:</p>\n\n<pre><code> if (<cond1>)\n {\n }\n else if (<cond2>)\n {\n }\n else if (<cond3>)\n {\n }\n else if (<cond4>)\n {\n }\n // ...etc\n else\n {\n }\n</code></pre>\n\n<p>I would restructure the code like this:</p>\n\n<pre><code> int main()\n {\n Player player1;\n do\n {\n generatePlayer(player1);\n }\n while(!isUserSatisfied());\n\n playGame();\n }\n</code></pre>\n\n<p>Then generatePlayer()</p>\n\n<pre><code> void generatePlayer(Player& player)\n {\n int extraPoints;\n\n player.statreset(extraPoints);\n while(extraPoints > 0)\n {\n std::cout << player;\n\n std::string inc;\n int amount;\n do\n {\n std::cout << \"Attribute you want to modify?\\n\";\n std::cin >> inc;\n }\n while(!isValidAttribute(inc));\n\n do\n {\n std::cout << \"You have \" << extraPoints << \" to play with\\n\";\n std::cin >> amount;\n }\n while(amount > extraPoints);\n\n player.modifyAttribute(inc, amount);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:07:53.547",
"Id": "36113",
"Score": "0",
"body": "Holy Moly. Did not expect such a thorough answer! Thank you! I will follow this to the last line, and try to do as you suggest!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T20:34:23.937",
"Id": "23399",
"ParentId": "23372",
"Score": "8"
}
},
{
"body": "<p>I wouldn't store my stats as hard-coded variables. You could store your stats inside of a map like this:</p>\n\n<pre><code>#include <map>\n#include <string>\n#include <iostream>\n\nclass Player\n{\npublic:\n Player()\n : m_StatPoints(10)\n {}\n\n int getStat(const std::string& statName) const\n {\n std::map<std::string, int>::const_iterator stat = m_Stats.find(statName);\n\n if (stat == m_Stats.end())\n {\n throw \"exception\"; //Add real exception here\n }\n\n return stat->second;\n }\n\n void addStat(const std::string& statName)\n {\n m_Stats.insert(std::make_pair(statName, 5));\n }\n\n void increaseStat(const std::string& statName, int points)\n {\n if (m_StatPoints - points >= 0)\n {\n m_Stats.at(statName) += points;\n m_StatPoints -= points;\n\n std::cout << \"increased \" << statName << \" by \" << points << \" points.\\n\";\n }\n else\n {\n std::cout << \"insufficient stat points\";\n }\n }\n\n void resetStats()\n {\n typedef std::map<std::string, int>::iterator StatIterator;\n\n for (StatIterator currentStat = m_Stats.begin(); currentStat != m_Stats.end(); ++currentStat)\n {\n currentStat->second = 5;\n }\n\n m_StatPoints = 10;\n }\n\nprivate:\n std::map<std::string, int> m_Stats;\n int m_StatPoints;\n};\n\nint main()\n{\n Player player;\n\n player.addStat(\"int\");\n player.addStat(\"dex\");\n player.addStat(\"str\");\n player.addStat(\"luck\");\n player.addStat(\"wid\");\n\n player.increaseStat(\"str\", 1);\n player.increaseStat(\"int\", 4);\n\n std::cout << \"the intelligence value of your player is: \" << player.getStat(\"int\");\n std::cout << \"the strength value of your player is: \" << player.getStat(\"str\");\n\n return 0;\n}\n</code></pre>\n\n<p>If you store your character info inside of a map you will have it more easy to extend your character later. You could even add stats over a textfile without specificly mentioning them inside of your program first. That way you are much more felxible.</p>\n\n<p>Furthermore you should use functions instead of lables since <code>goto</code> is pretty dangerous and that way your code looks very chaotic.</p>\n\n<p>A function is implemented as followed:</p>\n\n<pre><code>returnType functionName (parameter) { what you want to do }\n</code></pre>\n\n<p>for example:</p>\n\n<pre><code>void printThisNumber(int number)\n{\n std::cout << number;\n}\n</code></pre>\n\n<p>or with a return type:</p>\n\n<pre><code>int getMeNumberFive()\n{\n return 5;\n}\n</code></pre>\n\n<p>and is called as followed:</p>\n\n<pre><code>printThisNumber(5);\n\nint i = getMeNumberFive();\n</code></pre>\n\n<p>Simply google for functions, there are a lot of tutorials out there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-09T14:09:16.570",
"Id": "191604",
"ParentId": "23372",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "23399",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T00:37:20.650",
"Id": "23372",
"Score": "5",
"Tags": [
"c++",
"game"
],
"Title": "Assigning stats in a game"
}
|
23372
|
<p>I got a ton of helpful tips last time I posted some code, so I thought I would come back to the well.</p>
<p>My function is deciding whether or not the <code>secretWord</code> has been guessed in my hangman game. I am trying to accomplish this by taking a list, <code>lettersGuessed</code>, and comparing it to the char in each index of the string <code>secretWord</code>. My code works, but I feel as though it is not optimal nor formatted well.</p>
<pre><code>def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
chars = len(secretWord)
place = 0
while place < chars:
if secretWord[0] in lettersGuessed:
place += 1
return isWordGuessed(secretWord[1:], lettersGuessed)
else:
return False
return True
</code></pre>
<p>I tried to use a for loop (<code>for i in secretWord:</code>) originally, but I could not get my code to return both True and False. It would only do one or the other, which is how I ended up with the while loop. It seems that <code>while</code> loops are discouraged/looked at as not very useful. Is this correct?</p>
<p>Also, I am wondering if the recursive call is a good way of accomplishing the task.</p>
|
[] |
[
{
"body": "<p>Because we always return from the inside of the while, we'll never perform the loop more than once. Thus, your while actually acts like an <code>if</code>. Thus the value of <code>place</code> is not really used and you can get rid of it : <code>if place < chars</code> becomes <code>if 0 < chars</code> which is <code>if chars</code> which is <code>if len(secretWord)</code> which is really <code>if secretWord</code> because of the way Python considers the empty string as a false value.\nThus, you code could be :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n if secretWord:\n if secretWord[0] in lettersGuessed:\n return isWordGuessed(secretWord[1:], lettersGuessed)\n else:\n return False\n return True\n</code></pre>\n\n<p>Which can be re-written as :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n if secretWord:\n return secretWord[0] in lettersGuessed and isWordGuessed(secretWord[1:], lettersGuessed)\n return True\n</code></pre>\n\n<p>which is then nothing but :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n return not secretWord or secretWord[0] in lettersGuessed and isWordGuessed(secretWord[1:], lettersGuessed)\n</code></pre>\n\n<p>Now, if I was to write the same function, because it is so easy to iterate on strings in Python, I'd probably avoid the recursion and so something like :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n for letter in secretWord:\n if letter not in lettersGuessed:\n return False\n return True\n</code></pre>\n\n<p>Then, there might be a way to make this a one-liner but I find this to be pretty easy to understand and pretty efficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-18T00:15:37.170",
"Id": "401411",
"Score": "0",
"body": "If you wanted a one-liner for your final code, you could do `return all(letter in lettersGuessed for letter in secretWord)`; the Python default built-ins [`all()`](https://docs.python.org/3/library/functions.html#all) and [`any()`](https://docs.python.org/3/library/functions.html#any) are good tricks to have up your sleave for crafting concise Python code. I actually think it's equally clear too, so (IMO) it's even better than your current final version."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T06:51:44.373",
"Id": "23378",
"ParentId": "23375",
"Score": "7"
}
},
{
"body": "<p>You could think in sets of letters:</p>\n\n<pre><code>def is_word_guessed(secret_word, letters_guessed):\n\n return set(secret_word) <= set(letters_guessed)\n</code></pre>\n\n<p>Edit: to improve the answer as codesparkle suggested:</p>\n\n<p>The main benefit is the clarity of expression - the reader of the code doesn't need to run a double loop, or a recursive function in his/her head to understand it.</p>\n\n<p>The function and parameter names were changed in order to comply with <a href=\"http://www.python.org/dev/peps/pep-0008/#id32\" rel=\"noreferrer\" title=\"PEP8\">the Style Guide for Python Code</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-08T21:37:14.173",
"Id": "36437",
"Score": "0",
"body": "Interesting answer! Could you explain the benefits of using sets and maybe explain your renaming of the method to conform to python naming conventions? Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T18:59:24.637",
"Id": "525352",
"Score": "0",
"body": "@pjz I don't think `==` works either because that would only tell you if the two sets were identical (i.e., the guessed letters exactly matched the secret letters and had no additional extra letters). Personally my first thought was to use sets, but I'd probably use the built in functions, namely `issubset`. This would then be `set(secret_word).issubset(set(letters_guessed)` which would tell you if all the letters in your secret word are contained in your guessed letters. The built in functions should be more clear than `<=` about their purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T20:25:45.950",
"Id": "525429",
"Score": "1",
"body": "@zephyr I completely misread the code. You're completely correct. That said, I think the `all(letter in letters_guessed for letter in secret_word)` is the most readable solution."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-08T21:30:01.477",
"Id": "23631",
"ParentId": "23375",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "23378",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T05:01:59.713",
"Id": "23375",
"Score": "5",
"Tags": [
"python",
"hangman"
],
"Title": "In my Hangman game, one of my functions is correct but messy"
}
|
23375
|
<p>This is my python solution to the first problem on Project Euler:</p>
<pre><code>n = 1
rn = 0
while n < 1000:
if n%3 == 0 or n%5 == 0:
rn += n
n = n + 1
print(rn)
</code></pre>
<p>I would like to find a way to keep everything in this python code to as little number of lines as possible (maybe even a one liner??), and possibly improve the speed (it's currently around 12 ms). By the way, this is the problem: <blockquote>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p>
<p>Find the sum of all the multiples of 3 or 5 below 1000.</blockquote>Suggestions?<br />Thanks.<br /></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T21:28:10.807",
"Id": "63715",
"Score": "1",
"body": "`sum(n for n in range(1000) if not n%3 or not n%5)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-04T08:50:05.540",
"Id": "232506",
"Score": "0",
"body": "I like your solution to the problem. It is much more efficiently coded than another Project Euler #1 code question I just read."
}
] |
[
{
"body": "<p><strong>Python hint number 1:</strong></p>\n\n<p>The pythonic way to do :</p>\n\n<pre><code>n = 1\nwhile n < 1000:\n # something using n\n n = n + 1\n</code></pre>\n\n<p>is :</p>\n\n<pre><code>for n in range(1,1000):\n # something using n\n</code></pre>\n\n<p><strong>Python hint number 2:</strong></p>\n\n<p>You could make your code a one-liner by using list comprehension/generators :</p>\n\n<pre><code>print sum(n for n in range(1,1000) if (n%3==0 or n%5==0))\n</code></pre>\n\n<p>Your code works fine but if instead of 1000, it was a much bigger number, the computation would take much longer. A bit of math would make this more more efficient.</p>\n\n<p><strong>Math hint number 1 :</strong></p>\n\n<p>The sum of all the multiples of 3 or 5 below 1000 is really the sum of (the sum of all the multiples of 3 below 1000) plus (the sum of all the multiples of 5 below 1000) minus the numbers you've counted twice.</p>\n\n<p><strong>Math hint number 2 :</strong></p>\n\n<p>The number you've counted twice are the multiple of 15.</p>\n\n<p><strong>Math hint number 3 :</strong></p>\n\n<p>The sum of the multiple of 3 (or 5 or 15) below 1000 is the <a href=\"http://en.wikipedia.org/wiki/Arithmetic_progression#Sum\">sum of an arithmetic progression.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T13:02:15.763",
"Id": "36037",
"Score": "0",
"body": "Oh, sorry, my mistake, I inputted `100` instead of `1000` @Josay"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T17:04:20.053",
"Id": "36050",
"Score": "2",
"body": "Math hint #4: every number that is divideable by an odd number is an odd number itself (so you can skip half of the loop iterations). @Lewis"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T12:37:59.057",
"Id": "23380",
"ParentId": "23379",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "23380",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T11:41:15.993",
"Id": "23379",
"Score": "5",
"Tags": [
"python",
"project-euler"
],
"Title": "Project Euler Problem 1"
}
|
23379
|
<p>Here is my method:</p>
<pre><code>public JsonResult ValidateAll(string toys)
{
Dictionary<string, object> res = new Dictionary<string, object>();
List<string> result_check = new List<string>();
string[] lines = toys.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string toyName = line;
string toy_tmp = toyName.Trim();
string toy_tmp2 = HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(toyName)).Replace("&#228;", "&auml;").Trim();
string toy_tmp3 = toyName.Replace("\u00a0", " ").Trim();
string toy_tmp4 = HttpUtility.HtmlDecode(toyName.Trim());
string toy_tmp5 = HttpUtility.HtmlDecode(toyName.Replace("\u00a0", " ").Replace(" ", " ").Trim());
string tableInDatabase = "";
//Check if the toy is a doll
tblDoll doll = (from x in db.tblDoll
where (x.doll_name == toy_tmp || x.doll_name == toy_tmp2 || x.doll_name == toy_tmp3 || x.doll_name == toy_tmp4 || x.doll_name == itoy_tmp5)// || x.doll_name == toy_tmp6)
select x)
.FirstOrDefault();
if (doll != null)
{
table = "doll";
result_check.Add("1");
continue;
}
if (table == "")
{
var car = (from x in db.tblCar
where (x.car_name == toy_tmp || x.car_name == toy_tmp2 || x.car_name == toy_tmp3 || x.car_name == toy_tmp4)
select y).FirstOrDefault();
if (car != null)
{
table = "car";
result_check.Add("1");
continue;
}
}
//Do the same as for Car and Doll, do it for Plane and Boat too
}
res.Add("ok", result_check);
return Json(res, JsonRequestBehavior.AllowGet);
</code></pre>
<p>}</p>
<p>What I'm trying to do is this: the input string is a name of a toy. I have four tables for toys in my db: Car, Doll, Plane, Boat. I need to find in which table is the toy (the input string).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T13:25:03.057",
"Id": "36038",
"Score": "1",
"body": "What is it supposed to do, and what are you looking for? What does the input look like? A bit more context might be helpful here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T17:17:00.217",
"Id": "36052",
"Score": "0",
"body": "@GCATNM I added something, pls see."
}
] |
[
{
"body": "<p>Well without any context I am going to go out on a limb and take a stab at this anyway. </p>\n\n<p>First is if you are using a database, and have the ability to check for toy ID's instead of the toy names you won't have as many checks. it would require a little more work to pass in the string, but it would be very hard to change in the future if you get new toy names. IDs are a way of future proofing.</p>\n\n<p>One trick of refactoring is to look at code that does the same thing and pulling it out into its own method. This is how I see your code working out.</p>\n\n<pre><code>public JsonResult ValidateAll(string toys)\n{\n Dictionary<string, object> res = new Dictionary<string, object>();\n List<string> result_check = new List<string>();\n\n string[] lines = toys.Split(new string[] { \"\\n\" }, StringSplitOptions.RemoveEmptyEntries);\n\n foreach (string line in lines)\n {\n var doll = CheckForToy(db.tblDoll, line);\n if(AddResult(doll, \"doll\", ref result_check))\n continue;\n\n if (table == \"\")\n {\n var car = CheckForToy(db.tblCar, line);\n if (AddResult(car, \"car\", ref result_check))\n continue;\n }\n var plane = CheckForToy(db.tblPlane, line)\n if(AddResult(plane, \"plane, ref result_check))\n continue;\n\n var boat = CheckForToy(db.tblBoat, line)\n if(AddResult(boat, \"boat, ref result_check))\n continue;\n //Do the same as for Car and Doll, do it for Plane and Boat too\n }\n res.Add(\"ok\", result_check);\n return Json(res, JsonRequestBehavior.AllowGet);\n}\nprivate string CheckForToy(Table table, string line)\n{\n string toyName = line;\n\n string toy_tmp = toyName.Trim();\n string toy_tmp2 = HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(toyName)).Replace(\"&#228;\", \"&auml;\").Trim();\n string toy_tmp3 = toyName.Replace(\"\\u00a0\", \" \").Trim();\n string toy_tmp4 = HttpUtility.HtmlDecode(toyName.Trim());\n string toy_tmp5 = HttpUtility.HtmlDecode(toyName.Replace(\"\\u00a0\", \" \").Replace(\" \", \" \").Trim());\n\n string tableInDatabase = \"\";\n\n //Check if the toy is a doll\n tblDoll toy = (from x in table\n where (x.doll_name == toy_tmp || x.doll_name == toy_tmp2 || x.doll_name == toy_tmp3 || x.doll_name == toy_tmp4 || x.doll_name == itoy_tmp5)// || x.doll_name == toy_tmp6)\n select x)\n .FirstOrDefault();\n return toy;\n}\nprivate bool AddResult(Toy toy, string toyType, ref List<String> result)\n{\n if(toy != null)\n {\n table = toyType;\n result.Add(\"1\");\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>There is probably even more ways to refactor my code, but without better context that is the best I can do. This is where having unit tests is super useful because you can continue to run your test every time you make a change to it to clean it up. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T14:24:13.867",
"Id": "36039",
"Score": "1",
"body": "The `CheckForToy()` method unfortunately can't be that simple - the LINQ query is needed separately for each kind of toy, because they're apparently all different tables and types."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T14:09:28.163",
"Id": "23384",
"ParentId": "23381",
"Score": "1"
}
},
{
"body": "<p>Here's a crack at a bit of code. It's probably worth mentioning though that I don't think your code could even compile or if it does your missing variables i.e. itoy_tmp5...</p>\n\n<p>Either way, like Robert said I looked for some patterns that seemed to be repeating and started from there. I extracted the first part to a method and then extracted again etc etc</p>\n\n<p>Here's the code anyway if it helps.</p>\n\n<pre><code> private string[] GetPossibleNames(string toyName)\n {\n return new []\n {\n toyName,\n HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(toyName)).Replace(\"&#228;\", \"&auml;\"),\n toyName.Replace(\"\\u00a0\", \" \"),\n HttpUtility.HtmlDecode(toyName),\n HttpUtility.HtmlDecode(toyName.Replace(\"\\u00a0\", \" \"))\n };\n }\n\n private bool IsToyFor<T>(Table<T> table, string[] possibleToyNames, Func<T,string> getName)\n {\n return table.Any(p => possibleToyNames.Contains(getName(p)));\n }\n\n private bool HasInterestingToy(string[] possibleToyNames)\n {\n return IsToyFor(db.tblDoll, possibleToyNames, p => p.doll_name) ||\n IsToyFor(db.tblDoll, possibleToyNames, p => p.car_name);\n //Do the same as for Car and Doll, do it for Plane and Boat too\n }\n\n public JsonResult ValidateAll(string toys)\n {\n Dictionary<string, object> res = new Dictionary<string, object>();\n var resultCheck = new List<string>();\n\n string[] lines = toys.Split(new [] {\"\\n\"}, StringSplitOptions.RemoveEmptyEntries);\n\n foreach (string line in lines)\n {\n string[] possibleToyNames = GetPossibleNames(line.Trim());\n\n if (HasInterestingToy(possibleToyNames)) resultCheck.Add(\"1\"); \n }\n\n res.Add(\"ok\", resultCheck);\n return Json(res, JsonRequestBehavior.AllowGet);\n } \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T07:53:20.280",
"Id": "36082",
"Score": "0",
"body": "What should I put instead of T in IsToyFor??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T08:57:49.067",
"Id": "36087",
"Score": "0",
"body": "I was only guess at the types of tblCar etc but perhaps T might be the type of the base class for Car etc i.e. Entity ??"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T02:30:57.313",
"Id": "23411",
"ParentId": "23381",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23411",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T13:03:03.623",
"Id": "23381",
"Score": "0",
"Tags": [
"c#",
"optimization",
"entity-framework"
],
"Title": "How to optimize/refactor this method?"
}
|
23381
|
<p>You might have read my question on shortening my code to a one-liner for Problem 1. So, I was wondering, is there any more tricks of the trade to shorten my <a href="http://projecteuler.net/problem=2" rel="nofollow">Problem 2</a> solution:</p>
<pre><code>fib = [0, 1]
final = 1
ra = 0
while final < 4000000:
fib.append(fib[-1] + fib[-2])
final = fib[-1]
fib.pop()
for a in fib:
if a%2 == 0:
ra += a
print(ra)
</code></pre>
<p>Down to one line??<br />
This is the official Problem 2 question:<blockquote>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p>
<p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p>
<p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</blockquote>
Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T15:59:51.477",
"Id": "36044",
"Score": "5",
"body": "Writing everything in a single line is rarely a good idea. Why not strive for the most expressive, readable version, regardless of the number of lines?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T08:52:43.310",
"Id": "36084",
"Score": "0",
"body": "please note that the sharing projecteuler solutions outside the scope of the website is not appreciated. See http://projecteuler.net/about (after loggin in)"
}
] |
[
{
"body": "<p>The first few are probably OK, but you really shouldn't be publishing solutions to Project Euler problems online: don't spoil the fun for others!</p>\n\n<p>This said, there are several things you could consider to improve your code. As you will find if you keep doing Project Euler problems, eventually efficiency becomes paramount. So to get the hang of it, you may want to try and write your program as if being asked for a much, much larger threshold. So some of the pointers I will give you would generally be disregarded as micro optimizations, and rightfully so, but that's the name of the game in Project Euler!</p>\n\n<p>Keeping the general structure of your program, here are a few pointers:</p>\n\n<ul>\n<li>Why start with <code>[0, 1]</code> when they tell you to go with <code>[1, 2]</code>? The performance difference is negligible, but it is also very unnecessary.</li>\n<li>You don't really need several of your intermediate variables.</li>\n<li>You don't need to <code>pop</code> the last value, just ignore it when summing.</li>\n<li>An important thing is that in the Fibonacci sequence even numbers are every third element of the sequence, so you can avoid the divisibility check.</li>\n</ul>\n\n<p>Putting it all together:</p>\n\n<pre><code>import operator\n\ndef p2bis(n) :\n fib = [1, 2]\n while fib[-1] < n :\n fib.append(fib[-1] + fib[-2])\n return reduce(operator.add, fib[1:-1:3])\n</code></pre>\n\n<p>This is some 30% faster than your code, not too much, but the idea of not checking divisibility, but stepping in longer strides over a sequence, is one you want to hold to:</p>\n\n<pre><code>In [4]: %timeit p2(4000000)\n10000 loops, best of 3: 64 us per loop\n\nIn [5]: %timeit p2bis(4000000)\n10000 loops, best of 3: 48.1 us per loop\n</code></pre>\n\n<p>If you wanted to really streamline things, you could get rid of the list altogether and keep a running sum while building the sequence:</p>\n\n<pre><code>def p2tris(n) :\n a, b, c = 1, 1, 2\n ret = 2\n while c < n :\n a = b + c\n b = c + a\n c = a + b\n ret += c\n return ret - c\n</code></pre>\n\n<p>This gives a 7x performance boost, not to mention the memory requirements:</p>\n\n<pre><code>In [9]: %timeit p2tris(4000000)\n100000 loops, best of 3: 9.21 us per loop\n</code></pre>\n\n<p>So now you can compute things that were totally unthinkable before:</p>\n\n<pre><code>In [19]: %timeit p2tris(4 * 10**20000)\n1 loops, best of 3: 3.49 s per loop\n</code></pre>\n\n<p>This type of optimization eventually becomes key in solving more advanced problems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T20:09:36.963",
"Id": "36065",
"Score": "0",
"body": "`p2tris` seems to be computing something slightly different than `p2bis`: it's off by 2."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T05:20:07.447",
"Id": "36081",
"Score": "0",
"body": "@DSM Thanks for checking my code! It is solved now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T16:31:49.990",
"Id": "23387",
"ParentId": "23383",
"Score": "2"
}
},
{
"body": "<p>Rather than trying to cram everything into one line, I'd try to put things in small discrete units which map closely to the problem requirements.</p>\n\n<p>We need to sum (1) the terms in the Fibonacci sequence (2) whose values don't exceed 4 million (3) which are even.</p>\n\n<p>And so I'd write something like this:</p>\n\n<pre><code>from itertools import takewhile\n\ndef gen_fib():\n f0, f1 = 0, 1\n while True:\n yield f0\n f0, f1 = f1, f0+f1\n\nlimit = 4000000\nlow_fibs = takewhile(lambda x: x <= limit, gen_fib())\neven_total = sum(f for f in low_fibs if f % 2 == 0)\nprint(even_total)\n</code></pre>\n\n<p>where <code>gen_fib</code> yields the Fibonacci terms in sequence, <code>low_fibs</code> is an iterable object which yields terms until (and not including) the first term which is > 4000000, and <code>even_total</code> is the sum of the even ones. You could combine the last two into one line, if you wanted, but why?</p>\n\n<p>This has the advantage of never materializing one big list, as the terms are produced and consumed as needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T19:46:16.133",
"Id": "36061",
"Score": "0",
"body": "I was doing some timings, and with Python 2.7 `sum` appeared to be extremely slow compared to `reduce` or plain summing in a for loop. Maybe I had numpy running in the background, and there was something going on there, but I was very surprised."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T20:08:57.010",
"Id": "36063",
"Score": "0",
"body": "@Jaime: I can't reproduce that. genexps often show performance hits relative to loops/listcomps, but I don't see a major difference. `sum(i for i in xrange(10) if i % 2 == 0)` is only ~20% slower than the equivalent for loop version, and the difference becomes negligible in longer cases."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T16:41:12.940",
"Id": "23388",
"ParentId": "23383",
"Score": "2"
}
},
{
"body": "<p>In one line (plus an <code>import</code>):</p>\n\n<pre><code>from math import floor, log, sqrt\n(int(round((pow((1+sqrt(5))/2,2+floor(log(4e6*sqrt(5),(1+sqrt(5))/2)))/sqrt(5))))-1)//2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T20:43:39.540",
"Id": "36067",
"Score": "2",
"body": "Congratulations on a successful *defactoring* of the original code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T18:42:12.963",
"Id": "23395",
"ParentId": "23383",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "23387",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T13:44:49.857",
"Id": "23383",
"Score": "2",
"Tags": [
"python",
"project-euler",
"fibonacci-sequence"
],
"Title": "Project Euler - Shortening Problem 2"
}
|
23383
|
<p>I have to implement a class with has parent and child fields. The problem is that by adding a child it must immediately keep reference to its' parent. I implemented it and it seems to work but I am not quite sure if I did it right. Any advice will be useful!</p>
<pre><code>namespace DocumentToDocument
{
public class MyEventArgs<T>: EventArgs
{
public T D;
}
public class MyList<T> : List<T>
{
public event EventHandler OnAdd;
public new void Add(T item)
{
if (null != OnAdd)
{
var m = new MyEventArgs<Document> {D = item as Document};
OnAdd(this, m);
}
base.Add(item);
}
}
public class Document
{
public Document()
{
Children = new MyList<Document>();
Children.OnAdd += new EventHandler(Children_OnAdd);
}
public string Name;
public Document Parent;
public MyList<Document> Children;
public void Children_OnAdd(object sender, EventArgs e)
{
((MyEventArgs<Document>) e).D.Parent = this;
}
}
class Program
{
private static void Main(string[] args)
{
var d = new Document {Name = "I am a parent"};
var dd = new Document {Name = "I am a child"};
d.Children.Add(dd);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T15:08:38.600",
"Id": "36040",
"Score": "0",
"body": "I can't test it right now, but I think this will only work as long as the list of children is explicitly referenced as `MyList<>` - when used as `List<>` or `IList<>` the original implementation of `Add()` would come to bear. This violates the Liskov Substitution Principle and would cause problems when using any LINQ extension methods that may use `Add()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T15:18:59.713",
"Id": "36041",
"Score": "0",
"body": "Good answer, GCATNM. But I have no idea how to implement this event with List<> as this datatype has no built-in OnAdd Event"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T15:59:49.603",
"Id": "36043",
"Score": "1",
"body": "Micha, have you thought about implementing [IList](http://msdn.microsoft.com/en-us/library/5y536ey6.aspx) instead of inheriting List? You could keep using List as your underlying storage implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T20:12:48.367",
"Id": "36066",
"Score": "0",
"body": "Yes, I implemented IList. Seems more mature )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T22:39:07.967",
"Id": "36071",
"Score": "0",
"body": "It's certainly a much cleaner way. Replacing members with `new` is hardly ever a good solution, and particularly so in this case, as what you actually want is an override, but `new` can't give you that."
}
] |
[
{
"body": "<p>Here's how I might restructure it (note, I've removed many of the generics since it seems to be tied to <code>Document</code> - if you do need those classes to go for other types, go back to the generics, otherwise, YAGNI):</p>\n\n<pre><code>namespace DocumentToDocument\n{\n using System;\n using System.Collections.Generic;\n\n public sealed class MyEventArgs : EventArgs\n {\n private readonly Document document;\n\n public MyEventArgs(Document document)\n {\n this.document = document;\n }\n\n public Document Document\n {\n get\n {\n return this.document;\n }\n }\n }\n\n public sealed class MyList : List<Document>\n {\n public event EventHandler<MyEventArgs> OnAdd;\n\n public new void Add(Document item)\n {\n var onAdd = this.OnAdd;\n\n if (onAdd != null)\n {\n onAdd(this, new MyEventArgs(item));\n }\n\n base.Add(item);\n }\n }\n\n public sealed class Document\n {\n private readonly MyList children = new MyList();\n\n private readonly string name;\n\n private Document parent;\n\n public Document(string name, Document parent = null)\n {\n this.name = name;\n this.parent = parent;\n if (this.parent != null)\n {\n this.parent.Children.Add(this);\n }\n\n this.children.OnAdd += (sender, e) => e.Document.Parent = this;\n }\n\n public string Name\n {\n get\n {\n return this.name;\n }\n }\n\n public Document Parent\n {\n get\n {\n return this.parent;\n }\n\n set\n {\n this.parent = value;\n }\n }\n\n public MyList Children\n {\n get\n {\n return this.children;\n }\n }\n }\n\n internal static class Program\n {\n private static void Main()\n {\n var d = new Document(\"I am a parent\");\n var dd = new Document(\"I am a child\", d);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T19:18:40.187",
"Id": "23396",
"ParentId": "23385",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23396",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T15:00:43.373",
"Id": "23385",
"Score": "5",
"Tags": [
"c#",
".net"
],
"Title": "Child/Parent relationship by adding an element to list"
}
|
23385
|
<p>In the following piece of code I use the same trick three times. But cannot figure out how to write a common function that will do it for all of them. I know there is a toggle method in jQuery that does something similar but in this situation I wasn't able to get it do the job for me, so I wrote this:</p>
<pre><code>// fallback for ie
if (navigator.appName == "Microsoft Internet Explorer") {
var flag = true;
$(".right-arrow").click(function () {
if (flag) {
$(".slider-frame").animate({ left: "-130px" }, 1000);
flag = false;
}
else {
$(".slider-frame").animate({ left: "236px" }, 1000);
flag = true;
}
return false;
});
}
// more smooth CSS3-animation with move.js
else {
var flag = true;
$(".right-arrow").click(function () {
if (flag) {
move(".slider-frame").set("left", -130).duration("1s").end();
flag = false;
}
else {
move(".slider-frame").set("left", 236).duration("1s").end();
flag = true;
}
return false;
});
}
// eye that make passwords visible
var state = true;
$(".login-form form").append("<div class='eye'></div>");
$(".eye").click(function () {
if (state) {
$("#password").attr("type", "text");
$(".eye").css("background-position", "0 -49px");
state = false;
}
else {
$("#password").attr("type", "password");
$(".eye").css("background-position", "0 0");
state = true;
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T16:30:23.957",
"Id": "36046",
"Score": "2",
"body": "First off, before trying to DRY up your code, I'd suggest applying some more important concepts. For once, I'd suggest using proper feature detection instead of sniffing the `appName`. IE10 supports CSS3 animations, while old non-IE browsers do not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T16:48:13.873",
"Id": "36048",
"Score": "1",
"body": "You need to place your code into some functions. That you can reuse your code."
}
] |
[
{
"body": "<p>Here's how to DRY it up:</p>\n\n<pre><code>var flag = true,\n isIE = navigator.appName == \"Microsoft Internet Explorer\";\n\n$(\".right-arrow\").click(function () {\n if (isIE) {\n $(\".slider-frame\").animate({ left: flag ? \"-130px\" : \"236px\" }, 1000);\n }\n else {\n move(\".slider-frame\").set(\"left\", flag ? -130 : 236).duration(\"1s\");\n } \n flag = ! flag;\n return false;\n});\n</code></pre>\n\n<hr>\n\n<p>As pointed out by @FabrícioMatté, you should <a href=\"https://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr\">use feature detection</a> instead of browser sniffing.</p>\n\n<hr>\n\n<p><strong>P.S.</strong> You should also learn to <a href=\"http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-jquery-newbs-stop-jumping-in-the-pool/\" rel=\"nofollow noreferrer\">cache your selectors</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T16:50:03.137",
"Id": "23389",
"ParentId": "23386",
"Score": "2"
}
},
{
"body": "<p>Here's an idea about some things you can do to make it leaner.</p>\n\n<p>For each item that needs a click event, create an Immediately Executing Function. This will allow you to give local scope and not have a bazillion variables in the same scope to keep track of.</p>\n\n<p>next, see what comonalities you can find for each IEF, and bring them to the top of the IEF.</p>\n\n<p>I never like to attach event handlers via if/then statements. I'd rather figure out what I need to attach via if/then/whatever and only then attach.</p>\n\n<p>Here's a start for \".slider-frame\".</p>\n\n<pre><code>(function(){\n var selector = \".slider-frame\",\n clickmethod, \n flag = true, \n measures = [236, -130]; \n //this could be handled better, but whatever, fixing this wasn't the request\n if (navigator.appName == \"Microsoft Internet Explorer\") {\n clickmethod = function(){\n var value = measures[Number(flag)] + \"px\";\n $(selector).animate({ left: value }, 1000);\n flag = !flag;\n }\n }\n // more smooth CSS3-animation with move.js\n else {\n clickmethod = function(){\n var value = measures[Number(flag)];\n move(selector).set(\"left\", value).duration(\"1s\").end();\n flag = !flag;\n }\n }\n $(\".right-arrow\").click(clickmethod);\n})();\n</code></pre>\n\n<p>Edit: Joseph Silber's point about caching \"selectors\" (or rather any reference to <code>$(something)</code>) is also a good point but if anything referred to by such an expression is replaced, your cached \"selector\" will no longer be valid. Furthermore, it's not clear to me if <code>move(selector)</code> can be cached or not, so I just left it be.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T17:11:58.030",
"Id": "36051",
"Score": "0",
"body": "Thanks! It's interesting how you use the conversion of boolean to number. It's a good idea!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T16:58:16.567",
"Id": "23390",
"ParentId": "23386",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T16:15:58.043",
"Id": "23386",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"authentication",
"animation"
],
"Title": "Toggling animations"
}
|
23386
|
<p>I have been working on translating some code from C to C# but since I haven't been coding in C / C++ for many years now plus I do not want to resort to the unsafe keyword. I have made an attempt and would like some verification & optimisation suggestions.</p>
<p>Here is the code in C/C++.</p>
<pre><code>#ifdef __cplusplus /* C++ cannot assign void* from malloc to *data */
#define APPEND_DATA(/* T */ value, /* T** */ data, /* size_t* */ size) {\
if (!((*size) & ((*size) - 1))) {\
/*double alloc size if it's a power of two*/\
void** data_void = reinterpret_cast<void**>(data);\
*data_void = (*size) == 0 ? malloc(sizeof(**data))\
: realloc((*data), (*size) * 2 * sizeof(**data));\
}\
(*data)[(*size)] = (value);\
(*size)++;\
}
#else /* C gives problems with strict-aliasing rules for (void**) cast */
#define APPEND_DATA(/* T */ value, /* T** */ data, /* size_t* */ size) {\
if (!((*size) & ((*size) - 1))) {\
/*double alloc size if it's a power of two*/\
(*data) = (*size) == 0 ? malloc(sizeof(**data))\
: realloc((*data), (*size) * 2 * sizeof(**data));\
}\
(*data)[(*size)] = (value);\
(*size)++;\
}
#endif
</code></pre>
<p>Here is the code in C#:</p>
<pre><code>public static T[] AppendData<T>(T value, T[] data, ref uint size)
{
if ((size & (size - 1)) != 0)
{
/* Double alloc size if it's a power of two */
var tsize = size == 0 ? data.Length : size*2*data.Length;
var tdata = new T[tsize];
Array.Copy(data, tdata, data.Length);
tdata[size] = value;
data = tdata;
}
else
{
data[size] = value;
}
size++;
return data;
}
</code></pre>
<p>One more thing to note is that performance is paramount for this code as the overall algorithm it fits in to is quite slow.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T17:41:33.530",
"Id": "36053",
"Score": "0",
"body": "Welcome! Feel free to post the entire algorithm if you like — context can make a big difference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T17:46:14.240",
"Id": "36054",
"Score": "0",
"body": "A new/modified compression algorithm by Google. Here is the link to it - https://code.google.com/p/zopfli/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T17:48:47.543",
"Id": "36055",
"Score": "0",
"body": "My aim here is to refresh my C also to ensure that I am translating accurately. I am contending with ensuring the code works at the end and then I will optimise to ensure good performance and efficiency in c#."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T11:42:06.963",
"Id": "36094",
"Score": "0",
"body": "I started writing some notes but got blocked a little in because I really need some content. What is the function meant to do exactly? It looks like you are implementing the add function for a dynamic array but the if and tsize calculations look a bit off. Is size the size taken up in the array by the data or is it something you're passing that determines the size of the new array?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T12:47:50.783",
"Id": "36095",
"Score": "0",
"body": "If you are familiar with GitHub try cloning this https://code.google.com/p/zopfli and checkout the zopfli.c & the gzip_contianer.c files."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-10T06:11:10.573",
"Id": "36525",
"Score": "0",
"body": "zopfli.c was deleted but I can't find this function with the last version of it (https://code.google.com/p/zopfli/source/diff?spec=svn8c218eff39749e738c92bf34155099ad280c16f7&r=8c218eff39749e738c92bf34155099ad280c16f7&format=side&path=/zopfli.c) I can't see it in gzip_container.c either?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T06:41:07.380",
"Id": "39243",
"Score": "2",
"body": "When translating code between two languages with completely different goals, it would be a disservice to attempt to do a line-by-line literal translation. You should utilize features of the language that you are translating to as they were meant to be used. Don't restrict yourself to having the translated code behave exactly like the old code, do what makes sense in the target language. In this case, define a class to encapsulate the array and the used size then add methods to handle resizing. Better yet, don't even bother reinventing the wheel, use a `List`, the work is already done for you."
}
] |
[
{
"body": "<p>From a micro-optimization perspective I have found that C# and the JIT tend to like things from left to right (<a href=\"http://mediocresoft.com/Blog/simple-readable-csharp-micro-optimization-expression-operand-ordering\" rel=\"nofollow\">post</a>).\nEx: <code>(((size - 1) & size) != 0)</code> and <code>data.Length*size*2</code></p>\n\n<p>With a macro and readability (verification) perspective I would be curious to see the performance difference between this method and just using <code>List<T>.Add</code>.</p>\n\n<p>When it comes to performance you need to just measure it. On different machines if you can.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-22T22:18:13.553",
"Id": "24262",
"ParentId": "23392",
"Score": "1"
}
},
{
"body": "<p>Some notes, I may have some wrong because there isn't any context:</p>\n\n<ul>\n<li>In C# <code>uint</code> is generally avoided to prevent casting from <code>uint</code> to <code>int</code>, <a href=\"http://msdn.microsoft.com/en-us/library/bb494734.aspx\" rel=\"nofollow\">the array [] operator actually takes an <code>int</code> for example.</a> I know it feels more correct using <code>uint</code> but it just isn't better. Including <code>uint</code> in a public interface is also <a href=\"http://msdn.microsoft.com/en-us/library/bhc3fa7f.aspx\" rel=\"nofollow\">not CLS compliant</a>.</li>\n<li><p>It looks like you're implementing a dynamic array but isn't your <code>tsize</code> calculation incorrect? Shouldn't it be something more along the lines of this?</p>\n\n<pre><code>var tsize = size == 0 ? data.Length : size * 2 * data.Length;\n</code></pre>\n\n<p>In its current state it would always be doubling the array if there is an item present.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-23T03:38:46.387",
"Id": "24269",
"ParentId": "23392",
"Score": "0"
}
},
{
"body": "<h2>Wellcome in C# land!</h2>\n\n<p>You are trying to implement a dynamic array or something like that so why not to a List or another collection like Collection. These are dynamic sizeable no need to worry about size/space handling.</p>\n\n<p>In C# do not be an array-oriented coder feel free to use other powerfull collections.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T05:17:31.597",
"Id": "25324",
"ParentId": "23392",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T17:23:58.520",
"Id": "23392",
"Score": "3",
"Tags": [
"c#",
"c"
],
"Title": "Translate from C to C#"
}
|
23392
|
<p>As you can see below, I have a method which executes statements based on the first letter of a component firing an <code>ItemEvent</code>:</p>
<pre><code>public void itemStateChanged(ItemEvent ie) {
if(ie.getSource() == rRadioButton) {
currentScale = "r";
((DefaultEditor) rSpinner.getEditor()).getTextField().requestFocus();
}
else if(ie.getSource() == gRadioButton) {
currentScale = "g";
((DefaultEditor) gSpinner.getEditor()).getTextField().requestFocus();
}
else if(ie.getSource() == bRadioButton) {
currentScale = "b";
((DefaultEditor) bSpinner.getEditor()).getTextField().requestFocus();
}
//...
}
</code></pre>
<p>Is it possible to easily shorten the method and make it more automatic?</p>
<p>If the argument was an <code>ActionEvent</code> I could use <code>getActionCommand</code> to assign the value for <code>currentScale</code> but the same number of lines of code would be needed first to <code>setActionCommand</code> for every component.</p>
<p>I could also use <code>setName</code> and <code>getName</code> for components but this will result it the same issue as described above.</p>
<p>Also it would be good to be able to automatically point to a specific Spinner based on a specific RadioButton as you can see in the attached source code.</p>
<p>Maybe there is a possibility to use reflection for this but I don't know if this could work.</p>
|
[] |
[
{
"body": "<p>You repeat the line</p>\n\n<pre>((DefaultEditor) bSpinner.getEditor()).getTextField().requestFocus();</pre>\n\n<p>in every branch of the if/then. So you could easily shorten it by having the if/then look up of the currentScale be one thing and then have that line after it.</p>\n\n<p>Speaking of lookup, I'd probably have a hash of the currentScale values indexed by the type of the argument. In ActionScript, I'd use a Dictionary for this--I'm not sure what the Java equvalent is.</p>\n\n<p>This part <code>((DefaultEditor) bSpinner.getEditor())</code> looks like a \"code smell\" to me. This suggests that your instance is <a href=\"http://misko.hevery.com/2008/11/21/clean-code-talks-global-state-and-singletons/\" rel=\"nofollow\">reaching out</a> into things it has no business knowing about. At the very least, it's a violation of the <a href=\"http://www.ccs.neu.edu/home/lieber/LoD.html\" rel=\"nofollow\">law of Demeter</a>. Consider providing this through dependency injection as a member variable or providing it as an argument to the method.</p>\n\n<p>It is also possible that the method you show above might be better integrated into the default editor, the spinner, the spinner's editor, or the text field and <em>that</em> object might be in a position to set the currentState of whatever Class you're quoting from above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T22:46:38.123",
"Id": "36072",
"Score": "0",
"body": "I'm afraid you didn't notice the difference in calling rSpinner, gSpinner, bSpinner - it's not repeated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T01:17:05.900",
"Id": "36077",
"Score": "0",
"body": "Then the part where you look up what that should be could be extracted to a separate part (which, looking up, is what David suggests). This whole thing has a \"bad code smell\" aura about it, but since you don't provide much code it's hard to tell you how to fix it. It seems to me that you might just need a separate Controller or something for each one of these, then call the appropriate controller when you need it. It's possible that you could look up the controller in a hash."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T20:37:57.703",
"Id": "23400",
"ParentId": "23398",
"Score": "1"
}
},
{
"body": "<p>Without seeing the greater context in which this code appears such as how the components are constructed, and not having kept up with Spring since 1999, I can only address the immediate code. The above could be converted to use two maps: one for the text fields and another for the <code>currentScale</code> strings.</p>\n\n<p>In the code that builds the components, create the two maps and store them in instance fields of the same class.</p>\n\n<pre><code>private final Map<Object, JTextField> textFieldsByRadioButton = new IdentityHashMap<>();\nprivate final Map<Object, String> scalesByRadioButton = new IdentityHashMap<>();\n\nprivate void buildComponents() {\n ...\n addRadioButtonSpinnerMapping(rRadioButton, rSpinner, \"r\");\n addRadioButtonSpinnerMapping(gRadioButton, gSpinner, \"g\");\n addRadioButtonSpinnerMapping(bRadioButton, bSpinner, \"b\");\n}\n\nprivate void addRadioButtonSpinnerMapping(JRadioButton button, JSpinner spinner, String scale) {\n textFieldsByRadioButton.put(button, ((DefaultEditor) spinner.getEditor()).getTextField());\n scalesByRadioButton.put(button, scale);\n}\n\npublic void itemStateChanged(ItemEvent ie) {\n Object source = ie.getSource();\n JTextField textField = textFieldsByRadioButton.get(source);\n if (textField != null) {\n currentScale = scalesByRadioButton.get(source);\n textField.requestFocus();\n }\n ...\n}\n</code></pre>\n\n<p>While it requires slightly more code, it only takes one line to add another spinner.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T22:51:15.510",
"Id": "23406",
"ParentId": "23398",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T20:26:37.263",
"Id": "23398",
"Score": "3",
"Tags": [
"java"
],
"Title": "Shortening method based on an argument name"
}
|
23398
|
<p>I have implemented changes from a question I asked on this widget here:</p>
<p><a href="https://codereview.stackexchange.com/questions/21131/android-widget-code-review">Android widget code</a></p>
<p>I've added and changed a few things, so I would love some more coding advice!</p>
<pre><code>public class SacWidgetService extends Service {
private static final String TAG = "SAC WIDGET SERVICE";
AQuery aq;
private String roseXML = "sac-full.xml";
private String roseUrl;
private AppWidgetManager appWidgetManager;
private int[] allWidgetIds;
private File ext;
private File file;
@Override
public void onStart(Intent intent, int startId) {
aq = new AQuery(this);
// Create some random data
appWidgetManager = AppWidgetManager.getInstance(this
.getApplicationContext());
allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
// get external directory and put the file in there.
ext = Environment.getExternalStorageDirectory();
file = new File(ext, "avalancheconditionsreport/sac/dangerrose.png");
// parse xml and get the rose
xml_ajax();
stopSelf();
super.onStart(intent, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void xml_ajax() {
aq.ajax(roseXML, XmlDom.class, this, "sacCb");
}
public void sacCb(String url, XmlDom xml, AjaxStatus status) {
XmlDom r = xml.tag("reportrose");
roseUrl = r.tag("img").attr("src").trim();
File ext = Environment.getExternalStorageDirectory();
File target = new File(ext,
"avalancheconditionsreport/sac/dangerrose.png");
aq.download(roseUrl, target, new AjaxCallback<File>() {
public void callback(String url, File file, AjaxStatus status) {
String s = status.getMessage();
int i = status.getCode();
String e = s + " | Status Code: " + i;
if (file != null) {
getInfo();
} else {
Log.e("ACR SAC Widget Error", e);
}
}
});
}
private Bitmap getRose() {
Bitmap bitmap = null;
try {
FileInputStream input = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(input);
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, e.getMessage());
}
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage());
}
// Toast.makeText(this, "Sierra Avalanche Center Danger Rose",
// Toast.LENGTH_LONG).show();
return bitmap;
}
private void getInfo() {
// TODO Auto-generated method stub
Date dlm = new Date(file.lastModified());
String lm = dlm.toLocaleString();
for (int appWidgetId : allWidgetIds) {
RemoteViews views = new RemoteViews(this.getApplicationContext()
.getPackageName(), R.layout.sac_widget_layout);
Intent clickIntent = new Intent(this.getApplicationContext(),
SACActivity.class);
PendingIntent clickapp = PendingIntent.getActivity(
this.getApplicationContext(), 0, clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.ivdangerrose, clickapp);
views.setTextViewText(R.id.tvupdated, "Updated: " + lm);
views.setImageViewBitmap(R.id.ivdangerrose, getRose());
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><blockquote>\n<pre><code>try {\n FileInputStream input = new FileInputStream(file);\n bitmap = BitmapFactory.decodeStream(input);\n try {\n input.close();\n } catch (IOException e) {\n // TODO Auto-generated catch block\n Log.e(TAG, e.getMessage());\n }\n} catch (FileNotFoundException e) {\n Log.e(TAG, e.getMessage());\n}\n</code></pre>\n</blockquote>\n\n<p>If <code>decodeStream</code> throws an exception the stream won't be closed. A proper solution is the following:</p>\n\n<pre><code>try {\n FileInputStream input = new FileInputStream(file);\n try {\n bitmap = BitmapFactory.decodeStream(input);\n } finally {\n input.close();\n }\n} catch (FileNotFoundException e) {\n Log.e(TAG, e.getMessage());\n} catch (IOException e) {\n Log.e(TAG, e.getMessage());\n}\n</code></pre>\n\n<p>Or this:</p>\n\n<pre><code>try {\n FileInputStream input = new FileInputStream(file);\n try {\n bitmap = BitmapFactory.decodeStream(input);\n } finally {\n input.close();\n }\n} catch (IOException e) {\n Log.e(TAG, e.getMessage());\n}\n</code></pre>\n\n<p>(Since <code>FileNotFoundException</code> is a subclass of <code>IOException</code>).</p></li>\n<li><blockquote>\n<pre><code>AQuery aq;\n</code></pre>\n</blockquote>\n\n<p>I guess this field could be <code>private</code>. (<a href=\"https://stackoverflow.com/questions/5484845/should-i-always-use-the-private-access-modifier-for-class-fields\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.)</p></li>\n<li><blockquote>\n<pre><code>private String roseUrl;\n...\nprivate File ext;\n</code></pre>\n</blockquote>\n\n<p>These field is used only in one method (<code>onStart</code> and <code>sacCb</code>). They could be local variables instead. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><blockquote>\n<pre><code>public void xml_ajax() {\n</code></pre>\n</blockquote>\n\n<p>This method name does not follow the usual <code>camelCase</code> conventions and it should be a verb. From <a href=\"http://www.oracle.com/technetwork/java/codeconventions-135099.html#367\" rel=\"nofollow\">Code Conventions for the Java Programming Language</a>:</p>\n\n<blockquote>\n <p>Methods should be verbs, in mixed case with the first letter\n lowercase, with the first letter of each internal word capitalized.</p>\n</blockquote></li>\n<li><p>I'd use longer and more descriptive variable names (which explains their purpose) for better readability than this ones:</p>\n\n<blockquote>\n<pre><code>XmlDom r = xml.tag(\"reportrose\");\n...\nString s = status.getMessage();\nint i = status.getCode();\nString e = s + \" | Status Code: \" + i;\n...\nString lm = dlm.toLocaleString();\n</code></pre>\n</blockquote>\n\n<p>Longer names would make the code more readable since readers don't have to decode the abbreviations every time and when they write/maintain the code don't have to guess which abbreviation the author uses.</p></li>\n<li><blockquote>\n<pre><code>private Bitmap getRose() {\n Bitmap bitmap = null;\n try {\n FileInputStream input = new FileInputStream(file);\n try {\n bitmap = BitmapFactory.decodeStream(input);\n } finally {\n input.close();\n }\n } catch (IOException e) {\n Log.e(TAG, e.getMessage());\n }\n return bitmap;\n}\n</code></pre>\n</blockquote>\n\n<p>You can get rid of the bitmap variable here if you return immediately:</p>\n\n<pre><code>private Bitmap getRose() {\n try {\n FileInputStream input = new FileInputStream(file);\n try {\n return BitmapFactory.decodeStream(input);\n } finally {\n input.close();\n }\n } catch (IOException e) {\n Log.e(TAG, e.getMessage());\n }\n return null;\n}\n</code></pre>\n\n<p>See <em>Guideline 1-2: Release resources in all cases</em> in <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\" rel=\"nofollow\">Secure Coding Guidelines for the Java Programming Language</a></p></li>\n<li><blockquote>\n<pre><code>String lm = dlm.toLocaleString();\n</code></pre>\n</blockquote>\n\n<p>This method is deprecated, you should use something else.</p></li>\n<li><blockquote>\n<pre><code>// TODO Auto-generated catch block\n</code></pre>\n</blockquote>\n\n<p>Comments like this doesn't seem like professional work. Solve the issues and remove the comments.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T20:24:36.030",
"Id": "44099",
"ParentId": "23401",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "44099",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T21:31:32.063",
"Id": "23401",
"Score": "2",
"Tags": [
"java",
"android"
],
"Title": "Homescreen Widget Service"
}
|
23401
|
<p>I wrote a productivity app for Android. It lets you switch system settings, like Bluetooth, wife, screen brightness, volumes, ringtones, mobile data, airplane mode, etc. Unfortunately I have discovered that device manufacturers modify the OS in every possible way, disabling functionality, requesting additional permissions, or making it available only to system apps. I.e. switching WiFi on stock Android requires <code>android.permission.CHANGE_WIFI_STATE</code> permission, but most Samsung devices also require <code>android.permission.ACCESS_WIFI_STATE</code>. Switching mobile data is simply disabled on many devices.</p>
<p>This makes it impossible to predict how my code will work on a particular device, or on a future version of OS. But at the same time, I definitely don't want my app to crash, because there's really nothing worse that an app can do. So in order to be safe, I've been using what is sometimes called a "Pokemon exception handling" (Gotta catch 'em all!):</p>
<pre><code>try {
//Do stuff
} catch (Exception e) {
//Log an error, send crash report, etc.
}
//Keep calm and carry on
</code></pre>
<p>I know that this is generally considered a bad practice, but I just can't find a better way to handle this situation. I simply can't predict all possibilities of what could go wrong. Most of my methods for executing actions look something like this:</p>
<pre><code>private boolean switchWiFi(boolean state) {
try {
WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);
wm.setWifiEnabled(state);
return true; //Executed successfully
}
catch (Exception e){
//Give user a notification about an error, rather than crash
showErrorNotification("Couldn't switch WiFi.");
if(BuildConfig.DEBUG){Log.getStackTraceString(e);}//Log exception stack trace
return false; //Execution failed
}
}
</code></pre>
<p>Is there a better way to handle exceptions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T23:11:12.273",
"Id": "36073",
"Score": "4",
"body": "I would catch as many specific exceptions as possible and add the pokemon exception at the end to account for unknown problems. This should give you general error handling while also providing specific information for the most recurring cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-22T15:04:23.290",
"Id": "103236",
"Score": "0",
"body": "But why catching specific exceptions if you don't have specific error handlers? I often see in code a try with multiple catch that does the exact same thing. For me that does not make any sense."
}
] |
[
{
"body": "<p>When the called API throws unknown exceptions I don't think that there is other way than catching all exceptions (sometimes <code>Throwable</code>s too). +1 <em>Jeroen Vannevel</em>'s comment too.</p>\n\n<p>Anyway, a common interface might be able to improve the code a little bit:</p>\n\n<pre><code>public interface Command {\n\n run() throws Exception;\n\n String getName();\n\n}\n</code></pre>\n\n<p>Then, you can have implementations, like <code>WifiSwitcher</code>, and call them one after the other:</p>\n\n<pre><code>final List<String> errors = new ArrayList<String>();\nfor (final Command command: commands) {\n try {\n command.run();\n } catch (final Exception e) {\n errors.add(\"Could not perform command: \" + command.getName());\n if (BuildConfig.DEBUG) {\n Log.getStackTraceString(e);\n }\n }\n}\n\nif (errors.isEmpty()) {\n return true;\n}\nshowErrorNotification(errors);\nreturn false;\n</code></pre>\n\n<p>(I haven't tested nor compiled the code above.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T21:53:51.040",
"Id": "36180",
"Score": "1",
"body": "Interesting point, I'll give it a try."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T11:22:49.613",
"Id": "23421",
"ParentId": "23402",
"Score": "2"
}
},
{
"body": "<p>Try sending your caught exceptions to Google App Analytics as an Event (Then it doesn't show up as an App exception).</p>\n\n<p>Here's how to do it easily in Android:</p>\n\n<p><a href=\"http://tekkies.co.uk/report-caught-exceptions-as-google-analytics-events/\" rel=\"nofollow noreferrer\">http://tekkies.co.uk/report-caught-exceptions-as-google-analytics-events/</a></p>\n\n<p><img src=\"https://i.stack.imgur.com/gYPRA.png\" alt=\"enter image description here\"></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T09:42:33.750",
"Id": "38889",
"ParentId": "23402",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "23421",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T21:54:56.567",
"Id": "23402",
"Score": "12",
"Tags": [
"java",
"android",
"error-handling"
],
"Title": "Productivity app for Android"
}
|
23402
|
<p>A <a href="http://en.wikipedia.org/wiki/Node_%28computer_science%29" rel="nofollow">node</a> is a record consisting of one or more fields that are links to other nodes, and a data field. The link and data fields are often implemented by pointers or references although it is also quite common for the data to be embedded directly in the node. </p>
<p>Nodes are used to build linked data structures such as linked lists, trees, and graphs. Large and complex data structures can be formed from groups of interlinked nodes. <a href="http://en.wikipedia.org/wiki/Node_%28computer_science%29" rel="nofollow">Nodes</a> are conceptually similar to vertices, which are elements of a graph. Software is said to have a node graph architecture when its organization consists of interlinked nodes.</p>
<p><a href="http://en.wikipedia.org/wiki/Node_%28computer_science%29" rel="nofollow">http://en.wikipedia.org/wiki/Node_(computer_science)</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T22:43:29.047",
"Id": "23404",
"Score": "0",
"Tags": null,
"Title": null
}
|
23404
|
Nodes are the basic units used to build data structures such as linked lists and trees.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T22:43:29.047",
"Id": "23405",
"Score": "0",
"Tags": null,
"Title": null
}
|
23405
|
<p>The <em>batch</em> tag is used for Windows batch file questions.</p>
<p>Batch files are scripts executed by the Windows command processor (cmd.exe) or, in older times, by the DOS shell (command.com). While many people mistakenly believe that everything that has light gray text on a black background is DOS, pretty much no batch question ever asked here was DOS-related.</p>
<p>Since the batch language evolved it gathered a whole host of intricacies and difficulties.</p>
<p><strong>Resources</strong></p>
<ul>
<li><a href="http://ss64.com/nt/" rel="nofollow noreferrer">Comprehensive reference for the Windows command-line commands</a>. Includes flow control, like <code>FOR /F</code>.</li>
<li><a href="http://www.robvanderwoude.com/batchfiles.php" rel="nofollow noreferrer">Learn batch scripting</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-03-03T22:55:10.727",
"Id": "23407",
"Score": "0",
"Tags": null,
"Title": null
}
|
23407
|
The batch tag is used for Windows batch file questions.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-03-03T22:55:10.727",
"Id": "23408",
"Score": "0",
"Tags": null,
"Title": null
}
|
23408
|
<p>I am working on a project in which I have two tables in a different database with different schemas. So that means I have two different connection parameters for those two tables to connect using JDBC-</p>
<p>Let's suppose below is the config.property file.</p>
<pre><code>NUMBER_OF_THREADS: 10
TOTAL_RUNNING_TIME: 2
SLEEP_TIME: 200
RANGE_VALID_USER_ID: 1-1000
RANGE_NON_EXISTENT_USER_ID: 10000-50000
PERCENTAGE_VALID_USER_ID: 95
FLAG_VALIDATE_DATA: false
FLAG_STOP_PROGRAM: false
TABLES: table1 table2
#For Table1
table1.url: jdbc:mysql://localhost:3306/garden
table1.user: gardener
table1.password: shavel
table1.driver: jdbc-driver
table1.percentage: 80
table1.columns: COL1,COL2,COl3,Col4,COL5
#For Table2
table2.url: jdbc:mysql://otherhost:3306/forest
table2.user: forester
table2.password: axe
table2.driver: jdbc-driver
table2.percentage: 20
table1.columns: COL10,COL11,COl12,Col13,COL14
</code></pre>
<p>Now from the above property files it means-</p>
<ol>
<li>Number of Threads is 10</li>
<li><code>TOTAL_RUNNING_TIME</code> means each thread will run for <code>2 minutes</code> </li>
<li>Each thread will sleep for 200 milliseconds before making any other request</li>
<li>Range of valid User Id from which each thread will pick the id's depending on the percentage. Like 95% of each thread will pick Valid Id's and remaining 5% it will pick Non Existent User Id.</li>
<li>A boolean flag to validate the data.</li>
<li>A boolean flag to stop the program in case of any exceptions.</li>
</ol>
<p>Below method will read the above <code>config.properties</code> file and make a <code>TableConnectionInfo</code> object for each tables.</p>
<pre><code>private static void readPropertyFile() throws IOException {
prop.load(LnPRead.class.getClassLoader().getResourceAsStream("config.properties"));
threads = Integer.parseInt(prop.getProperty("NUMBER_OF_THREADS").trim());
durationOfRun = Long.parseLong(prop.getProperty("TOTAL_RUNNING_TIME").trim());
sleepTime = Long.parseLong(prop.getProperty("SLEEP_TIME").trim());
flagValidateData = Boolean.parseBoolean(prop.getProperty("FLAG_VALIDATE_DATA").trim());
flagTerminate = Boolean.parseBoolean(prop.getProperty("FLAG_STOP_PROGRAM").trim());
startValidRange = Integer.parseInt(prop.getProperty("RANGE_VALID_USER_ID").trim().split("-")[0]);
endValidRange = Integer.parseInt(prop.getProperty("RANGE_VALID_USER_ID").trim().split("-")[1]);
startNonValidRange = Integer.parseInt(prop.getProperty("RANGE_NON_EXISTENT_USER_ID").trim().split("-")[0]);
endNonValidRange = Integer.parseInt(prop.getProperty("RANGE_NON_EXISTENT_USER_ID").trim().split("-")[1]);
percentageValidId = Double.parseDouble(prop.getProperty("PERCENTAGE_VALID_USER_ID").trim());
tableNames = Arrays.asList(prop.getProperty("TABLES").trim().split(","));
for (String arg : tableNames) {
TableConnectionInfo ci = new TableConnectionInfo();
ArrayList<String> columns = new ArrayList<String>();
String url = prop.getProperty(arg + ".url").trim();
String user = prop.getProperty(arg + ".user").trim();
String password = prop.getProperty(arg + ".password").trim();
String driver = prop.getProperty(arg + ".driver").trim();
String table = prop.getProperty(arg + ".table").trim();
double percentage = Double.parseDouble(prop.getProperty(arg + ".percentage").trim());
columns = new ArrayList<String>(Arrays.asList(prop.getProperty(arg + ".columns").split(",")));
ci.setUrl(url);
ci.setUser(user);
ci.setPassword(password);
ci.setDriver(driver);
ci.setTableName(table);
ci.setPercentage(percentage);
ci.setColumns(columns);
tableList.put(arg, ci);
}
}
</code></pre>
<p>Below is the <code>TableConnectionInfo</code> class that will hold all the table connection info for a particular table. </p>
<pre><code>public class TableConnectionInfo {
public String url;
public String user;
public String password;
public String driver;
public double percentage;
public String tableName;
public ArrayList<String> columns;
public ArrayList<String> getColumns() {
return columns;
}
public void setColumns(ArrayList<String> columns) {
this.columns = columns;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
}
</code></pre>
<p>Now I am creating <code>ExecutorService</code> for specified number of threads and passing this <code>tableList</code> object (that I created by reading the <code>config.property file</code>) to constructor of <code>Task</code> class -</p>
<pre><code>// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(10);
long startTime = System.currentTimeMillis();
long endTime = startTime + (durationOfRun * 60 * 1000);
for (int i = 0; i < threads; i++) {
service.submit(new Task(endTime, tableList));
}
</code></pre>
<p>Below is my <code>Task</code> class that implements <code>Runnable interface</code> in which each thread will make two connections for each table in the starting before doing anything meaningful.</p>
<pre><code>class Task implements Runnable {
private static final Logger LOG = Logger.getLogger(Task.class.getName());
private static Random random = new SecureRandom();
private Connection[] dbConnection = null;
private PreparedStatement preparedStatement = null;
private ResultSet rs = null;
private HashMap<String, Connection> tableStatement = new HashMap<String, Connection>();
private final long endTime;
private final LinkedHashMap<String, TableConnectionInfo> tableLists;
public static ConcurrentHashMap<Long, AtomicLong> selectHistogram = new ConcurrentHashMap<Long, AtomicLong>();
public static ConcurrentHashMap<Long, AtomicLong> connectionHistogram = new ConcurrentHashMap<Long, AtomicLong>();
public static ConcurrentHashMap<String, AtomicInteger> exceptionMap = new ConcurrentHashMap<String, AtomicInteger>();
/**
* Constructor to pass the values
*
* @param durationOfRun
* @param tableList
*/
public Task(long endTime, LinkedHashMap<String, TableConnectionInfo> tableList) {
this.endTime = endTime;
this.tableLists = tableList;
}
@Override
public void run() {
try {
int j = 0;
dbConnection = new Connection[tableLists.size()];
//loop around the map values and make the connection list
for (TableConnectionInfo ci : tableLists.values()) {
dbConnection[j] = getDBConnection(ci.getUrl(), ci.getUser(), ci.getPassword(), ci.getDriver());
tableStatement.put(ci.getTableName(), dbConnection[j]);
j++;
}
while (System.currentTimeMillis() <= endTime) {
double randomNumber = random.nextDouble() * 100.0;
TableConnectionInfo table = selectRandomTable(randomNumber);
final int id = generateRandomId(random);
final String columnsList = getColumns(table.getColumns());
final String selectSql = "SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, " + columnsList + " from "
+ table.getTableName() + " where id = ?";
preparedStatement = tableStatement.get(table.getTableName()).prepareCall(selectSql);
preparedStatement.setString(1, String.valueOf(id));
long start = System.nanoTime();
rs = preparedStatement.executeQuery();
long end = System.nanoTime() - start;
final AtomicLong before = selectHistogram.putIfAbsent(end / 1000000L, new AtomicLong(1L));
if (before != null) {
before.incrementAndGet();
}
List<String> colData = new ArrayList<String>(columnsList.split(",").length);
boolean foundData = false;
if (rs.next()) {
if (id >= LnPRead.startValidRange && id <= LnPRead.endValidRange) {
foundData = true;
for (String column : columnsList.split(",")) {
colData.add(rs.getString(column.trim()));
}
} else {
handleException(ReadConstants.NON_VALID_DATA, LnPRead.flagTerminate);
}
}
if (LnPRead.flagValidateData && foundData) {
for (String str : colData) {
if (!isJSONValid(str, id)) {
LOG.error("Invalid JSON String " + str + "with id" + id);
handleException(ReadConstants.INVALID_JSON, LnPRead.flagTerminate);
}
}
}
if (LnPRead.sleepTime > 0L) {
Thread.sleep(LnPRead.sleepTime);
}
}
} catch (SQLException e) {
handleException(e.getCause() != null ? e.getCause().toString() : e.toString(), LnPRead.flagTerminate);
} catch (Exception e) {
handleException(e.getCause() != null ? e.getCause().toString() : e.toString(), LnPRead.flagTerminate);
} finally {
closeConnection(preparedStatement, dbConnection);
}
}
/**
* A simple method to decide whether a String is a valid JSON String or not.
*
* @param str
* @param id
* @return
*/
public boolean isJSONValid(final String str, final int id) {
boolean valid = true;
try {
final JSONObject obj = new JSONObject(str);
final JSONArray data = obj.getJSONArray("lv");
final int n = data.length();
for (int i = 0; i < n; ++i) {
final JSONObject lv = data.getJSONObject(i);
JSONObject v = lv.getJSONObject("v");
if (v.getInt("userId") != id) {
valid = false;
break;
}
}
} catch (JSONException ex) {
valid = false;
}
return valid;
}
/**
* A simple method to get the column names in the order in which it was
* inserted
*
* @param columns
* @return
*/
private String getColumns(final List<String> columns) {
List<String> copy = new ArrayList<String>(columns);
Collections.shuffle(copy);
int rNumber = random.nextInt(columns.size()) + 1;
List<String> subList = copy.subList(0, rNumber);
Collections.sort(subList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return columns.indexOf(o1) < columns.indexOf(o2) ? -1 : 1;
}
});
return StringUtils.join(subList, ",");
}
/**
* A simple method to choose random table basis on the percentage
*
* @param randomNumber
* @return
*/
private TableConnectionInfo selectRandomTable(double randomNumber) {
double limit = 0;
for (TableConnectionInfo ci : tableLists.values()) {
limit += ci.getPercentage();
if (randomNumber < limit) {
return ci;
}
}
throw new IllegalStateException();
}
/**
* A simple method to decide which id's I need to pick either valid id or
* non valid id
*
* @param r
* @return
*/
private int generateRandomId(Random r) {
int randomID;
if (r.nextFloat() < LnPRead.percentageValidId / 100) {
randomID = r.nextInt(LnPRead.endValidRange - LnPRead.startValidRange + 1)
+ LnPRead.startValidRange;
} else {
randomID = r.nextInt(LnPRead.endNonValidRange - LnPRead.startNonValidRange + 1)
+ LnPRead.startNonValidRange;
}
return randomID;
}
/**
* A simple method to close the connection
*
* @param callableStatement
* @param dbConnection
*/
private void closeConnection(PreparedStatement preparedStatement, Connection[] dbConnection) {
if (preparedStatement != null) {
try {
preparedStatement.close();
preparedStatement = null;
} catch (SQLException e) {
LOG.error("Threw a SQLException in finally block of prepared statement " + getClass().getSimpleName(), e);
}
}
for (Connection con : dbConnection) {
if (con != null) {
try {
con.close();
con = null;
} catch (SQLException e) {
LOG.error("Threw a SQLException in finally block of dbConnection " + getClass().getSimpleName(), e);
}
}
}
}
/**
* Attempts to establish a connection to the given database URL
*
* @return the db connection
*/
private Connection getDBConnection(String url, String username, String password, String driver) {
Connection dbConnection = null;
try {
Class.forName(driver);
long start = System.nanoTime();
dbConnection = DriverManager.getConnection(url, username, password);
long end = System.nanoTime() - start;
final AtomicLong before = connectionHistogram.putIfAbsent(end / 1000000, new AtomicLong(1L));
if (before != null) {
before.incrementAndGet();
}
} catch (ClassNotFoundException e) {
handleException(e.getCause() != null ? e.getCause().toString() : e.toString(), LnPRead.flagTerminate);
} catch (SQLException e) {
handleException(e.getCause() != null ? e.getCause().toString() : e.toString(), LnPRead.flagTerminate);
}
return dbConnection;
}
/**
* A simple method that will add the count of exceptions and name of
* exception to a map
*
* @param cause
* @param flagTerminate
*/
private static void handleException(String cause, boolean flagTerminate) {
LOG.error(cause);
AtomicInteger count = exceptionMap.get(cause);
if (count == null) {
count = new AtomicInteger();
AtomicInteger curCount = exceptionMap.putIfAbsent(cause, count);
if (curCount != null) {
count = curCount;
}
}
count.incrementAndGet();
if (flagTerminate) {
System.exit(1);
}
}
}
</code></pre>
<p>In my first try block in the <code>run method</code>, I am making <code>dbConnection</code> array for storing two different database connections. And then I have a <code>tableStatement</code> as HashMap in which I am storing corresponding table name with it's <code>dbConnection</code>. For example <code>Table1</code> will have <code>Table1</code> connection in the <code>tableStatement</code> HashMap.</p>
<p>And then after that I am applying this logic in the while loop so that each thread should run for 2 minutes-</p>
<pre><code>/* Generate random number and check to see whether that random number
* falls between 1 and 80, if yes, then choose table1
* and then use table1 connection and statement that I made above and do a SELECT query on that table.
* If that random numbers falls between 81 and 100 then choose table2
* and then use table2 connection and statement and do a SELECT query on that table
*/
</code></pre>
<ol>
<li>Generating Random number between 1 and 100.</li>
<li>If that random number is less than table1.getPercentage() then I am choosing <code>table1</code> and then use <code>table1 connection</code> object to make a SELECT sql call to that database. Else choose <code>table2</code> and then use <code>table2 connection object</code> to make a SELECT SQL call to that database.</li>
<li>After executing SELECT SQL, if result set contains any data, then check to see whether the id is between Valid Range. If it is between the valid range then store it in <code>colData</code> list of String but if it not in the valid range, log an exception.</li>
<li>After that if the flag to validate the data is true, then validate the JSON String.</li>
</ol>
<p><strong>Problem Statement:</strong></p>
<p>I am trying to see whether is there any potential <code>thread safety issues</code> or <code>race conditions</code> possible here in my run method? And is there anything that I can improve in my code?</p>
<p>I know, it's a lot of code that somebody has to go through. I am in the starting phase of multithreading so that is the reason I am having problem initially.</p>
|
[] |
[
{
"body": "<ol>\n<li><p>It looks thread-safe for me, I've not found any concurrency-related issue except that you might want to to use a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadLocalRandom.html\" rel=\"nofollow noreferrer\"><code>ThreadLocalRandom</code></a> or use separate <code>SecureRandom</code> instances with a <code>ThreadLocal</code> for performance reasons. See also. <a href=\"https://stackoverflow.com/a/1461624/843804\">Is SecureRandom thread safe?</a></p></li>\n<li><blockquote>\n<pre><code>boolean valid = true;\n</code></pre>\n</blockquote>\n\n<p>Instead of this local variable you could return immediately if you know the result:</p>\n\n<pre><code>public boolean isJSONValid(final String str, final int id) {\n try {\n final JSONObject obj = new JSONObject(str);\n final JSONArray data = obj.getJSONArray(\"lv\");\n final int n = data.length();\n\n for (int i = 0; i < n; ++i) {\n final JSONObject lv = data.getJSONObject(i);\n JSONObject v = lv.getJSONObject(\"v\");\n if (v.getInt(\"userId\") != id) {\n return false;\n }\n }\n } catch (JSONException ex) {\n return false;\n }\n return true;\n}\n</code></pre></li>\n<li><p>The following fields could be local variables in <code>run</code>:</p>\n\n<blockquote>\n<pre><code>private Connection[] dbConnection = null;\nprivate PreparedStatement preparedStatement = null;\nprivate ResultSet rs = null;\nprivate HashMap<String, Connection> tableStatement = new HashMap<String, Connection>();\n</code></pre>\n</blockquote>\n\n<p><em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em></p></li>\n<li><p>The <code>null</code> assignment is unnecessary here (in both cases):</p>\n\n<blockquote>\n<pre><code>if (preparedStatement != null) {\n try {\n preparedStatement.close();\n preparedStatement = null;\n } catch (SQLException e) {\n LOG.error(\"Threw a SQLException in finally block of prepared statement \" + getClass().getSimpleName(),\n e);\n }\n}\n\nfor (Connection con: dbConnection) {\n if (con != null) {\n try {\n con.close();\n con = null;\n } catch (SQLException e) {\n LOG.error(\"Threw a SQLException in finally block of dbConnection \" + getClass().getSimpleName(), e);\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>It only nulls a local variable/parameter which will be destroyed anyway at the end of the block/method. I guess you wanted to null the field, for that you need a <code>this.</code> prefix but as above, the fields could be local variables in <code>run</code>, so it's unnecessary.</p></li>\n<li><p>A <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clause could make the second loop flatten</a>:</p>\n\n<pre><code>for (Connection con: dbConnection) {\n if (con == null) {\n continue;\n }\n try {\n con.close();\n } catch (SQLException e) {\n LOG.error(\"Threw a SQLException in finally block of dbConnection \" + getClass().getSimpleName(), e);\n }\n}\n</code></pre></li>\n<li><blockquote>\n<pre><code>LOG.error(\"Threw a SQLException in finally block of prepared statement \" \n + getClass().getSimpleName(), e);\n</code></pre>\n</blockquote>\n\n<p>If you are using Logback or Log4j the <code>getClass().getSimpleName()</code> is unnecessary, you can set in the <code>log4j.xml</code> or <code>logback.xml</code> to log the class name for every log statement.</p></li>\n<li><p>Instead of <code>System.nanoTime()</code>, you could use a stopwatch class, like <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Stopwatch.html\" rel=\"nofollow noreferrer\">Guava <code>Stopwatch</code></a> or <a href=\"https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/StopWatch.html\" rel=\"nofollow noreferrer\">Apache Commons <code>StopWatch</code></a>).</p></li>\n<li><p>You could extract out the increment part of this method for higher abstraction level:</p>\n\n<blockquote>\n<pre><code>private static void handleException(String cause, boolean flagTerminate) {\n LOG.error(cause);\n\n AtomicInteger count = exceptionMap.get(cause);\n if (count == null) {\n count = new AtomicInteger();\n AtomicInteger curCount = exceptionMap.putIfAbsent(cause, count);\n if (curCount != null) {\n count = curCount;\n }\n }\n count.incrementAndGet();\n\n if (flagTerminate) {\n System.exit(1);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>It's easier to read, it's easier to get an overview what the method does (without the details) and you can still check them if you are interested in. Furthermore, you need to read and understand less code (not the whole original method) if you want to modify just a small part of it.</p>\n\n<pre><code>private static void handleException(String cause, boolean flagTerminate) {\n LOG.error(cause);\n incrementExceptionCount(cause);\n if (flagTerminate) {\n System.exit(1);\n }\n}\n\nprivate static void incrementExceptionCount(final String cause) {\n ...\n}\n</code></pre></li>\n<li><p>I guess you could use here the same structure with <code>AtomicLong</code>s:</p>\n\n<pre><code>private static void incrementExceptionCount(final String cause) {\n AtomicInteger previousValue = exceptionMap.putIfAbsent(cause, new AtomicInteger());\n if (previousValue != null) {\n previousValue.incrementAndGet();\n }\n}\n</code></pre>\n\n<p>You could also extract a similar method for <code>AtomicLong</code>s, since currently it's duplicated in the code.</p></li>\n<li><p>Anyway, instead of the <code>ConcurrentHashMap<Long, AtomicLong></code> structures I'd use <a href=\"http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/util/concurrent/AtomicLongMap.html\" rel=\"nofollow noreferrer\">Guava's <code>AtomicLongMap</code></a>. It was designed for these situations.</p>\n\n<p>(<em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><p>The logic in the method parameter is duplicated here.</p>\n\n<blockquote>\n<pre><code>} catch (ClassNotFoundException e) {\n handleException(e.getCause() != null ? e.getCause().toString() : e.toString(), LnPRead.flagTerminate);\n} catch (SQLException e) {\n handleException(e.getCause() != null ? e.getCause().toString() : e.toString(), LnPRead.flagTerminate);\n}\n</code></pre>\n</blockquote>\n\n<p>It could be moved a new method:</p>\n\n<pre><code>private void handleException2(Exception e) {\n handleException(e.getCause() != null ? e.getCause().toString() : e.toString(), LnPRead.flagTerminate);\n}\n</code></pre>\n\n<p>A few explanatory local variable would make it more readable:</p>\n\n<pre><code>private void handleException2(final Exception e) {\n final Throwable cause = e.getCause();\n final String exceptionString;\n if (cause == null) {\n exceptionString = e.toString();\n } else {\n exceptionString = cause.toString();\n }\n handleException(exceptionString, LnPRead.flagTerminate);\n}\n</code></pre>\n\n<p>Reference: <em>Chapter 6. Composing Methods</em>, <em>Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler:</p>\n\n<blockquote>\n <p>Put the result of the expression, or parts of the expression, \n in a temporary variable with a name that explains the purpose.</p>\n</blockquote>\n\n<p>And <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>.</p></li>\n<li><p>The <code>randomID</code> local variable is unnecessary here:</p>\n\n<blockquote>\n<pre><code>private int generateRandomId(Random r) {\n int randomID;\n\n if (r.nextFloat() < LnPRead.percentageValidId / 100) {\n randomID = r.nextInt(LnPRead.endValidRange - LnPRead.startValidRange + 1) + LnPRead.startValidRange;\n } else {\n randomID = r.nextInt(LnPRead.endNonValidRange - LnPRead.startNonValidRange + 1)\n + LnPRead.startNonValidRange;\n }\n\n return randomID;\n}\n</code></pre>\n</blockquote>\n\n<p>You could return immediately (and use an explanatory variable too):</p>\n\n<pre><code>private int generateRandomId(final Random r) {\n final boolean generateValidId = r.nextFloat() < LnPRead.percentageValidId / 100;\n if (generateValidId) {\n return r.nextInt(LnPRead.endValidRange - LnPRead.startValidRange + 1) + LnPRead.startValidRange;\n } else {\n return r.nextInt(LnPRead.endNonValidRange - LnPRead.startNonValidRange + 1)\n + LnPRead.startNonValidRange;\n }\n}\n</code></pre>\n\n<p>Note that how easy to decide now whether the <code>if</code> or the <code>else</code> branch generates valid IDs. (I've just guessed here, you might need to invert the condition.)</p></li>\n<li><p>I'd move the <code>random.nextDouble()</code> inside the <code>selectRandomTable</code> method.</p>\n\n<blockquote>\n<pre><code>double randomNumber = random.nextDouble() * 100.0;\nTableConnectionInfo table = selectRandomTable(randomNumber);\n</code></pre>\n</blockquote>\n\n<p>Nothing indicates the parameter should be between <code>0</code> and <code>100</code>. It should be an internal part of the method to choose a proper random number.</p></li>\n<li><p>In the same method, the <code>IllegalStateException</code> should contain some debugging information, like the generated random number. It would help debugging.</p></li>\n<li><p><code>columnsList.split(\",\")</code> could be extracted out to a local variable. It's used multiple times.</p></li>\n<li><blockquote>\n<pre><code>durationOfRun = Long.parseLong(prop.getProperty(\"TOTAL_RUNNING_TIME\").trim());\nsleepTime = Long.parseLong(prop.getProperty(\"SLEEP_TIME\").trim());\n</code></pre>\n</blockquote>\n\n<p>The parsing and trimming could have a separate function:</p>\n\n<pre><code>private static long loadLong(Properties properties, String key) {\n return Long.parseLong(properties.getProperty(key).trim());\n}\n</code></pre>\n\n<p>You can create similar functions for the boolean and integer fields too.</p></li>\n<li><blockquote>\n<pre><code>for (String arg: tableNames) {\n</code></pre>\n</blockquote>\n\n<p><code>arg</code> is not too descriptive here. I'd call it <code>tableName</code>.</p></li>\n<li><p>I'd rename <code>isJSONValid</code> to <code>isJsonValid</code> or <code>isValidJson</code>. I think it would be easier to read (although it's inconsistent with the JSON library's naming but I think that's a minor issue). From <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em>: </p>\n\n<blockquote>\n <p>While uppercase may be more common, \n a strong argument can made in favor of capitalizing only the first \n letter: even if multiple acronyms occur back-to-back, you can still \n tell where one word starts and the next word ends. \n Which class name would you rather see, HTTPURL or HttpUrl?</p>\n</blockquote></li>\n<li><p>The <code>isJSONValid</code> contains two magic numbers:</p>\n\n<blockquote>\n<pre><code>JSONArray data = obj.getJSONArray(\"lv\");\nint n = data.length();\n\nfor (int i = 0; i < n; ++i) {\n JSONObject lv = data.getJSONObject(i);\n JSONObject v = lv.getJSONObject(\"v\");\n...\n</code></pre>\n</blockquote>\n\n<p>They are the <code>lv</code> and <code>v</code> strings. Constants with longer and more descriptive name would help readers to figure out what should be the content of these fields. You could also rename the variable names too (<code>data</code>, <code>lv</code>, <code>v</code>) to express the intent.</p></li>\n<li><blockquote>\n<pre><code>final int n = data.length();\n\nfor (int i = 0; i < n; ++i) {\n</code></pre>\n</blockquote>\n\n<p>It seem a microoptimization, I guess the JVM will cache that for you if it counts. (<a href=\"https://stackoverflow.com/a/9337135/843804\">JVM option to optimize loop statements</a>)</p></li>\n<li><blockquote>\n<pre><code> * @param str\n * @param id\n * @return\n</code></pre>\n</blockquote>\n\n<p>I'd remove these comments. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><blockquote>\n<pre><code>public boolean isJSONValid(final String str, final int id) {\n</code></pre>\n</blockquote>\n\n<p>I'd rename the parameter to <code>jsonString</code> from <code>str</code>.</p></li>\n<li><blockquote>\n<pre><code>private HashMap<String, Connection> tableStatement = new HashMap<String, Connection>();\nprivate final LinkedHashMap<String, TableConnectionInfo> tableLists; \n</code></pre>\n</blockquote>\n\n<p><code>HashMap<...></code> reference types should be simply <code>Map<...></code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n<li><blockquote>\n<pre><code>if (id >= LnPRead.startValidRange && id <= LnPRead.endValidRange) {\n</code></pre>\n</blockquote>\n\n<p><code>startValidRange</code> sounds like a method (the name starts with a verb/action). I'd call it <code>validRangeStart</code>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T16:11:23.240",
"Id": "43793",
"ParentId": "23409",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-03T23:56:53.433",
"Id": "23409",
"Score": "4",
"Tags": [
"java",
"multithreading",
"json",
"jdbc"
],
"Title": "Finding potential thread safety issues and race conditions in my multithreading code"
}
|
23409
|
<p>I'm having performance issues with this query. If I remove the <code>status</code> column, it runs very fast; but adding the subquery in the column section delays the query way too much (1.02 min execution). How can I modify this query so it runs faster while still getting the desired data?</p>
<p>The reason I put that subquery there is because I needed the status for the latest activity; some activities have <code>null</code> status so I have to ignore them.</p>
<p>Establishments: 6.5k rows -
EstablishmentActivities: 70k rows -
Status: 2 (Active, Inactive)</p>
<pre><code>SELECT DISTINCT
est.id,
est.trackingNumber,
est.NAME AS 'establishment',
actTypes.NAME AS 'activity',
(
SELECT stat3.NAME
FROM SACPAN_EstablishmentActivities eact3
INNER JOIN SACPAN_ActivityTypes at3
ON eact3.activityType_FK = at3.code
INNER JOIN SACPAN_Status stat3
ON stat3.id = at3.status_FK
WHERE eact3.establishment_FK = est.id
AND eact3.rowCreatedDT = (
SELECT MAX(est4.rowCreatedDT)
FROM SACPAN_EstablishmentActivities est4
INNER JOIN SACPAN_ActivityTypes at4
ON est4.establishment_fk = est.id
AND est4.activityType_FK = at4.code
WHERE est4.establishment_fk = est.id
AND at4.status_FK IS NOT NULL
)
AND at3.status_FK IS NOT NULL
) AS 'status',
est.authorizationNumber,
reg.NAME AS 'region',
mun.NAME AS 'municipality',
ISNULL(usr.NAME, '') + ISNULL(+ ' ' + usr.lastName, '')
AS 'created',
ISNULL(usr2.NAME, '') + ISNULL(+ ' ' + usr2.lastName, '')
AS 'updated',
est.rowCreatedDT,
est.rowUpdatedDT,
CASE WHEN est.rowUpdatedDT >= est.rowCreatedDT
THEN est.rowUpdatedDT
ELSE est.rowCreatedDT
END AS 'LatestCreatedOrModified'
FROM SACPAN_Establishments est
INNER JOIN SACPAN_EstablishmentActivities eact
ON est.id = eact.establishment_FK
INNER JOIN SACPAN_ActivityTypes actTypes
ON eact.activityType_FK = actTypes.code
INNER JOIN SACPAN_Regions reg
ON est.region_FK = reg.code --
INNER JOIN SACPAN_Municipalities mun
ON est.municipality_FK = mun.code
INNER JOIN SACPAN_ContactEstablishments ce
ON ce.establishment_FK = est.id
INNER JOIN SACPAN_Contacts con
ON ce.contact_FK = con.id
--JOIN SACPAN_Status stat ON stat.id = actTypes.status_FK
INNER JOIN SACPAN_Users usr
ON usr.id = est.rowCreatedBy_FK
LEFT JOIN SACPAN_Users usr2
ON usr2.id = est.rowUpdatedBy_FK
WHERE (con.ssn = @ssn OR @ssn = '*')
AND eact.rowCreatedDT = (
SELECT MAX(eact2.rowCreatedDT)
FROM SACPAN_EstablishmentActivities eact2
WHERE eact2.establishment_FK = est.id
)
--AND est.id = 6266
ORDER BY 'LatestCreatedOrModified' DESC
</code></pre>
<p>I can't upload the execution plan because of rep points, but there's a 21% on one of the establishment activity tables.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T10:52:15.360",
"Id": "36091",
"Score": "0",
"body": "Please provide [DDL](http://en.wikipedia.org/wiki/Data_definition_language) query for the tables and execution plan"
}
] |
[
{
"body": "<p>Your code is calling several tables multiple times when it doesn't seem like it needs to. Can you pull out your Activities related tables into common table expressions and just link to those in your main query. Rough example:</p>\n\n<pre><code>;with created as\n(\n select establishment_fk, max(rowCreatedDT) as maxCreated\n FROM SACPAN_EstablishmentActivities\n JOIN SACPAN_ActivityTypes at4\n ON activityType_FK = at4.code\n WHERE at4.status_FK IS NOT NULL \n),\n status as \n(\n SELECT eact3.establishment_fk, stat3.NAME as status, at3.NAME as activity\n FROM SACPAN_EstablishmentActivities eact3\n INNER JOIN SACPAN_ActivityTypes at3\n ON eact3.activityType_FK = at3.code\n INNER JOIN SACPAN_Status stat3\n ON stat3.id = at3.status_FK\n where exists\n (select 1 from created \n where created.establishment_fk = eact3.establishment_fk\n and created.maxCreated = eact3.rowCreatedDT)\n)\nSELECT DISTINCT\n est.id,\n est.trackingNumber,\n est.NAME AS 'establishment',\n actTypes.NAME AS 'activity',\n AS 'status',\n est.authorizationNumber,\n reg.NAME AS 'region',\n mun.NAME AS 'municipality',\n ISNULL(usr.NAME, '') + ISNULL(+ ' ' + usr.lastName, '')\n AS 'created',\n ISNULL(usr2.NAME, '') + ISNULL(+ ' ' + usr2.lastName, '')\n AS 'updated',\n est.rowCreatedDT,\n est.rowUpdatedDT,\n CASE WHEN est.rowUpdatedDT >= est.rowCreatedDT\n THEN est.rowUpdatedDT\n ELSE est.rowCreatedDT\n END AS 'LatestCreatedOrModified'\nFROM SACPAN_Establishments est\nINNER JOIN status on status.establishment_fk = est.id\nINNER JOIN SACPAN_Regions reg\n ON est.region_FK = reg.code --\nINNER JOIN SACPAN_Municipalities mun\n ON est.municipality_FK = mun.code\nINNER JOIN SACPAN_ContactEstablishments ce\n ON ce.establishment_FK = est.id\nINNER JOIN SACPAN_Contacts con\n ON ce.contact_FK = con.id\nINNER JOIN SACPAN_Users usr\n ON usr.id = est.rowCreatedBy_FK\nLEFT JOIN SACPAN_Users usr2\n ON usr2.id = est.rowUpdatedBy_FK\nWHERE (con.ssn = @ssn OR @ssn = '*')\n</code></pre>\n\n<p>That may be a little rough, but the idea here is to pull out what your Max Created date is just once and then just get your status as one set. I'm fairly certain that a large part of your slowness on the status subquery is how it's having to run; if you can get it into one set that you can then connect to the main query, will hopefully help.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-13T03:24:05.370",
"Id": "108038",
"Score": "1",
"body": "I would like to say, while CTEs make the code much easier to read, they generally don't improve performance, because the CTE has to be ran every time it's called, just like a subquery. But I do like how your query looks a lot better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-12T23:35:55.997",
"Id": "23814",
"ParentId": "23410",
"Score": "2"
}
},
{
"body": "<p><strong>Nitpicking</strong></p>\n<p>I find your table aliases to be difficult to follow. Take this with a grain of salt coming from an outsider to your organization. I find <code>eact</code>, <code>eact3</code>, <code>eact4</code>, etc. to be a bit confusing, for example. Granted, if there is an internal, consistent standard, disregard this part.</p>\n<p><strong><code>SELECT DISTINCT</code></strong></p>\n<p>This is a pretty expensive operation, and <a href=\"https://stackoverflow.com/questions/54418/how-do-i-or-can-i-select-distinct-on-multiple-columns\">usually better to use GROUP BY instead</a>. That way you run your uniqueness check on the result set instead of the source data set (which could be a LOT larger) and only on the columns you think/know may have duplicate values. For example:</p>\n<pre><code>GROUP BY est.id, est.trackingNumber, actTypes.NAME\n</code></pre>\n<p><strong>Create a stored statement</strong></p>\n<p>Given the look of this whole script, this doesn't smell like an ad-hoc query to me. Assuming that's accurate, you would benefit from creating a stored statement, in this case likely a stored procedure. This commented line at the bottom kind of gave me a hint:</p>\n<pre><code>-- AND est.id = 6266\n</code></pre>\n<p>For example:</p>\n<pre><code>CREATE PROCEDURE FooBar\n @Establishment_ID INT\nAS\nBEGIN\n/* your query here */\nAND est.id = @Establishment_ID -- your commented line\nORDER BY 'LatestCreatedOrModified' DESC\nEND;\nGO\n</code></pre>\n<p>Then, whenever needed:</p>\n<pre><code>EXEC FooBar 6266;\n</code></pre>\n<p>This way, the execution plan will be stored after it is called for the first time, speeding up (sometimes dramatically) execution after it is ran once.</p>\n<p><strong>Compliments</strong></p>\n<p>I have to note that your formatting, capitalization and aliasing are consistent. Kudos for that.</p>\n<h1><strong>The elephant in the room</strong></h1>\n<p>To me, the slowness of this query could be largely due to multiple levels of nested subqueries, each with multiple <code>join</code> operations. It appears that you join the same tables over and over, and this could be mitigated to some extent by having your nested <code>where</code> clauses in your outer query, whenever possible.</p>\n<p>This:</p>\n<pre><code> FROM SACPAN_EstablishmentActivities eact3 --(1)\n INNER JOIN SACPAN_ActivityTypes at3 -- (2)\n ON eact3.activityType_FK = at3.code\n INNER JOIN SACPAN_Status stat3 -- (3)\n</code></pre>\n<p>That:</p>\n<pre><code> FROM SACPAN_EstablishmentActivities est4 -- (1)\n INNER JOIN SACPAN_ActivityTypes at4 -- (2)\n</code></pre>\n<p>And the other:</p>\n<pre><code>INNER JOIN SACPAN_EstablishmentActivities eact -- (1)\n ON est.id = eact.establishment_FK\nINNER JOIN SACPAN_ActivityTypes actTypes -- (2)\n ON eact.activityType_FK = actTypes.code\nINNER JOIN SACPAN_Regions reg\n ON est.region_FK = reg.code --\nINNER JOIN SACPAN_Municipalities mun\n ON est.municipality_FK = mun.code\nINNER JOIN SACPAN_ContactEstablishments ce\n ON ce.establishment_FK = est.id\nINNER JOIN SACPAN_Contacts con\n ON ce.contact_FK = con.id\n--JOIN SACPAN_Status stat -- (3)\n</code></pre>\n<p>Notice I've commented out where you are joining all the same tables. You could more than likely work most these conditions into your <code>where</code> clause and avoid unneeded overhead. It's impossible for me to test it out, since I don't have access to your DB, but try to eliminate subqueries/CTEs as much as you can help it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-13T03:01:46.900",
"Id": "59862",
"ParentId": "23410",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T01:40:12.810",
"Id": "23410",
"Score": "1",
"Tags": [
"performance",
"sql",
"sql-server"
],
"Title": "Subquery performance too slow"
}
|
23410
|
<p>Is this an ideal use of if..else or can this code be simplified/beautified further?</p>
<pre><code> // If any image found and bigger than thumbnail settings, get that one
if ( isset( $matches ) && !empty( $matches[1][0] ) ) {
$image_found = $matches[1][0];
$image_dimensions = getimagesize($image_found);
if ( ( $image_dimensions[0] > $width ) && ( $image_dimensions[1] > $height ) ) {
$thumbnail_img = $matches[1][0];
}
// Check 2nd image found
else if ( !empty( $matches[1][1] ) ) {
$image_found = $matches[1][1];
$image_dimensions = getimagesize($image_found);
if ( ( $image_dimensions[0] > $width ) && ( $image_dimensions[1] > $height ) ) {
$thumbnail_img = $matches[1][1];
}
// Check 3rd image found
else if ( !empty( $matches[1][2] ) ) {
$image_found = $matches[1][2];
$image_dimensions = getimagesize($image_found);
if ( ( $image_dimensions[0] > $width ) && ( $image_dimensions[1] > $height ) ) {
$thumbnail_img = $matches[1][2];
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>One of the points that should raise a query is the amount of repeated code - you have a duplicate for every if. This suggests creating a function to handle it instead. Personally, I would end up with something like the following:</p>\n\n<pre><code>function is_better_image( $image, $thumbnail_width, $thumbnail_height )\n{\n $image_dimensions = getimagesize($image);\n if ( ( $image_dimensions[0] > $thumbnail_width ) && ( $image_dimensions[1] > $thumbnail_height ) ) {\n return true; \n }\n return false;\n}\n\nfunction check_image( $image, $width, $height )\n{\n if ( !empty( $image ) ) {\n if ( is_better_image( $image, $width, $height ) ) {\n return $image;\n }\n }\n}\n...\nif ( isset( $matches ) ) {\n // check all possible image matches\n $possible_thumbnail_img = check_image( $matches[1][0], $width, $height );\n if ( is_null( $possible_thumbnail_img ) ) {\n $possible_thumbnail_img = check_image( $matches[1][1], $width, $height );\n }\n if ( is_null( $possible_thumbnail_img ) ) {\n $possible_thumbnail_img = check_image( $matches[1][2], $width, $height );\n }\n // if we have a suitable image, use that instead\n if ( !is_null( $possible_thumbnail_img ) ) {\n $thumbnail_img = $possible_thumbnail_img\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T08:27:11.320",
"Id": "23414",
"ParentId": "23412",
"Score": "1"
}
},
{
"body": "<p>Let me make it clear for myself. You have an array of images, which sometimes can be empty. You start off by checking the first image, if it's valid for your needs you take it, and if not you keep on checking the next one, and the next one, and so on until you find the one which is valid. Is that right? If so, here are my few thoughts. </p>\n\n<p>Firstly, I must say that Glenn has made good points, namely: 1) factor the common code in all cases out to a separate function, and 2) if you have nested conditionals, most times it's better and more readable to replace it with <a href=\"http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\">Guard Clauses</a>.\nHowever, personally I would prefer the following solution:</p>\n\n<pre><code>$theImg = null;\n$i = 0;\nwhile (!empty($matches[1][$i])) {\n $imgAtHand = $matches[1][$i];\n $dimensions = getimagesize($imgAtHand);\n if (($dimensions[0] > $width) && ($dimensions[1] > $height)) {\n $theImg = $imgAtHand;\n break;\n }\n $i++;\n}\n</code></pre>\n\n<p>It has a couple of advantages over the \"nested conditional\" approach:</p>\n\n<ul>\n<li>it eliminates code duplication;</li>\n<li>it will work regardless of the array size.</li>\n</ul>\n\n<p>One more thing. The following piece of code</p>\n\n<pre><code>isset($matches) && !empty($matches[1][0])\n</code></pre>\n\n<p>may well be replaced with</p>\n\n<pre><code>!empty($matches[1][0])\n</code></pre>\n\n<p>to make the code less verbose.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T10:03:54.577",
"Id": "36216",
"Score": "0",
"body": "$theImg = null; should be $theImg = NULL; right? http://php.net/manual/en/language.types.null.php"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T11:35:51.663",
"Id": "36221",
"Score": "0",
"body": "@drtanz, the `NULL` constant, as well as `TRUE` and `FALSE`, is case-insensitive, but usually it's written in lowercase by convention (https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md#25-keywords-and-truefalsenull)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T09:46:06.700",
"Id": "23417",
"ParentId": "23412",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "23417",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T04:46:27.843",
"Id": "23412",
"Score": "4",
"Tags": [
"php",
"image"
],
"Title": "If any image found and bigger than thumbnail settings, get that one"
}
|
23412
|
<p>I'd like to know any ways of shortening this UI window for Maya, at the moment, because I couldn't find very detailed documentation and not very skilled with python, I have just built this UI with the knowledge that I have already, I know it's not the best way of doing it (using empty text elements to fill gaps etc)</p>
<p>Can someone provide me with an example on how to shorten this code or structure it properly?</p>
<pre><code>import maya.cmds as cmds
class randomScatter():
def __init__(self):
if cmds.window("randSelection", exists=1): cmds.deleteUI("randSelection")
cmds.window("randSelection", t="Scatter Objects - Shannon Hochkins", w=405, sizeable=0)
cmds.rowColumnLayout(nc=3,cal=[(1,"right")], cw=[(1,100),(2,200),(3,105)])
cmds.text(l="Prefix ")
cmds.textField("prefix")
cmds.text(l="")
cmds.text(l="Instanced object(s) ")
cmds.textField("sourceObj", editable=0)
cmds.button("sourceButton", l="Select")
cmds.text(l="Target ")
cmds.textField("targetObj", editable=0)
cmds.button("targetButton", l="Select")
cmds.separator( height=20, style='in')
cmds.separator( height=20, style='in')
cmds.separator( height=20, style='in')
cmds.text(l='Copy Options ')
cmds.radioButtonGrp('copyOptions', labelArray2=['Duplicate', 'Instance'], numberOfRadioButtons=2, sl=2)
cmds.text(l="")
cmds.text(l="Rotation Options ")
cmds.radioButtonGrp('orientation', labelArray2=['Follow Normals', 'Keep original'], numberOfRadioButtons=2, sl=1)
cmds.text(l="")
cmds.separator( height=20, style='in')
cmds.separator( height=20, style='in')
cmds.separator( height=20, style='in')
cmds.text(l="")
cmds.checkBox('copyCheck', l='Stick copies to target mesh.')
cmds.text(l="")
cmds.separator( height=20, style='in')
cmds.separator( height=20, style='in')
cmds.separator( height=20, style='in')
cmds.text('maxNumber', l="Copies ")
cmds.intFieldGrp("totalCopies", nf=1, v1=10, cw1=100)
cmds.text(l="")
cmds.separator( height=20, style='in')
cmds.separator( height=20, style='in')
cmds.separator( height=20, style='in')
cmds.text(l='')
cmds.text(l=" From To", align='left')
cmds.text(l='')
cmds.text(l="Random Rotation")
cmds.floatFieldGrp("rotValues", nf=2, v1=0, v2=0, cw2=[100,100])
cmds.text(l="")
cmds.text(l="Random Scale")
cmds.floatFieldGrp("scaleValues", nf=2, v1=0, v2=0, cw2=[100,100])
cmds.text(l="")
cmds.setParent("..")
cmds.rowColumnLayout(w=405)
cmds.separator( height=20, style='in')
cmds.text("Progress", height=20)
cmds.progressBar('buildGridProgBar', maxValue=100, width=250)
cmds.separator( height=20, style='in')
cmds.button("excute", l="Scatter Objects", w=403, al="right")
cmds.showWindow("randSelection")
randomScatter()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T13:59:48.320",
"Id": "51163",
"Score": "0",
"body": "You have alot of cmds.separator lines in a group of 3. Put them in for loops. Allmost everytime when the code looks repetetive, there can be used a loop to shorten it."
}
] |
[
{
"body": "<p>It's not easy to answer this question, since:</p>\n\n<ol>\n<li>it applies to very specific Maya Embedded Language commands that aren't well documented,</li>\n<li>it's difficult to run the software ourselves.</li>\n</ol>\n\n<p>Anyway, based on other GUIs I've worked with, you don't need to worry too much about the code quality. Popular frameworks usually provide... GUIs (eg. Qt Creator) that allow you to create place your elements, and then generate code that looks like yours (not always too good). If this is possible in Maya, go for it.</p>\n\n<p>You can go with that approach yourself too: separate GUI code from everything else, and use parameters in <code>__init__</code> for what is likely to change in the future.</p>\n\n<p>I also recommand that you follow PEP 8, especially the <a href=\"http://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow\">section on whitespaces</a>. This is a standard that a lot of Python developers follow: it makes it way easier to work with other Python developers that share this convention.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-03T06:51:15.793",
"Id": "25757",
"ParentId": "23413",
"Score": "0"
}
},
{
"body": "<p>(1) You define <code>random_scatter</code> as a class but then call it like a function, which works but is confusing. With your programme as it currently stands, there is no reason for it to be a class, so better simply to define <code>random_scatter</code> as a function (use <code>def random_scatter():</code> at the top). </p>\n\n<p>(2) You can remove repetition and make the code more readable using functions and loops, e.g. write a function</p>\n\n<pre><code>def insert_seperators(number):\n for _ in range(number):\n cmds.separator(height=20, style='in')\n</code></pre>\n\n<p>then you can replace </p>\n\n<pre><code> cmds.separator( height=20, style='in')\n cmds.separator( height=20, style='in')\n cmds.separator( height=20, style='in')\n</code></pre>\n\n<p>with</p>\n\n<pre><code> insert_separators(3)\n</code></pre>\n\n<p>(3) If you have other functions doing similar things with <code>cmds</code> then try to see what they have in common and put that in a single function, which accepts parameters according to what changes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-31T13:09:51.487",
"Id": "30559",
"ParentId": "23413",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T06:02:07.410",
"Id": "23413",
"Score": "2",
"Tags": [
"python"
],
"Title": "Shorten Python/Maya Window UI code"
}
|
23413
|
<p>This script extracts all urls from a specific HTML div block (with BeautifulSoup 4) : </p>
<pre><code>raw_data = dl("http://somewhere")
links = []
soup = BeautifulSoup(raw_data)
data = str(soup.find_all('div', attrs={'class' : "results"}))
for link in BeautifulSoup(data, parse_only = SoupStrainer('a')):
links.append(urllib.parse.unquote_plus(link['href']))
return links
</code></pre>
<p>Is there a more efficient and clean way to do it ?</p>
|
[] |
[
{
"body": "<p>AFAIK, you can use <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">List comprehension</a> to make it more efficient </p>\n\n<pre><code>raw_data = dl(\"http://somewhere\")\nsoup = BeautifulSoup(raw_data)\ndata = str(soup.find_all('div', attrs={'class' : \"results\"}))\nreturn [ urllib.parse.unquote_plus(link['href']) for link in BeautifulSoup(data, parse_only = SoupStrainer('a'))]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T12:45:56.947",
"Id": "23426",
"ParentId": "23416",
"Score": "1"
}
},
{
"body": "<p>I would use <strong>lmxl.html</strong> + <strong>xpath</strong></p>\n\n<p>Let's say, the html you get from \"url\" is:</p>\n\n<pre><code> <html>\n <body>\n <div class=\"foo\">\n <a href=\"#foo1\">foo1</a>\n <a href=\"#foo2\">foo2</a>\n </div>\n <div class=\"results\">\n <a href=\"#res1\">res1</a>\n <a href=\"#res2\">res2</a>\n </div>\n <div class=\"bar\">\n <a href=\"#bar1\">bar1</a>\n <a href=\"#bar2\">bar2</a>\n </div>\n <div id=\"abc\">\n <a href=\"#abc\">abc</a>\n </div>\n <div>\n <a href=\"#nothing\">nothing</a>\n </div>\n <a href=\"#xyz\">xyz</a>\n </body>\n </html>\n</code></pre>\n\n<p>Here is how I would do:</p>\n\n<pre><code>from StringIO import StringIO\nfrom lxml.html import parse\n\nif __name__ == '__main__':\n\n tree = parse(url)\n hrefs = tree.xpath(\"//div[@class='results']/a/@href\")\n\n print hrefs\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>['#res1', '#res2']\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-19T08:59:08.537",
"Id": "24075",
"ParentId": "23416",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T09:40:40.713",
"Id": "23416",
"Score": "1",
"Tags": [
"python"
],
"Title": "URLs extraction from specific block"
}
|
23416
|
<p>I've got this code</p>
<pre><code>Double best = nodes.get(edge.getToNodeId());
if (best == null || (best > g+h)) {
nodes.put(edge.getToNodeId(), g+h);
if (best == null) {
open.add(new State(edge.getToNodeId(), g, h, top));
} else {
open.modify(new State(edge.getToNodeId(), g, h, top));
}
}
</code></pre>
<p>I don't quite like it because I duplicate the <code>best == null</code> clause. Would it be better in these types of situation to duplicate the <code>nodes.put()</code> instead? Or is there some third, more readable, way without duplicates?</p>
|
[] |
[
{
"body": "<p>I think it's a matter of taste and preference. In either case, you would have to duplicate something. But, there's something that drew my attention. I don't claim it to be correct or be a solution to your problem. Hard to say without knowing the context and data structures that you use. Anyways, here we go...</p>\n\n<p>I noticed that in both cases, whether <code>best == null</code> or not, you pass the same arguments, though to different methods. I suspect that this checking might occur in many other places as well. So, what if we create a method (e.g. <code>addOrModify()</code>) and move this condition statement to that method. And the method would internally decide whether to add a new <code>State</code> or modify the existing one. Somewhat similar behavior may be observed in the <code>java.util.Set.add(E e)</code> method, where the method checks if the element has already been added to the <code>Set</code> and then returns <code>false</code> without adding it twice...</p>\n\n<p>Then, we end up with something like this in the client code:</p>\n\n<pre><code>Double best = nodes.get(edge.getToNodeId());\nif (best == null || (best > g+h)) {\n nodes.put(edge.getToNodeId(), g+h);\n open.addOrModify(new State(edge.getToNodeId(), g, h, top)); \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T10:55:21.843",
"Id": "36092",
"Score": "0",
"body": "addOrModify() is an option I considered, but it would need one special argument for the \"best\" value. Anyway this snippet is just from an implementation of A* algorithm which is no more than 100 lines of code so I don't want to overcomplicate things. I was just wondering if the solution I've written doesn't seem ugly :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T11:08:00.610",
"Id": "36093",
"Score": "0",
"body": "@HonzaBrabec, well, I wouldn't say it's ugly. Maybe \"a necessary evil\" at most... In your case, however, I believe it's good enough."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T10:43:53.053",
"Id": "23419",
"ParentId": "23418",
"Score": "5"
}
},
{
"body": "<ol>\n<li><p>You can introduce a local variable for the result of the null check. The following expressions are also duplicated in the code:</p>\n\n<ol>\n<li><code>edge.getToNodeId()</code></li>\n<li><code>g+h</code></li>\n<li><code>new State(nodeId, g, h, top)</code></li>\n</ol>\n\n<p>I'd start with eliminating these:</p>\n\n<pre><code>final NodeId nodeId = edge.getToNodeId();\nfinal Double best = nodes.get(nodeId);\nfinal int gPlusH = g + h; // TODO: needs a better name\nfinal boolean newData = best == null; // TODO: needs a better name\nif (newData || (best > gPlusH)) {\n nodes.put(nodeId, gPlusH);\n final State state = new State(nodeId, g, h, top);\n if (newData) {\n open.add(state);\n } else {\n open.modify(state);\n }\n}\n</code></pre>\n\n<p>Reference: <em>Chapter 6. Composing Methods</em>, <em>Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler:</p>\n\n<blockquote>\n <p>Put the result of the expression, or parts of the expression, \n in a temporary variable with a name that explains the purpose.</p>\n</blockquote>\n\n<p>And <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>.</p></li>\n<li><p>Short variable names (like <code>g</code> and <code>h</code>) are not too readable. I suppose you have autocomplete, so using longer names does not mean more typing but it would help readers and maintainers a lot since they don't have to remember the purpose of each variable - the name would express the programmers intent.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T13:55:05.500",
"Id": "36107",
"Score": "1",
"body": "[Sometimes short variable names are good](http://programmers.stackexchange.com/a/176585/633)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:56:27.553",
"Id": "36145",
"Score": "0",
"body": "I know these practices you've mentioned, however I don't think there is always a need to be so dogmatic (sorry) :) g and h are the case of names @Svish mentioned. Naming variable gPlusH IMO doesn't help the maintainability in any way. It just duplicates the expression. What if I wanted to change the expression? I'd have to change the name of the variable too (not too comfortable i think). I also find edge.getToNodeId() (which translates as \"get the id of the node this edge goes to\") more readable than nodeId. With other things you've changed I have no problem :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T12:16:31.337",
"Id": "23425",
"ParentId": "23418",
"Score": "1"
}
},
{
"body": "<p>As far as I understand the code extract, you want to create the state if it does not exist, otherwise update it if necessary.</p>\n\n<p>I would handle the special case first and continue with the normal work:</p>\n\n<pre><code> final Double best = nodes.get(edge.getToNodeId());\n if (best == null) {\n best = Double.POSITIVE_INFINITY;\n open.add(new State(edge.getToNodeId(), g, h, top));\n }\n nodes.put(edge.getToNodeId(), Math.min(g + h, best));\n if (g + h < best)\n open.modify(new State(edge.getToNodeId(), g, h, top));\n</code></pre>\n\n<p>Other than that, I would think about better variable names. It could be helpful to change method signatures or objects, too. This depends on the rest of the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T12:18:18.257",
"Id": "23479",
"ParentId": "23418",
"Score": "1"
}
},
{
"body": "<p>What is 'g' or 'h'? How could you name your conditions in 'if' statement? Use better names and you will find the solution. I assume that 'g' is 'guru' and 'h' is 'height' :) Also you can extend your 'open' thing and inject there the operation you want. Also you can hide your conditions with a nice name or reuse these. So, you can make appropriate code changes in order to achieve the following pattern:</p>\n\n<pre><code>BestAndGuruAndHeightWrapper bestAndGuruAndHeightWrapper = new BestAndGuruAndHeightWrapper (nodes.get (edge.getToNodeId()), guru, height);\n\nConditionsCollection conditionsCollection = new ConditionsCollection ();\n\nif (conditionsCollection.AConditionToPerform (bestAndGuruAndHeightWrapper)) {\n nodes.put(edge.getToNodeId(), bestAndGuruAndHeightWrapper.Guru + bestAndGuruAndHeightWrapper.Height);\n\n open.operate(new State(edge.getToNodeId(), bestAndGuruAndHeightWrapper.Guru, bestAndGuruAndHeightWrapper.Height, top), bestAndGuruAndHeightWrapper.Best);\n}\n</code></pre>\n\n<p>You can also use the Decorator pattern in order to add the \"if null check\" responsibility to your \"open object\" thing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-08T10:40:14.480",
"Id": "36403",
"Score": "0",
"body": "The snippet is from an implementation of A* algorithm. In that context (http://en.wikipedia.org/wiki/A*_search_algorithm) The names 'g', 'h' are natural."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T20:36:55.070",
"Id": "23588",
"ParentId": "23418",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "23419",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T09:56:10.607",
"Id": "23418",
"Score": "4",
"Tags": [
"java"
],
"Title": "Nested condition subset of the top one"
}
|
23418
|
<p>So I create 3D tree like structures using L-systems. Basically this means I generate a string like this:</p>
<pre><code> "FFFFFFFF-[[FFFF-[[FF-[[F-[[X]+X]+F[+FX]-X]+F]]]]]"
</code></pre>
<p>This string is then interpreted by a turtle performing certain actions for each character in the string. The problem is how to map characters to turtle actions in an elegant way in C++.</p>
<p>Right now I use a enum to specify the actions and performAction calls methods based on the action. Is there a better way of doing it?</p>
<p>The turtle code:</p>
<pre><code>enum TurtleAction {
MoveForward,
TurnLeft,
TurnRight,
PitchDown,
PitchUp,
RollLeft,
RollRight,
TurnAround,
PushState,
PopState
};
struct TurtleState {
Vec3f pos;
Vec3f H;
Vec3f L;
Vec3f U;
double width;
};
class Turtle {
TurtleState m_currentState;
stack<TurtleState> m_states;
void(*m_drawFunc)(Vec3f,double); ///< Drawing callback
public:
double alpha; ///< Turning angle
Turtle(TurtleState startState,
void(*drawFunc)(Vec3f,double));
void performAction(TurtleAction action);
private:
void move(double dist);
void turn(double deg);
void pitch(double deg);
void roll(double deg);
void push();
void pop();
void rotate(const Mat44f & R);
};
void
Turtle::performAction(TurtleAction action){
switch (action) {
case MoveForward:
move(1.0f);
break;
case TurnLeft:
turn(-alpha);
case TurnRight:
turn(+alpha);
case PitchDown:
pitch(-alpha);
case PitchUp:
pitch(+alpha);
case RollLeft:
roll(-alpha);
case RollRight:
roll(+alpha);
case TurnAround:
turn(180.0f);
case PushState:
push();
case PopState:
pop();
default:
break;
}
}
</code></pre>
<p>The string parsing:</p>
<pre><code>class LSystem {
map<char,TurtleAction> m_actionRules;
TurtleState m_start;
public:
void draw(string & str,void(*drawFunc)(Vec3f,double));
void computeString(string & axiom, int generations);
LSystem();
~LSystem();
};
void
LSystem::draw(string &str, void (*drawFunc)(Vec3f, double))
{
Turtle turtle(m_start,drawFunc);
turtle.alpha = 25.0f;
for (int s = 0; s < str.size(); s++) {
char c = str[s];
map<char,TurtleAction>::iterator it = m_actionRules.find(c);
if (it != m_actionRules.end()) {
turtle.performAction(it->second);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T00:33:20.100",
"Id": "36192",
"Score": "0",
"body": "Have you considered that sometimes more than one character chained together can have a different meaning. Or more than one character can mean one instructions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T10:38:25.673",
"Id": "36217",
"Score": "0",
"body": "No. Right now I only work with single character instructions. Actually I don't know how easily it could be done with varying instruction lengths. Either I would need to introduce some separation characters or have some kind of state machine."
}
] |
[
{
"body": "<p>The design flaw <strong>would have been</strong> the use of this switch case with 11 entries. That's already a lot. By the way I warn you, you have forgotten 9 <code>break</code> out of 11 cases.</p>\n\n<p>However, in your case, each case relates to a single action. I mean, there is not a lot new to understand while reading: for each case you define a single behaviour action, inside a single word function call. (You don't put multi line, multi code, with multi conditions behaviour that is complex inside your switch case... : this is the thing to avoid and you have avoided it)</p>\n\n<p>So honestly speaking it's totally acceptable.</p>\n\n<p><br></p>\n\n<p>Only for your culture I am mentionning some ways to get rid of switch case. I repeat myself, you shouldn't apply them in your case right now.</p>\n\n<p>However, the first thing you may notice in such design, maybe there are common behaviours that are dupplicated between all your function call inside the switch case.</p>\n\n<p>Imagine, if in roll() and turn() you would first have to</p>\n\n<ol>\n<li>Turn head to the right to see if nothing tries to cross my path</li>\n<li>Turn head to the left to see if nothing is moving straight right on me</li>\n</ol>\n\n<p>and then only to <code>roll()</code> or to <code>turn()</code></p>\n\n<p>Then you could start thinking about using the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">Strategy pattern</a> instead of simple function calls. This way, the strategy object which contain the action to do, can share common behaviour in a mother class.</p>\n\n<p>If you started to have really many Strategies, that should be tune and tweaked precisely, then you would think about implementing the <a href=\"http://en.wikipedia.org/wiki/Interpreter_pattern\" rel=\"nofollow\">Interpreter Pattern</a> so as to map between the precise language in your entry and the Strategies to apply.</p>\n\n<p>And if you start to have a big Interpreter object and you think you need a grammar to express all the possibilities, then no doubt you should think about a Domain Specific Language. ( with you how parser etc... ).</p>\n\n<p>In your case the switch case is entirely sufficient ;-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:27:09.463",
"Id": "36130",
"Score": "0",
"body": "Thanks alot :) The breaks were certainly a problem. Ok I will look into the two patterns. Thanks for the review!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:54:28.473",
"Id": "23439",
"ParentId": "23420",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "23439",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T11:00:56.893",
"Id": "23420",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Is there a better way to translate a string into methods?"
}
|
23420
|
<p>I wrote some code which compares numbers of all datatypes with each other.
The standard Comparer which is implemented by every number Type only compares numbers of the same type.</p>
<p>I cast to decimal because this is the largest possible number type and should cover everything.</p>
<ol>
<li>What do you think about the code?</li>
<li>Is there any room for improvement?</li>
<li>How can I handle NaN the best way?</li>
<li>Do you think BigInt and Real numbers should be a part of it?</li>
</ol>
<p></p>
<pre><code>public class UniversalNumberComparer: IComparer
{
public int Compare(object x, object y)
{
if(!IsNumber(x) || !IsNumber(y))
throw new InvalidOperationException();
if(x == null)
{
return y == null
? 0
: -1;
}
else
{
if(y == null)
return 1;
}
return Decimal.Compare(Convert.ToDecimal(x), Convert.ToDecimal(y));
}
private bool IsNumber(object value)
{
if(value is sbyte || value is sbyte?)
return true;
if(value is byte || value is byte?)
return true;
if(value is short || value is short?)
return true;
if(value is ushort || value is ushort?)
return true;
if(value is int || value is int?)
return true;
if(value is uint || value is uint?)
return true;
if(value is long || value is long?)
return true;
if(value is ulong || value is ulong?)
return true;
if(value is float || value is float?)
return true;
if(value is double || value is double?)
return true;
if(value is decimal || value is decimal?)
return true;
return false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T16:03:22.123",
"Id": "36149",
"Score": "0",
"body": "Have you even tried your code? It won't work unless both values are `decimal`. Also, what about `BigInteger`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T17:00:23.173",
"Id": "36158",
"Score": "0",
"body": "fixed.\nBigInt is part of the question. At the moment i only handle basic types at the moment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T18:50:52.787",
"Id": "36166",
"Score": "5",
"body": "Where do you see yourself needing this object? Generally, you should be comparing two numbers of the same type. Exceptions to this rule should be few enough that you should handle (and comment) it where needed rather than coming up with a general-purpose class. Needing to create a general-purpose class to compare separate number types, particularly in a type-unsafe manner reeks of code smells elsewhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T20:38:14.663",
"Id": "36178",
"Score": "1",
"body": "[Determine if type is numeric](http://stackoverflow.com/questions/124411/using-net-how-can-i-determine-if-a-type-is-a-numeric-valuetype) should be very helpful"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T13:54:05.237",
"Id": "36229",
"Score": "1",
"body": "@DanLyons The point is to have a comparer for a generic list<object> which orders the content by the values of the numbers.\nAnd... in an Assert Helper class wich test if a number value is in between 2 other values without knowing the type and without writing tons of overloads and generics make no much sense here either"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T13:57:20.520",
"Id": "36230",
"Score": "0",
"body": "@radarbob Thanks for the link i will check it out"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T19:14:51.030",
"Id": "36356",
"Score": "1",
"body": "Whenever you write code, there should be a reason to do it. Treating the code as good or bad, or considering possible improvements only makes sense if there's context of problem you're trying to solve. If there's not problem your code solves, it's just useless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-08T15:14:58.130",
"Id": "36415",
"Score": "0",
"body": "@loki2302 I would not have asked for a code review if there is no reason for me to have this code. This was not an academic example but is used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-08T16:18:52.527",
"Id": "36421",
"Score": "0",
"body": "I'm not saying it has no reason to exist, I'm saying it's impossible to tell if its good or bad unless you unveil the problem you're solving: first, the problem, then solution."
}
] |
[
{
"body": "<p>Some thoughts:</p>\n\n<ul>\n<li>There's no point in testing whether <code>x</code> or <code>y</code> is null, because when <code>null</code> is passed, <code>IsNumber()</code> returns <code>false</code>.</li>\n<li>If you do want to keep that code, perhaps by modifying <code>IsNumber()</code> to accept <code>null</code>, then you should organize that if/else tree better. Standard structure is to either <code>return</code> from every branch of the tree, not <code>return</code> from the tree at all, or (for purposes of error checking) not have an <code>else</code> clause at all. You're using an <code>if</code>/<code>else</code> pair, with a nested ternary operator (<code>? :</code>) <strong>and</strong> another nested <code>if</code>. It's just a confusing jumble.</li>\n<li>Exhaustive lists like in <code>IsNumber()</code> are generally a bad idea, but in this case I think it's acceptable. I have no opinion between lots of individual test/return pairs vs a single giant test. However, there's no point to testing the nullable cases - once you've converted to an <code>object</code> (\"boxing\"), a null value looses the type it had had, and anything else is simply the type of its value. You would have to explicitly cast it <em>back</em> to a nullable in order to set it to <code>null</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T19:28:15.923",
"Id": "36170",
"Score": "0",
"body": "I think the point about `is int?` could use some elaboration: There is no such thing as boxed nullable value. Boxing (i.e. converting to `object`) of nullable value results either in `null` or in the underlying type (e.g. `int`) boxed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T20:56:33.527",
"Id": "36179",
"Score": "0",
"body": "@svick - Good to know. I knew that it behaved that way, but I had no idea why. I'll edit in a bit more about that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T18:48:11.053",
"Id": "23453",
"ParentId": "23422",
"Score": "3"
}
},
{
"body": "<p>Based on the comment of \"radarbob\", you could redefine your IsNumber() to:</p>\n\n<pre><code>private static bool IsNumber(object value)\n{\n return TypeCodes.Contains(Type.GetTypeCode(value.GetType()));\n}\n\nprivate static readonly List<TypeCode> TypeCodes = new List<TypeCode>\n{\n TypeCode.Byte,\n TypeCode.Decimal,\n TypeCode.Double,\n TypeCode.Int16,\n TypeCode.Int32,\n TypeCode.Int64,\n TypeCode.SByte,\n TypeCode.Single,\n TypeCode.UInt16,\n TypeCode.UInt32,\n TypeCode.UInt64,\n};\n</code></pre>\n\n<p>And as \"Bobson\" mentioned, mixing the ternary operator and nested if/else structures is messy. Keep it with an if/else structure or you could try this:</p>\n\n<pre><code>public int Compare(object x, object y)\n{\n if(!IsNumber(x) || !IsNumber(y))\n throw new InvalidOperationException();\n\n return x == null\n ? (y == null ? 0 : -1)\n : (y == null ? 1 : Decimal.Compare(Convert.ToDecimal(x), Convert.ToDecimal(y)));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T23:01:33.840",
"Id": "36181",
"Score": "1",
"body": "I don't find that use of ternary particularly clear, but it's still better than the mess of conventions in the OP. It's easy enough to read through it and see what it does, but it isn't intuitively obvious."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T21:16:31.903",
"Id": "23461",
"ParentId": "23422",
"Score": "0"
}
},
{
"body": "<blockquote>\n <p>I cast to decimal because this is the largest possible number type and should cover everything.</p>\n</blockquote>\n\n<p>Since this statement uses fallacious reasoning, and the correctness of the code depends on this statement being sound, the code is unlikely to be correct. <em>Just because decimal takes up the most bytes doesn't mean that every value of every other numeric type can be represented in decimal.</em></p>\n\n<p>Presumably you would like your numeric comparer to have the property that if, say, 10<sup>200</sup> and 10<sup>210</sup> are passed in as doubles, that the one which is <em>ten billion times larger</em> would be considered larger. What actually happens?</p>\n\n<p>And presumably you would like to have the property that if say, 10<sup>-200</sup> and 10<sup>-210</sup> are passed in as doubles, that the one which is <em>ten billion times smaller</em> would be considered smaller. What actually happens?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-13T16:57:53.863",
"Id": "23869",
"ParentId": "23422",
"Score": "5"
}
},
{
"body": "<p>As for your question about NaN: this is also a situation where conversion to decimal is likely to be problematic. Assuming that you resolve that problem, the question then is what to do about it in the comparison.</p>\n\n<p>It depends on the goals of your comparison. The semantics of NaN are \"this thing isn't even a number, so asking which one is bigger is a nonsensical question\", and therefore any operation on NaN is false. That means that NaN is <em>not</em> greater than any number, <em>not</em> smaller than any number and <em>not</em> equal to any number, including itself. If that's acceptable for your comparison purposes then that's the semantics you should implement.</p>\n\n<p>Those semantics are <strong>not acceptable for sorting</strong>. If the comparison is being used in a comparison sort then the comparison is required to produce a <em>total consistent order</em>. It must be <em>reflexive</em> -- every number must equal itself. It must be <em>antisymmetric</em> -- if a < b is true then b < a must be false. And it must be <em>transitive</em> -- if a < b is true and b < c is true then a < c must be true. The usual way to deal with NaNs is to say that all NaNs are equal to each other -- achieving reflexivity, and that all NaNs are smaller than every non-NaN -- achieving antisymmetry and transitivity.</p>\n\n<p>And don't forget that you'll need to deal with positive and negative infinities.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-14T14:29:24.087",
"Id": "36838",
"Score": "0",
"body": "Thanks Eric. I already felt that casting to decimal is not the way to go. The Comparer as i posted does it for me at the moment and my project. BUT i really want to make it work considering all possible cases (Negatives, NAN, nullables,...). To be honest, i expected this task as much easier then it turned out to be."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-13T17:08:12.837",
"Id": "23870",
"ParentId": "23422",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T11:31:30.037",
"Id": "23422",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Universal number comparer"
}
|
23422
|
<p>I am learning C# and I have made my way through the entire C# 101 course on buzz3D. The last project they have you do is create a product inventory system that must be split up between classes and only the Main() method can be in the Program class. It was listed that all methods had to be as close to or below 25 lines as possible. They also required you to use an example of exception handling and outputting/reading from a file.</p>
<p>With all that said, I was wondering how you might refactor this mess I seem to have made. It works good and does exactly as they wanted, but I can't help but think my 334 lines of code is a bit unnecessary for this application. I am trying to understand the proper use of enums, classes and methods, and any help would be great appreciated!</p>
<p>Please remember that I only finished a C# 101 class, so advanced refactoring will most likely confuse me greatly, but I am here to learn. They really only covered the basics of what I currently am using in this example. Basic looping with while, for, foreach, if...method declaration with basic parameter arguments, basic enum declaration and usage, and very basic class definitions including fields and properties. Thanks!</p>
<pre><code>using System;
using System.IO;
using System.Collections.Generic;
namespace Product_Inventory_Using_Classes
{
enum ProgramState { MainMenu, AddProduct, RemoveProduct, DisplayProducts, Exit }
internal class Input
{
public ProgramState GetKey(string prompt)
{
while (true)
{
int choice;
List<string> productCheck = WriteBuffer.ProductData;
Console.Write(prompt);
if (!int.TryParse(Console.ReadKey(true).KeyChar.ToString(), out choice))
{
Console.WriteLine("\nInvalid choice");
}
if (choice != 1 && choice != 2 && choice != 3 && choice != 4)
{
Console.WriteLine("\nInvalid choice");
}
else
{
if (choice == 1)
{
return ProgramState.AddProduct;
}
if (choice == 2)
{
if (productCheck == null || productCheck.Count == 0)
{
Console.Write("No products exist. Add products first. Press any key");
Console.ReadKey(true);
return ProgramState.MainMenu;
}
return ProgramState.RemoveProduct;
}
if (choice == 3)
{
return ProgramState.DisplayProducts;
}
if (choice == 4)
{
return ProgramState.Exit;
}
}
}
}
public string GetString(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
}
internal class Menu
{
public ProgramState CurrentState { get; private set; }
public Menu(ProgramState state)
{
CurrentState = state;
}
public void GetMenuState(ProgramState state)
{
CurrentState = state;
}
public ProgramState MainMenu()
{
Input choice = new Input();
Console.Clear();
Console.WriteLine("Main Menu\n\n" +
"[1] Add Product\n" +
"[2] Remove Product\n" +
"[3] Display Products\n" +
"[4] Exit\n");
CurrentState = choice.GetKey("Enter Choice> ");
return CurrentState;
}
public void AddProduct()
{
while (true)
{
WriteBuffer product = new WriteBuffer();
Console.Clear();
Console.WriteLine("Add Products\n");
if (WriteBuffer.ProductData != null && WriteBuffer.ProductData.Count != 0)
{
for (int i = 0; i < (WriteBuffer.ProductData.Count - 1); i += 2)
{
Console.WriteLine(WriteBuffer.ProductData[i]);
}
}
string itemToAdd = product.GetProductName();
if (itemToAdd != "")
{
product.GetProductPrice();
}
else
{
break;
}
}
}
public void RemoveProduct()
{
List<string> product = WriteBuffer.ProductData;
while (true)
{
Console.Clear();
Console.WriteLine("Remove Products\n");
for (int i = 0; i < (product.Count - 1); i += 2)
{
Console.WriteLine(product[i]);
}
if (WriteBuffer.ProductData.Count == 0)
{
break;
}
Input name = new Input();
string itemRemoved = name.GetString("\nEnter item to be removed> ");
if (itemRemoved != "")
{
int itemLoc = WriteBuffer.ProductData.IndexOf(itemRemoved);
WriteBuffer.ProductData.RemoveAt(itemLoc + 1);
WriteBuffer.ProductData.RemoveAt(itemLoc);
}
else
{
break;
}
}
}
public void DisplayProduct()
{
ConsoleOutput display = new ConsoleOutput();
display.DisplayProducts();
}
}
internal class WriteBuffer
{
public static List<string> ProductData { get; private set; } // the list is static so that it keeps the same data through all instances
static WriteBuffer() // the constructor is static so the list is only instantiated once
{
ProductData = new List<string>();
}
public string GetProductName()
{
Input name = new Input();
while (true)
{
string input = name.GetString("\nEnter Name> ");
if (input != "")
{
ProductData.Add(input);
return input;
}
return input;
}
}
public void GetProductPrice()
{
Input price = new Input();
while(true)
{
float validNum;
if (float.TryParse(price.GetString("Enter Price> "), out validNum))
{
ProductData.Add(validNum.ToString());
return;
}
Console.WriteLine("\nInvalid Data. Enter Price> ");
}
}
}
internal class FileIO
{
public static List<string> ProductList { get; private set; }
public List<string> ProductListDisplay { get; private set; }
public string ProductName { get; private set; }
public string ProductPrice { get; private set; }
public void WriteFile()
{
ProductList = WriteBuffer.ProductData;
using (StreamWriter productFile = new StreamWriter("Products.txt"))
{
WriteBuffer output = new WriteBuffer();
foreach (var product in ProductList)
{
productFile.WriteLine(product);
}
}
}
public void ReadFile()
{
try
{
using (StreamReader productFile = new StreamReader("Products.txt"))
{
ProductListDisplay = new List<string>();
while (true)
{
ProductName = productFile.ReadLine();
ProductPrice = productFile.ReadLine();
ProductListDisplay.Add(ProductName);
ProductListDisplay.Add(ProductPrice);
if (ProductName == null)
{
break;
}
}
}
}
catch (Exception)
{
StreamWriter productFile = new StreamWriter("Products.txt");
productFile.Close();
}
}
}
internal class ConsoleOutput
{
public void DisplayProducts()
{
FileIO product = new FileIO();
if (WriteBuffer.ProductData != null)
{
for (int i = 0; i < (WriteBuffer.ProductData.Count - 1); i += 2)
{
product.ReadFile();
Console.WriteLine("{0} [${1}]", product.ProductListDisplay[i], product.ProductListDisplay[i + 1]);
}
}
}
}
internal class Program
{
private static void Main()
{
Menu menu = new Menu(ProgramState.MainMenu);
while (true)
{
switch (menu.CurrentState)
{
case ProgramState.MainMenu:
menu.MainMenu();
break;
case ProgramState.AddProduct:
FileIO productAdd = new FileIO();
menu.AddProduct();
productAdd.WriteFile();
menu.GetMenuState(ProgramState.MainMenu);
break;
case ProgramState.RemoveProduct:
FileIO productRemoved = new FileIO();
menu.RemoveProduct();
productRemoved.WriteFile();
menu.GetMenuState(ProgramState.MainMenu);
break;
case ProgramState.DisplayProducts:
Console.Clear();
Console.WriteLine("Display Products\n");
menu.DisplayProduct();
Console.ReadKey(true);
menu.GetMenuState(ProgramState.MainMenu);
break;
case ProgramState.Exit:
return;
}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>That's a lot of code to look through :) I haven't analyzed all of it, but after looking at the first couple of classes, here are some ideas to get you started.</p>\n\n<p>In your <code>Input.GetKey</code> method, you have a bunch of <code>if</code> statements to check the value of the <code>choice</code> variable. It would be much cleaner and easier to read if you used a <code>switch</code> statement, like this:</p>\n\n<pre><code>switch (choice)\n{\n case 1:\n return ProgramState.AddProduct;\n case 2:\n if (productCheck == null || productCheck.Count == 0)\n {\n Console.Write(\"No products exist. Add products first. Press any key\");\n Console.ReadKey(true);\n return ProgramState.MainMenu;\n }\n return ProgramState.RemoveProduct;\n case 3:\n return ProgramState.DisplayProducts;\n case 4:\n return ProgramState.Exit;\n default:\n Console.WriteLine(\"\\nInvalid choice\");\n break;\n}\n</code></pre>\n\n<p>I do find it confusing, though, that the <code>Input.GetKey</code> method has logic in it that makes it very specific so it can only be used for the main menu. I would have expected all of the code for the main menu to be in one method. For instance:</p>\n\n<pre><code>public ProgramState MainMenu()\n{\n Console.Clear();\n Console.WriteLine(\"Main Menu\\n\\n\" +\n \"[1] Add Product\\n\" +\n \"[2] Remove Product\\n\" +\n \"[3] Display Products\\n\" +\n \"[4] Exit\\n\");\n while (true)\n {\n Console.Write(\"Enter Choice> \");\n int choice;\n if (!int.TryParse(Console.ReadKey(true).KeyChar.ToString(), out choice))\n {\n Console.WriteLine(\"\\nInvalid choice\");\n }\n else\n {\n switch (choice)\n {\n case 1:\n return ProgramState.AddProduct;\n case 2:\n if (productCheck == null || productCheck.Count == 0)\n {\n Console.Write(\"No products exist. Add products first. Press any key\");\n Console.ReadKey(true);\n CurrentState = ProgramState.MainMenu;\n }\n else\n {\n ProgramState.RemoveProduct;\n }\n break;\n case 3:\n CurrentState = ProgramState.DisplayProducts;\n break;\n case 4:\n CurrentState = ProgramState.Exit;\n break;\n default:\n Console.WriteLine(\"\\nInvalid choice\");\n break;\n }\n }\n }\n return CurrentState;\n}\n</code></pre>\n\n<p>And if you do remove that code from the <code>Input</code> class, it's kind of silly to even keep it around since it adds very little value over the <code>Console</code> class. The only valid reason I can think of to keep it would be if you want or need to abstract away the input method being used. For instance, if you want to be able to, down the road, change it from a console application to a web page or a WinForm application, then it would be easier to make that change if you had the <code>Input</code> class effectively wrapping the <code>Console</code> logic. However, if that's not important to you, as I suspect is the case, then you should probably just ditch the <code>Input</code> class entirely.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T13:50:50.343",
"Id": "36106",
"Score": "0",
"body": "I totally agree with you. I wish I could ditch the whole input method, only issue is, that is what they requested for the project at the end of the series. Specifically each one of these fields had to be handled seperately: Storing Data, Reading Data, Writing Data, Getting input from user and displaying product data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T13:59:19.930",
"Id": "36108",
"Score": "0",
"body": "If you do keep the `Input` class, then I would recommend keeping it very basic and reusable, and then make sure you are using it from everywhere. Nothing should use the `Console` class directly *except* for the `Input` class and the `Output` class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:00:40.737",
"Id": "36109",
"Score": "0",
"body": "Thanks for the advise. I will see what I can do to tidy things up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:02:30.663",
"Id": "36110",
"Score": "2",
"body": "For what it's worth, the typical way to layer your code would be to keep all input and output in \"UI\" or \"Presentation\" classes, all of the data-storage classes in \"Data Model\" or \"DTO\" classes, and all the reading and writing of the data in \"Data Access\" classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:04:05.100",
"Id": "36111",
"Score": "0",
"body": "Ahh, that makes sense. This is the kind of knowledge I need. Thanks! wish I could rep up your answer, lol. I'm too noob."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:07:56.980",
"Id": "36114",
"Score": "0",
"body": "Then the all-important layer that you are totally missing is the business layer. Right now you are kind of mixing up all those layers. For instance, the Input class mixes UI and business layer functionality. The `Menu` class does as well. The *(confusingly named)* `WriteBuffer` class appears to mix data model, UI, and business logic. `ConsoleOutput` seems to be just UI, which is good, and `FileIO` seems to be just data access, which is also good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:14:01.680",
"Id": "36115",
"Score": "0",
"body": "Yea I do see what you are saying about the WriteBuffer class. That title makes no sense for what it is doing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:14:20.647",
"Id": "36116",
"Score": "1",
"body": "For instance, I would expect one or more data model classes that simply store all the data about a product in memory, nothing more. Then I would expect a `ProductDataAccess` class that loads and saves products to file. Then a `ProductBusiness` class that works with the data access and data model classes to perform all of the logic. Then a `ProductUi` class that contains methods to display products as well as input products and uses the `ProductBusiness` class to do all the work. Then maybe a `MainMenuUi` that displays the main menu and uses the `ProductUi` to do each task."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:18:01.243",
"Id": "36117",
"Score": "0",
"body": "That's a good thorough breakdown of how this should be structured. Definitely gives me some thoughts on how to tackle the program again. I think I will start from scratch again just to understand all of the concepts you mention."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:23:53.390",
"Id": "36118",
"Score": "0",
"body": "Do you think it is possible to keep every method below 25 lines with only basic knowledge and not any of the powerful shorthand stuff?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:34:53.543",
"Id": "36119",
"Score": "0",
"body": "I do think keeping each method short is important and 25 lines is a good rule-of-thumb, but there are plenty of times where it's just not practical. For instance, if you have a main menu that contains 10 options, it wouldn't be possible to even have a switch statement for all ten options in less than 25 lines. Now, you may decide that at that point, it would be getting to the point where you may want to break out each menu option into its own class so the menu could be displayed and processed in a small loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:36:26.493",
"Id": "36120",
"Score": "0",
"body": "But there's a good chance that it would just be overkill and a longer method that is over 25 lines would actually be easier to read. So, while long methods are definitely a strong indicator that your logic should be broken apart, sometimes it just means that your logic really does just take that many lines and it doesn't make sense to break it apart. But yes, it's always *possible* to make all your methods less than 25 lines, even if it doesn't necessarily make sense to do so :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:42:11.553",
"Id": "36121",
"Score": "0",
"body": "For instance, in the `MainMenu` method in my example (which is over 25 lines), you could put the part that writes the menu itself into a separate `WriteMenu` method, then put the part that reads the input key and parses a separate `GetChoice` method. Then you could move the `switch` block into a `ProcessChoice` method, or something. I think, in this case, something like that make sense and would be simple to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:45:55.070",
"Id": "36123",
"Score": "0",
"body": "Excellent! I will give it a shot. Much appreciated!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:46:50.033",
"Id": "36126",
"Score": "0",
"body": "The thing that rubs me the wrong way, though, with doing that, is that in one method you are displaying what option 1 means. In another method, you are determining which key means option 1. And then in a third method you are performing the logic that is meant by option 1. Since all of those things are related to the same thing, it's nice to have them all in one place. If you needed to add a fifth option, you'd have to go to three different methods to add the logic. That's where having it all in one method is simpler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:50:49.760",
"Id": "36127",
"Score": "0",
"body": "Or, if it's worth the trouble, making a separate `MenuOption` class for each choice would probably be the cleanest way. Then each class could encapsulate all of the logic for each option. They would all need to inherit from a base abstract class, or they would all need to implement the same interface. For instance, each one would need to have a `Description` property and probably a `Choice` character property, then a `PerformAction` method of some sort that calls the appropriate business layer method for that menu choice. But, that is a bit more advanced."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T19:20:54.207",
"Id": "36168",
"Score": "1",
"body": "@StevenDoggart - When I implemented a menu like this, I declared a `Dictionary<char, Tuple<string,Action>>` to store the menu. The key was the character to select it, and the Tuple had the text to display and the function to call when that choice was selected. Entries looked like `{'Q', Tuple.Create(\"Quit Program\", QuitProgram)}` with `void QuitProgram()` being one function. That's about the limit of complexity I'd want to have before making it into a class, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T19:27:12.447",
"Id": "36169",
"Score": "0",
"body": "@Bobson good point. It would be useful to have it in a dictionary, anyway, so you could easily get the menu item by the typed character. It is a little less self-documenting that way and less flexible too, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T23:32:42.777",
"Id": "36187",
"Score": "0",
"body": "That does look convenient, but for the sake of trying to understand the basics, I am trying to conform to the standards they asked us to complete the project with."
}
],
"meta_data": {
"CommentCount": "19",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T13:38:43.067",
"Id": "23434",
"ParentId": "23428",
"Score": "5"
}
},
{
"body": "<h1>Good Abstraction makes methods shorter</h1>\n\n<p>I suspect this is the hidden \"Ah-Ha\" lesson.</p>\n\n<p>NOTE: <em>the code samples are for inspirational purposes only. It is not a comprehensive refactoring of the entire program.</em></p>\n\n<p>For example instead of <code>if(choice !=1 && choice !=2 ...)</code> do this <code>if(ValidChoice())</code>, that says what it does much better and <code>ValidChoice()</code> will be very short indeed.</p>\n\n<p><strong>Make enumeration for menu choices</strong></p>\n\n<pre><code>public enum choices {Add = 1, Remove, Display, Exit}\n</code></pre>\n\n<p>We'll use that in a minute.</p>\n\n<p><strong>Rename <code>GetString</code> to something like <code>GetUserInput</code></strong></p>\n\n<p><strong>Refactor <code>GetKey</code> so code reads \"abstractly appropriate\"</strong></p>\n\n<pre><code>public ProgramState GetKey(string prompt) {\n bool invalidChoice = true;\n\n while (invalidChoice){\n // all that \"noisy\" code goes into a method that says what it does\n choice = GetUserInput();\n invalidChoice = ValidChoice(choice); \n }\n\n // no ELSE needed. We fall through when we get a valid choice\n return ProcessUserSelection(choice);\n}\n\n\nprotected bool ValidChoice(Choices choice) {\n return (choice != Choices.Add && \n choice != Choices.Remove && \n choice != Choices.Display &&\n choice != Choices.Exit);\n}\n</code></pre>\n\n<p>More refactoring. I made each case a method call; perhaps overkill (except for choice 2) but code in this method - \"at this level of abstraction\" - will not change if, for example, you change how <code>AddProduct()</code> works.</p>\n\n<pre><code>protected ProgramState ProcessUserSelection(Choices choice) {\n ProgramState stateOfTheUnion; // default value is zero, by the way\n\n switch(choice) {\n case Choices.Add :\n stateOfTheUnion = AddProduct();\n break;\n\n case Choices.Remove:\n stateOfTheUnion = RemoveProduct();\n break;\n\n case Choices.Display:\n stateOfTheUnion = DisplayProduct();\n break;\n\n case Choices.Exit:\n stateOfTheUnion = Exit();\n break;\n\n default:\n choice = Choices.Exit;\n // whatever\n }\n\n return stateOfTheUnion;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T07:54:39.560",
"Id": "36209",
"Score": "0",
"body": "This does not seem to work. Correct me if I am wrong here, but your `ValidChoice(Choices choice)` method declaration does not permit you to pass in an int or string for the comparison. This is due to ints and strings not being assignable to the `Choices` enum. So I am getting an error using your method because when I try to instantiate the `ValidChoices(choice)` method and assign it to `invalidChoice`, I get a compiler error that says you cannot assign an int to type `Choices`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T09:58:31.100",
"Id": "36215",
"Score": "0",
"body": "Also even though you say the default value is 0, there is a compiler error that requires you to initialize it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T18:37:41.993",
"Id": "36246",
"Score": "0",
"body": "From the code I illustrate, looks like `GetUserInput()` must convert the input to an enum. Converting is easy: [Cast int to enum](http://stackoverflow.com/questions/29482/cast-int-to-enum-in-c-sharp)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T02:01:29.357",
"Id": "36276",
"Score": "0",
"body": "That's exactly what I had done. Thanks! Love google."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T21:43:02.477",
"Id": "23464",
"ParentId": "23428",
"Score": "8"
}
},
{
"body": "<p>From a high level, I have to disagree with your class design and names - they're really modeled after your implementation (<code>Input</code>, <code>FileIO</code>, etc.) instead of your problem domain. I would've expected to see some classes such as <code>Product</code>, <code>Inventory</code>, etc.</p>\n\n<p>I won't attempt a straight refactoring - though there's isolated areas of code that could be improved on, the main thing that jumps out at me is the mix of concerns spread across all your classes. Currently, your classes all know way too much about <code>Console</code> and user input - you need to centralize that logic, and split into dedicated layers: UI, business, storage.</p>\n\n<p>Here's an attempt to walk through a design - which should hopefully give you enough to tweak the specifics to meet your needs. Any compile errors or bugs are intentional and intended for learning purposes. Just kidding - though I will take some shortcuts since MarkDown isn't the best IDE. </p>\n\n<p>Let's first extract out a <code>Product</code> class so we'll have something to work with:</p>\n\n<pre><code> public class Product {\n public string Name { get; set; }\n public decimal Price { get; set; }\n }\n</code></pre>\n\n<p>Now, we'll need something to keep track of the inventory levels. We could use a simple <code>List<Product></code> for this, but let's go ahead and abstract it out into an <code>Inventory</code> class, so that we'll have a place to put some convenience methods. Since we know we'll need to be able to remove an item by name (not caring about the price), we'll need some help to find that entry. We can also add some convenience methods around adding a product. </p>\n\n<pre><code> public class Inventory {\n private List<Product> Products { get; set; }\n\n public int Count { get { return this.Products.Count; } }\n\n public IEnumerable<Product> GetAllProducts() {\n return this.Products.AsReadOnly(); // don't want products added/removed directly\n }\n\n public void RemoveByName(string productName) {\n var p = this.FindByName(productName);\n if (p != null) this.Products.Remove(p);\n }\n\n public void AddProduct(string productName, decimal productPrice) {\n this.Products.Add(new Product() { Name = productName, Price = productPrice });\n }\n\n public Product FindByName(string productName) {\n foreach (Product p in this.Products) {\n if (p.Name == productName) {\n return p;\n }\n }\n return null; // not found\n }\n }\n</code></pre>\n\n<p>Ok - that pretty much gives us our product management functionality. Now, on to UI. </p>\n\n<p>You've got the right idea here - console input/output should be handled generically, so let's expand on that idea and write a few generic helper classes. A good way to think through this is figuring out what portions of what you need to do are <em>specific</em> to your app, and what is a <em>generic</em> concern. You should try to split those as much as possible. These won't have anything to do with <code>Products</code>, so they'll be reusable in a different console app.</p>\n\n<pre><code> public class ConsoleInput {\n public string Ask(string prompt) {\n this.Tell(prompt);\n return Console.ReadLine();\n }\n\n public decimal AskDecimal(string prompt) {\n decimal d;\n string answer;\n do {\n answer = this.Ask(prompt);\n } while (!decimal.TryParse(answer, out d));\n return d;\n }\n\n public int AskInt(string prompt) {\n int i;\n string answer;\n do {\n answer = this.Ask(prompt);\n } while (!int.TryParse(answer, out i));\n return i;\n }\n\n public string Choose(string prompt, params string[] validChoices) {\n string answer;\n do {\n answer = this.Ask(prompt);\n } while (validChoices.IndexOf(answer) < 0);\n return answer;\n }\n\n public int Choose(string prompt, params int[] validChoices) {\n int answer;\n do {\n answer = this.AskInt(prompt);\n } while (validChoices.IndexOf(answer) < 0);\n return answer;\n }\n\n public string Tell(string message) {\n Console.Write(message);\n }\n }\n</code></pre>\n\n<p>Ok, now we have enough to get to refactoring the <code>Menu</code> class. Currently, your <code>Menu</code> class has too many responsibilities - it's showing the menu, tracking the current state, and adding/removing products. We're going to trim that down to just showing the menu and tracking the current state:</p>\n\n<pre><code> public class Menu {\n public ProgramState CurrentState { get; private set; }\n\n public void MainMenu() {\n ConsoleInput input = new ConsoleInput();\n\n this.CurrentState = (ProgramState)input.Choose(\n \"Main Menu\\n\\n\" +\n \"[1] Add Product\\n\" +\n \"[2] Remove Product\\n\" +\n \"[3] Display Products\\n\" +\n \"[4] Exit\\n\",\n 1, 2, 3, 4\n );\n }\n }\n</code></pre>\n\n<p>Ok - now we've got most of the pieces, we just need to put the actual program logic together. Let's move on to the <code>Main</code> method:</p>\n\n<pre><code> public class Program {\n public static void Main(string[] args) {\n Inventory inventory = new Inventory();\n ConsoleInput input = new ConsoleInput();\n Menu menu = new Menu();\n\n switch (menu.CurrentState) {\n case ProgramState.MainMenu:\n menu.MainMenu();\n break;\n case ProgramState.AddProduct:\n inventory.AddProduct(\n input.Ask(\"Product Name?\"),\n input.AskDecimal(\"Product Price?\")\n );\n menu.MainMenu();\n break;\n case ProgramState.RemoveProduct:\n if (inventory.Count == 0) {\n input.Tell(\"No products exist. Add products first!\");\n } else {\n inventory.RemoveProduct(\n input.Ask(\"Product Name?\")\n );\n }\n menu.MainMenu();\n break;\n case ProgramState.DisplayProducts:\n foreach (Product p in inventory.GetAllProducts()) {\n input.Tell(\"{0} {1:c2}\\n\", p.Name, p.Price);\n }\n menu.MainMenu();\n break;\n case ProgramState.Exit:\n return 0;\n }\n }\n }\n</code></pre>\n\n<p>For file IO, the way you're currently doing it (saving after each add/remove) you could add it as part of <code>Inventory</code>:</p>\n\n<pre><code> public class Inventory {\n private string FileName { get; set; }\n\n public Inventory(string fileName) {\n this.FileName = fileName;\n this.Products = this.ReadProducts();\n }\n\n public void AddProduct(...) {\n ...\n this.SaveProducts();\n }\n\n private void SaveProducts()\n using (StreamWriter ...) {\n }\n }\n\n private List<Product> ReadProducts() {\n using (StreamReader ...) {\n }\n }\n</code></pre>\n\n<p>If you're familiar with inheritance, hopefully you can see how you could add that functionality into a 'PersistentInventory' subclass.</p>\n\n<p>Hopefully, you can see by splitting the functionality out cohesively both readability and maintainability. Think through adding the following functionality in v2 of your app with the various designs:</p>\n\n<ul>\n<li>Configurable filenames for storage</li>\n<li>Multiple inventory locations (eg., store/warehouse)</li>\n<li>Keeping track of quantity levels as products are added/removed</li>\n<li>Sending an alert (eg., via email) when quantity reaches 0 for an item</li>\n<li>Making a web page interface</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T15:51:49.650",
"Id": "27700",
"ParentId": "23428",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23434",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T13:01:52.593",
"Id": "23428",
"Score": "5",
"Tags": [
"c#"
],
"Title": "C# product inventory. How would you refactor this?"
}
|
23428
|
<p>So I am essentially a complete newbie to programming, and have been attempting to learn Python by completing the Project Euler problems. I haven't gotten very far, and this is my code for <a href="http://projecteuler.net/problem=3" rel="nofollow">problem #3</a> :</p>
<blockquote>
<p>The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?</p>
</blockquote>
<p>Although my solution works, I'd like to know how I can improve.</p>
<pre><code>primes = [2]
factors = []
def isPrime(x):
a = 1
if x == 1:
return False
while a < x:
a += 1
if x % a == 0 and a != x and a != 1:
return False
break
return True
def generatePrime():
a = primes[-1]+1
while isPrime(a) == False:
a += 1
primes.append(a)
def primeFactor(x):
a = primes[-1]
while a <= x:
if x % a == 0:
factors.append(a)
x /= a
generatePrime()
a = primes[-1]
primeFactor(input("Enter the number: "))
print("The prime factors are: " + str(factors) + "\nThe largest prime factor is: " + str(sorted(factors)[-1]))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:06:48.310",
"Id": "36112",
"Score": "0",
"body": "You should replace `while a < x:` with `while a < math.sqrt(x):` You can also check whether x is even and > 2, in that case it is not a prime, also google for 'prime sieve'."
}
] |
[
{
"body": "<p>You can save quite a bit time on your prime generation. What you should keep in mind is that a prime is a number which is no multiple of a prime itself; all other numbers are.</p>\n\n<p>So in your <code>isPrime</code> function you can just go through your primes list and check if each prime is a divisor of the number. If not, then it is a prime itself. Of course you would need to make sure that you fill your primes list enough first.</p>\n\n<p>As the most basic idea, you only need to check until <code>sqrt(n)</code>, so you only generate numbers this far. And you can also just skip every even number directly. You could also make similar assumptions for numbers dividable by 3 etc., but the even/uneven is the simplest one and enough to get fast results for not too big numbers.</p>\n\n<p>So a prime generation algorithm, for possible prime divisors up to <code>n</code>, could look like this:</p>\n\n<pre><code>primes = [2]\nfor i in range(3, int(math.sqrt(n)), 2):\n isPrime = not any(i % p == 0 for p in primes)\n if isPrime:\n primes.append(i)\n</code></pre>\n\n<p>Then to get the prime factors of <code>n</code>, you just need to check those computed primes:</p>\n\n<pre><code>primeFactors = []\nm = n\nfor p in primes:\n while m % p == 0:\n m = m / p\n primeFactors.append(p)\n if m == 0:\n break\n\nprint('The prime factorization of `{0}` is: {1}'.format(n, '×'.join(map(str,primeFactors))))\n</code></pre>\n\n<p>For the euler problem 3 with <code>n = 317584931803</code>, this would produce the following output:</p>\n\n<blockquote>\n <p>The prime factorization of <code>317584931803</code> is: 67×829×1459×3919</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T18:42:02.080",
"Id": "36164",
"Score": "0",
"body": "If you are not going to sieve to calculate your primes, you should at least bring together your prime calculation and factor testing together, so that as soon as you find the `67` factor, your largest prime to calculate is reduced from `563546` to `68848`, and by the time you know `829` is a prime to `2391`, and once `1459` is known as a prime you don't calculate any more primes to test as factors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T19:19:03.887",
"Id": "36167",
"Score": "0",
"body": "@Jaime Sure, you can again save a lot when combining those two. My original solution for problem 3 (which btw. doesn’t even require factorization) is a lot more concise too. But given OP’s original code structure I thought it would make more sense to show separated and reusable pieces. With my example I could once generate the primes and then just run the factorization against multiple numbers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T16:58:58.283",
"Id": "23447",
"ParentId": "23429",
"Score": "5"
}
},
{
"body": "<p>My code takes 2 milliseconds to execute from tip to tail ...</p>\n\n<pre><code># 600851475143\n\nimport math\n\nimport time\n\nnumber = int(input(\"> \"))\n\nstart_time = time.time()\n\n\ndef prime_factors(number):\n\n prime_factorization = []\n\n box = number\n\n while number > 1:\n for i in range(math.floor(math.log2(number))):\n for j in range(2, number + 1):\n if number % j == 0:\n prime_factorization.append(j)\n number = number//j\n last_factor = j\n if last_factor > math.sqrt(box):\n return prime_factorization\n break\n return prime_factorization\n\n\nprint(f\"Prime factors = {prime_factors(number)}\")\n\nprint(f\"execution time = {time.time() - start_time} seconds\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-14T07:50:22.943",
"Id": "475391",
"Score": "2",
"body": "Hey, welcome to Code Review! Please add some more explanation on *how* and *why* your code is better (faster). Otherwise this is just an alternative solution, which alone is not enough for an answer here. Have a look at our [help-center](https://codereview.stackexchange.com/help/how-to-answer) for more information."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-14T06:32:46.730",
"Id": "242243",
"ParentId": "23429",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T13:17:46.433",
"Id": "23429",
"Score": "8",
"Tags": [
"python",
"project-euler",
"primes"
],
"Title": "Project Euler #3 - how inefficient is my code?"
}
|
23429
|
<p>Can anyone help me speed up this query? At present, it returns 1200 rows in 5 secs. I've notice that it is looking at 240000 response records. I think this is where the issue may be.</p>
<p>I've created the following indexes:</p>
<pre><code>CREATE INDEX idx_eventid ON `action` (eventid);
CREATE INDEX idx_actionid ON `response` (actionid);
CREATE INDEX idx_date ON `response` (`date`);
CREATE INDEX idx_stockid ON `eventstocklink` (stockid);
CREATE INDEX idx_eventid ON `eventstocklink` (eventid);
CREATE INDEX idx_cusid ON `event` (cusid);
</code></pre>
<p><code>SELECT</code> statement:</p>
<pre><code>SELECT
response2.actionid,
response2.typeid,
response2.notes,
response2.eventid,
response2.actiondate,
response2.userid,
response2.eventtype,
response2.firstname,
response2.surname,
response2.postcode,
response2.eventtypeid,
response2.dealtrue,
response2.dealid,
response2.eventpic,
response2.registrationnumber,
response2.deptlinkid,
response2.customtype,
response2.enquiryid,
response2.eventstocklinkid,
response2.cusid,
response2.stockid,
response2.custitle,
response2.actiontypeid,
response2.deptbut,
response2.cushomtel,
response2.cusworktel,
response2.cusmobtel,
response2.cusadd1,
response2.cusadd2,
response2.cusadd3,
response2.cuscounty,
response2.cushomemail,
response2.cusworkemail,
response2.responsetype,
response2.date,
response2.done,
response2.responsebut,
response2.reasonid,
response2.responseid,
response2.depttype,
response2.responsetypeid,
response2.username,
response2.actionusername,
diarytime.diarytime,
response2.prospectmake,
response2.prospectmod,
response2.prospectnu,
response2.statedesc,
response2.site
FROM
diarytime
LEFT JOIN
(SELECT
action.actionid,
action.typeid,
response.notes,
action.eventid,
action.actiondate,
response.userid,
eventtype.event AS eventtype,
cus.firstname,
cus.surname,
cus.postcode,
event.typeid AS eventtypeid,
IF(ISNULL(deal.dealid), 0, 1) AS dealtrue,
IF(ISNULL(deal.dealid), 0, deal.dealid) AS dealid,
eventtype.eventpic,
IF(
ISNULL(stock.registrationnumber),
0,
stock.registrationnumber
) AS registrationnumber,
event.deptlinkid,
action.customtype,
prospect.enquiryid AS enquiryid,
action.eventstocklinkid,
event.cusid,
eventstocklink.stockid,
cus.custitle,
action.actiontypeid,
dept.deptbut,
cus.cushomtel,
cus.cusworktel,
cus.cusmobtel,
cus.cusadd1,
cus.cusadd2,
cus.cusadd3,
cus.cuscounty,
cus.cushomemail,
cus.cusworkemail,
responsetype.responsetype,
response.date,
response.done,
responsetype.responsebut,
response.reasonid,
response.responseid,
dept.depttype,
response.typeid AS responsetypeid,
response.username,
response.username AS actionusername,
prospect.stockmake AS prospectmake,
prospect.stockmod AS prospectmod,
prospect.otdbtype AS prospectnu,
stockstate.statedesc,
site.site
FROM
response
INNER JOIN users_eden.users AS users
ON users.userid = response.userid
INNER JOIN ACTION
ON response.actionid = action.actionid
LEFT JOIN responsetype
ON responsetype.responsetypeid = response.typeid
LEFT JOIN EVENT
ON event.eventid = action.eventid
LEFT JOIN eventtype
ON eventtype.eventid = event.typeid
LEFT JOIN cus
ON cus.cusid = event.cusid
LEFT JOIN deal
ON deal.dealid = action.dealid
LEFT JOIN enquiries AS prospect
ON prospect.actionid = action.actionid
LEFT JOIN deptlink
ON deptlink.deptlinkid = event.deptlinkid
LEFT JOIN dept
ON dept.deptid = deptlink.deptid
LEFT JOIN site
ON site.siteid = deptlink.siteid
LEFT JOIN eventstocklink
ON eventstocklink.eventstocklinkid = action.eventstocklinkid
LEFT JOIN stock
ON stock.stockid = eventstocklink.stockid
LEFT JOIN stockstate
ON stockstate.stateid = eventstocklink.statusid
WHERE UCASE(response.reasonid) <> 'FIRST'
AND UCASE(response.reasonid) <> 'CANCELLED'
AND UCASE(response.reasonid) <> 'WEBSITE'
AND DATE(response.date) = '20130228'
ORDER BY DATE(response.date) ASC,
TIME(response.date) ASC) AS response2
ON HOUR(response2.date) = HOUR(diarytime.diarytime)
</code></pre>
<p>Results of explain:</p>
<pre><code>id select_ty table type poss_keys key key_len ref rows Extra
1 PRIMARY diarytime index idx_diarytime 4 24 Using index
1 PRIMARY <derived2> ALL 1119
2 DERIVED response ALL idx_actionid 240542 Using filesort
2 DERIVED action eq_ref PRIMARY PRIMARY 4 response.actionid 1
2 DERIVED users eq_ref PRIMARY PRIMARY 4 response.userid 1 Using index
2 DERIVED responsetype eq_ref PRIMARY PRIMARY 4 response.typeid 1
2 DERIVED event eq_ref PRIMARY PRIMARY 4 action.eventid 1
2 DERIVED eventtype eq_ref PRIMARY PRIMARY 4 event.typeid 1
2 DERIVED cus eq_ref PRIMARY PRIMARY 8 event.cusid 1
2 DERIVED deal eq_ref PRIMARY PRIMARY 4 action.dealid 1 Using index
2 DERIVED prospect ref idx_actionididx_actionid 5 action.actionid 1
2 DERIVED deptlink eq_ref PRIMARY PRIMARY 4 event.deptlinkid 1
2 DERIVED dept eq_ref PRIMARY PRIMARY 4 deptlink.deptid 1
2 DERIVED site eq_ref PRIMARY PRIMARY 4 deptlink.siteid 1
2 DERIVED eventstocklink eq_ref PRIMARY PRIMARY 4 action.eventstocklinkid 1
2 DERIVED stock eq_ref PRIMARY PRIMARY 8 eventstocklink.stockid 1
2 DERIVED stockstate eq_ref PRIMARY PRIMARY 4 eventstocklink.statusid 1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T09:21:21.353",
"Id": "36097",
"Score": "0",
"body": "The index on response.date cannot be used because you are using a function on the column."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T12:40:32.080",
"Id": "36098",
"Score": "0",
"body": "sorted - got it down 1 sec - had to create separate columns for date and hour and remove all functions on date fields"
}
] |
[
{
"body": "<p>In your Select statement you are doing this</p>\n\n<pre><code>WHERE UCASE(response.reasonid) <> 'FIRST' \n AND UCASE(response.reasonid) <> 'CANCELLED' \n AND UCASE(response.reasonid) <> 'WEBSITE' \n AND DATE(response.date) = '20130228' \n</code></pre>\n\n<p>Which is about the same as doing this</p>\n\n<pre><code>WHERE UCASE(response.reasonid) NOT IN ('FIRST','CANCELLED','WEBSITE')\n AND DATE(response.date)='20130228'\n</code></pre>\n\n<p>Both of which are slower because of the use of the <code>Not Equals</code> function in the query. But using the <code>IN</code> statement makes the code a little less redundant looking.</p>\n\n<p>If you could change this query to use the <code>Equals</code> function in the where statement instead, this query would run much faster.</p>\n\n<p>For References on why this is please see <a href=\"https://codereview.stackexchange.com/a/33461/18427\">my answer</a> to a similar question.</p>\n\n<p><strong>Relevant links from answer</strong></p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/7419299/1214743\">answer to SQL Server “<>” operator is very slow compared to “=” on table with a few million rows</a></li>\n</ul>\n\n<p>I also think that if you use a temp table instead of nested select statements you could speed this up as well, because you could add Primary keys and indexes to the temp table helping the engine to sort the results faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T16:50:25.640",
"Id": "35232",
"ParentId": "23430",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T09:10:12.313",
"Id": "23430",
"Score": "4",
"Tags": [
"optimization",
"performance",
"mysql",
"sql"
],
"Title": "Slow MySQL query - 1200 rows in 5secs"
}
|
23430
|
<p>I am studying about how to use an interface for decoupling, and I wrote a program. Does it actually implemented decoupling? Are there any possible modifications to make it better?</p>
<pre><code>public partial class MainPage
{
// Constructor
public MainPage()
{
InitializeComponent();
IDBInterface idbInterface = new SQL();
CommunicationChannel com = new CommunicationChannel();
com.Update(idbInterface);
}
}
interface IDBInterface
{
void Update();
}
class SQL:IDBInterface
{
public void Update()
{
MessageBox.Show("Please wait.. We are updating SQL Server...");
}
}
class Oracle : IDBInterface
{
public void Update()
{
MessageBox.Show("Please wait.. We are updating Oracle Server...");
}
}
class CommunicationChannel
{
public void Update(IDBInterface idb)
{
idb.Update();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T09:59:31.913",
"Id": "36102",
"Score": "2",
"body": "Still you can decopule your actual code MainPage class by delegating some other type to create the concrete objects. For which you can refer to Inversion of Control and Creational design patters. The problem now is if dependency objects creation fails, then Mainpage object creation also fails. NO Dependency Injection"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T10:07:08.220",
"Id": "36103",
"Score": "2",
"body": "on a different note, its better to get rid of `IDBInterface`. Make it `IDb` or even better `DbInterface`.."
}
] |
[
{
"body": "<p>Yes that's it, that is decoupled.</p>\n\n<p>However, the benefits of this are not visible in your example because the look of SQL and IDBInteraface are the same.</p>\n\n<p>It would become obvious if your example was of that kind:</p>\n\n<pre><code>interface IDBInterface\n{\n void Update(string sqlQuery);\n void Insert(string sqlQuery);\n void Select(string sqlQuery);\n}\n\nclass SQL:IDBInterface\n{\n public void Update(string sqlQuery){/*implementation*/};\n public void Insert(string sqlQuery){/*implementation*/};\n public void Select(string sqlQuery){/*implementation*/};\n\n public void connect(){/*implementation*/};\n public void disconnect(){/*implementation*/};\n public void optimize(){/*implementation*/};;\n public void backup(){/*implementation*/};;\n}\n</code></pre>\n\n<p>In such cases, when using the <code>IDBInterface</code>, you would not even mind about all the administrative work to be done ( connect, disconnect, optimize, backup).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T10:05:45.407",
"Id": "23436",
"ParentId": "23435",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23436",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T09:56:25.837",
"Id": "23435",
"Score": "8",
"Tags": [
"c#",
"interface"
],
"Title": "Using an interface for decoupling"
}
|
23435
|
<p>I have tried to build my first MVC sign up form.</p>
<p>Here is the user controller method <code>register</code>:</p>
<pre><code>public function register() {
if($this->isPost()) {
$user = new UserModel();
$result = $user->add($_POST);
if(!$result) {
$this->redirect('user/register');
} elseif(is_array($result)) {
$this->view->set('errors', $result);
$this->view->addTemplate('header', 'header', array('title' => 'Error', 'bodyClass' => 'registerError'));
$this->view->render('user/registerError');
} else {
$this->view->set('firstName', $_POST['firstName']);
$this->view->addTemplate('header', 'header', array('title' => 'Thank you ' . $_POST['firstName'], 'bodyClass' => 'registerTrue'));
$this->view->addTemplate('footer', 'footer');
$this->view->render('user/registerTrue');
}
} else {
$this->view->addTemplate('header', 'header', array('title' => 'Register', 'bodyClass' => 'userRegister'));
$this->view->addTemplate('footer', 'footer');
$this->view->render('user/register');
}
}
</code></pre>
<p>Here is my user model method <code>add</code>:</p>
<pre><code>public function add($data) {
$errors = array();
if(!FormValLib::checkNotEmpty($data)) {
// return false;
}
if(!FormValLib::checkEmail($data['email'])) {
$errors[] = 'The email you provided is not valid';
}
if(!FormValLib::compare($data['email'], $data['confirmEmail'])) {
$errors[] = 'Your emails do not match';
}
if(!FormValLib::checkMinLength($data['password'], 6)) {
$errors[] = 'Your password must be at least 6 characters long';
}
if(!FormValLib::compare($data['password'], $data['confirmPassword'])) {
$errors[] = 'Your passwords do not match';
}
if($errors) {
return $errors;
} else {
$q = $this->db->prepare('INSERT INTO users (name, email, password) VALUES (?, ?, ?)');
$q->execute(array($data['firstName'] . ' ' . $data['secondName'], $data['email'], hash('sha512', $data['password'])));
return true;
}
}
</code></pre>
<p><code>FormValLib</code> is just a very simple form validation class. I am not so bothered about coding standards just the design pattern in general!</p>
|
[] |
[
{
"body": "<p>I'm not a PHP expert but:</p>\n\n<p>The <code>Register</code> method is too long. Extract each branch of the top-level conditional into separate methods.</p>\n\n<p>The line <code>$this->view->addTemplate('header'...</code> is too long. Assign the array to an intermediate variable first.</p>\n\n<p>Assign <code>$this->view</code> to something so you can reference it with a shorter name.</p>\n\n<p><code>registerTrue</code> seems like a poor name, how about <code>registrationSuccess</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T17:10:47.057",
"Id": "36160",
"Score": "0",
"body": "Thanks for your input, but otherwise than that the general architecture and pattern is ok? I still am working on my view class which is why the `addTemplate` and `render` methods are a bit sketchy"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T16:01:14.220",
"Id": "23443",
"ParentId": "23437",
"Score": "1"
}
},
{
"body": "<p><code>add</code> is doing both validation and insertion. It'd probably be better if the two tasks were separated. That'd make it possible to validate something without trying to add to the DB just yet. :P</p>\n\n<p>I personally am a bit leery of returning an array of errors from <code>add</code>...partly because you're using <code>true</code> to indicate success, and <code>$this->add($data)</code> would be truthy even if there were errors. In a public method, IMO, that is a recipe for confusion. I'd prefer to see a result type more explicitly indicating success or error.</p>\n\n<p>You might want to store the errors elsewhere (maybe as a property of the object, considering they're a direct result of its state) rather than returning them. Or, don't even store them -- if you separate validation and insertion, that list of errors can be recreated at will. Either way, you can then simply return a boolean indicating whether the insert succeeded. If false, then the caller can get those errors if it cares why the add failed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T20:18:26.733",
"Id": "36173",
"Score": "0",
"body": "Thanks this has helped, I thought returning an array of errors in the model was a bit dodgy. I think I will improve upon it by doing what you said in your post, maybe make a method validate user and add user. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T19:45:54.520",
"Id": "23455",
"ParentId": "23437",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23455",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:25:47.183",
"Id": "23437",
"Score": "1",
"Tags": [
"php",
"design-patterns",
"mvc",
"form"
],
"Title": "Simple sign up form"
}
|
23437
|
<p>I have a few hundred files in a directory that I need to read in parallel. Namely, the files that have the same name, but different file extensions (.a and .b), but they're pretty much plain text files. The corresponding .a and .b files have the same number of lines. I need to read each line into cell arrays x and y until all each pair of files in the directory have been read. Currently, I'm doing it with a nested loop which works fine, but just takes too long. Is there any way to do this faster?</p>
<pre><code>x = {};
y = {};
dir1 = dir( [ directory, filesep, '*', 'a'] );
dir2 = dir( [ directory, filesep, '*', 'b'] );
i = 1;
for i=1:length(dir1)
fid1 = fopen([directory, filesep, dir1(i).name]);
fid2 = fopen([directory, filesep, dir2(i).name]);
sentence1 = fgetl(fid1);
sentence2 = fgetl(fid2);
while ischar(sentence)
x{i} = sentence1;
y{i} = sentence2;
i = i+1;
sentence1 = fgetl(fid1);
sentence2 = fgetl(fid2);
end
fclose(fid1);
fclose(fid2);
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T10:15:21.113",
"Id": "36124",
"Score": "0",
"body": "Are you sure that it's the reading of the files which takes too long? I see that you're not preallocating memory for the cell arrays `x` and `y`... this may also be a reason for a slowdown."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T11:42:35.047",
"Id": "36125",
"Score": "0",
"body": "I think you can get rid of the parallel. Then you could read one file in one go. Suppose reading from hard disk should be much faster without this searching back and forward."
}
] |
[
{
"body": "<p>Performing this in parallel using <code>PARFOR</code> should be straightforward if you have the Parallel Computing Toolbox installed. Whether it goes any faster or not depends entirely on the size of your data, the speed of your disks etc. Here's how I would approach it:</p>\n\n<pre><code>function [x, y] = readOnePairOfFiles(name1, name2)\n x = {}; y = {};\n fid1 = fopen(name1); fid2 = fopen(name2);\n %# Read from fid1 and fid2, build up x and y\nend\n\n% Use PARFOR to invoke readOnePairOfFiles\nx = {}; y = {};\nparfor ii = 1:length(dir)\n name1 = fullfile(directory, dir1(ii).name);\n name2 = fullfile(directory, dir2(ii).name);\n [thisX, thisY] = readOnePairOfFiles(name1, name2);\n x = [x, thisX]; %# concatenation reduction to get x and y\n y = [y, thisY];\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T08:29:00.843",
"Id": "23470",
"ParentId": "23438",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T09:44:32.053",
"Id": "23438",
"Score": "1",
"Tags": [
"matlab"
],
"Title": "Matlab - Fastest way to parallel read many files line by line?"
}
|
23438
|
<p>I have this function containing some loops and a double for loop. What it does is set up a matrix first to store results in (the task at hand is comparing genomes) and then with sliding window, calculate the differences between sequences. It's very slow for very long sequences, I was hoping somebody know how to speed this up, the part causing the bottleneck is:</p>
<pre><code>n1 <- 0
for(i in seq(windowp1)) {
n1 <- n1+1
n2 <- 0
setTxtProgressBar(prog, n1)
for(i in seq(1:ncol(Distances))) {
n2 <- n2+1
Distances[n1,n2] <- sum(x[pairs[n2,1],c(windowp1[n1]:windowp2[n1])] != x[pairs[n2,2],c(windowp1[n1]:windowp2[n1])])
}
Distances2 <- (Distances/winsize)*100
}
</code></pre>
<p>Where windowp1 is a vector of numbers defining the start of each window. Distances is the pre-made matrix for the results, it has as many cols as there are pairwise comparisons of sequences and as many row's as there are sliding window frames, determined by windowp1 and windowp2. The differences between the sequences are calculated simply by the hamming distance. The loop 1 ticks up the window, the second loop then ticks over to do all comparisons between sequences to do in the window, then the first loop ticks to select the next window. The final line makes the hamming distances in the matrix a % of the widowsize.</p>
|
[] |
[
{
"body": "<p>Can't see exactly what's going with the sliding windows but it looks like you're calculating the full distance matrix: (i,j) and (j,i). If so, you probably only need half (usually lower) but you can make both with <code>Distances[n1,n2] <- Distances[n2,n1] <- sum ...</code> If this is correct, you'll basically double your speed.</p>\n\n<p>But, if I misunderstood the above, you could still win a little time by reducing the number of index lookup, since these are really slow in R. In particular <code>c(windowp1[n1]:windowp2[n1])</code> could be pulled out of the loop. Depending on what \"x\" looks like, you might try \"xor(a, b)\" rather than \"a != b\".</p>\n\n<p>Adding a few other changes (eg, drop n1,n2 in favor of the loop variables) but leaving the possible \"full matrix\" thing I mentioned, here's a suggestion:</p>\n\n<pre><code>distances.ncol <- ncol(Distances)\nfor(i in seq_along(windowp1)) {\n wp12 <- c(windowp1[i]:windowp2[i])\n setTxtProgressBar(prog, i)\n\n for(j in seq_len(distances.ncol)) {\n Distances[i,j] <-\n sum(x[pairs[j,1],wp12] != x[pairs[j,2],wp12])\n }\n Distances2 <- (Distances/winsize)*100\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T21:27:29.400",
"Id": "23552",
"ParentId": "23440",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:21:15.030",
"Id": "23440",
"Score": "3",
"Tags": [
"optimization",
"r"
],
"Title": "Vectorize or otherwise speed up a double for loop"
}
|
23440
|
<p>This is a simple repeatable question regarding the usage of Python3's comprehensions:</p>
<p><strong>Could the Python3 syntax be used in another way to speed up the process, further so the gap between Python3 and numpy would be reduced?</strong> (see chart below).</p>
<p>The results & code:
<img src="https://i.stack.imgur.com/CRHrV.png" alt="Runtime test of Python3's list comprehension, dict comprehension, python for loop and numpy">
Above: Runtime test of Python3's list comprehension, dict comprehension, python for loop and numpy
<img src="https://i.stack.imgur.com/Ilt4i.png" alt="Runtime test without power-functions including Janne Karila suggestion to break down the power function to x * x * x">
<strong>Update 1</strong> Above: Runtime test without power-functions including Janne Karila suggestion to break down the power function to x * x * x
<img src="https://i.stack.imgur.com/mh1Dz.png" alt="Runtime test without powerfunctions and with Justin Peels recommendation to use return list(a.values())">
<strong>Update2</strong> Above: Runtime test without powerfunctions and with Justin Peels recommendation to use return list(a.values())</p>
<pre><code>#/usr/bin/python3 -
import sys
from datetime import datetime
import numpy
import matplotlib.pyplot as pyplot
def doingnothing(n):
for i in range(n):
pass
return []
def numpysum(n): #NPY
a = numpy.arange(n) ** 2.
b = numpy.arange(n) ** 3.
c = a + b
return c
def listexpression(n): #LE
#return [x**2+x**3 for x in range(n)]
return [x*x+x*x*x for x in range(n)]
def dictcomprehension(n): #DC
# a = {x:x**2+x**3 for x in range(n)}
a = {x:x*x+x*x*x for x in range(n)}
# return [a[key] for key in a]
return list(a.values())
def pythonsum(n): #PS
a = list(range(n))
b = list(range(n))
c = []
for i in range(len(a)):
# a[i] = i ** 2.
a[i] = i * i
# b[i] = i ** 3.
b[i] = i * i * i
c.append(a[i] + b[i])
return c
def runtimetest(size,verbose=True):
v = verbose
d = {'DoingNothing':None,
'NPY':None,
'LE':None,
'DC':None,
'PS':None}
start = datetime.now()
c = doingnothing(size)
d['DoingNothing'] = datetime.now() - start
start = datetime.now()
c = numpysum(size)
d['NPY'] = datetime.now() - start
start = datetime.now()
c = listexpression(size)
d['LE'] = datetime.now() - start
start = datetime.now()
c = dictcomprehension(size)
d['DC'] = datetime.now() - start
start = datetime.now()
c = pythonsum(size)
d['PS'] = datetime.now() - start
if v:
for key in sorted(d):
print(key, "took", round(d[key].seconds + d[key].microseconds/10**6,6), " sec.")
else:
return d
def view(results):
"""
result['header']=['DoingNothing','NPY','LE','DC','PS']
result[3000]=[0.0, 0.0, 0.002, 0.003, 0.003001]
"""
if 'header' in results.keys():
results.pop('header')
steps,DN,NPY,LE,DC,PS=[],[],[],[],[],[] #I love multiple assignment!
for step in sorted(results):
steps.append(step)
DN.append(results[step][0])
NPY.append(results[step][4])
LE.append(results[step][5])
DC.append(results[step][6])
PS.append(results[step][4])
pyplot.plot(steps,DN)
pyplot.plot(steps,NPY)
pyplot.plot(steps,LE)
pyplot.plot(steps,DC)
pyplot.plot(steps,PS)
pyplot.legend(['Empty Loop', 'Numpy.Arange', 'List Comprehension', 'Dict Comprehension', 'Python for Loop'], loc='upper left')
scale = 'linear'
pyplot.xscale(scale)
pyplot.yscale(scale)
pyplot.title('runtime test')
pyplot.xlabel('length of list')
pyplot.ylabel('runtime in seconds')
pyplot.show()
def longruntimetest(length):
if length<10**4:
length=10**4
result = {}
result['header']=['DoingNothing','NPY','LE','DC','PS']
for step in range(10**3, length+1,10**3):
t=runtimetest(step,verbose=False)
result[step]=[t['DoingNothing'],t['NPY'],t['LE'],t['DC'],t['PS']]
for i in range(len(result[step])):
result[step][i]=round(result[step][i].seconds
+result[step][i].microseconds/10**6,6)
view(result)
def main():
if sys.version_info <= (3, 2):
sys.stdout.write("Sorry, requires Python 3.2.x, not Python 2.x\n")
sys.exit(1)
testsize=10**5
runtimetest(testsize)
longruntimetest(testsize)
if __name__=='__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:18:57.917",
"Id": "36131",
"Score": "0",
"body": "Similar, though not the same:\nhttp://stackoverflow.com/questions/9708783/numpy-vs-list-comprehension-which-is-faster?rq=1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:06:17.590",
"Id": "36132",
"Score": "0",
"body": "You might also be able to speed up the `numpysum` function by calling `arange` only once (for me a factor of about .75). `a = np.arange(n); c = a**2 + a**3` Still, @Janne's solution helps even more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:32:03.470",
"Id": "36140",
"Score": "0",
"body": "@askewchan, or even better, do `a = np.arange(n); b = a * a; c = b + b * a`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:32:54.047",
"Id": "36141",
"Score": "0",
"body": "in dictcomprehension, `return list(a.values())` is faster on my machine than the list comprehension you are using."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:34:02.143",
"Id": "36143",
"Score": "0",
"body": "Why is pythonsum so convoluted? shouldn't it just be `for i in range(n): a = i * i; b = a * i; c.append(a + b` or something similar to that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:56:41.147",
"Id": "36146",
"Score": "0",
"body": "@Justin, for i in range(n) is correct, it cuts off the overhead for the len-function. But because a is a list b = a * i wont work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T16:01:12.843",
"Id": "36148",
"Score": "0",
"body": "why are `a` and `b` lists in the first place in that function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T16:09:06.327",
"Id": "36151",
"Score": "0",
"body": "The run-time test is about creating a comparable scenario's for all 5 numerical operations and measure the runtime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T16:15:18.003",
"Id": "36153",
"Score": "0",
"body": "okay. I just don't see them all as exactly comparable I guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T16:19:31.200",
"Id": "36154",
"Score": "0",
"body": "...Comparable as \"producing the same result\" using similar methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T16:26:18.227",
"Id": "36156",
"Score": "0",
"body": "Exactly, a list comprehension is comparable to the method I described using a for loop... not to creating two extra lists `a` and `b`. Anyway, it doesn't really matter."
}
] |
[
{
"body": "<pre><code>def listexpression(n): #LE\n return [x * x * (1 + x) for x in range(n)]\n</code></pre>\n\n<p>is over 3 times faster than your version with <code>x**2+x**3</code> (from 8.47 ms to 2.31 ms with n = 10000).</p>\n\n<p>Though, NumPy will also benefit from regrouping the expression this way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:58:01.840",
"Id": "36133",
"Score": "0",
"body": "Is factoring like this generally beneficial? What's so inefficient about the power syntax?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:02:17.553",
"Id": "36134",
"Score": "1",
"body": "@askewchan, count the number of multiplies. x * x + x * x * x is 3 multiplies. x * x * (1 + x) is two multiplies and an addition. That doesn't account for the whole speed up but it is part of it. A multiply is generally much slower than an addition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:11:18.060",
"Id": "36135",
"Score": "0",
"body": "Oh I missed that point entirely, it really is the factoring (like I wrote but didn't realize). So `x**2 * (1 + x)` would speed it up just as much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:20:27.393",
"Id": "36136",
"Score": "0",
"body": "@askewchan: no, `x*x` should be a little faster than `x**2` (although not by much given the Python overhead). Basically, raising something to an arbitrary power has to go via logarithms or the equivalent behind the scenes, whereas `x*x` is just one float multiplication. (Admittedly modern C compilers are pretty good at strength-reducing `pow` calls with hardcoded exponents, but if the value isn't known until runtime you often have to branch.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:20:42.947",
"Id": "36137",
"Score": "1",
"body": "I just timeit’d it: `x * x * (1 + x)` > `x * x + x * x * x` >> `x ** 2 * (1 + x)` >>> `x ** 2 + x ** 3` (`>` means a bit faster, `>>` quite a bit faster, `>>>` a lot faster)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:26:17.827",
"Id": "36138",
"Score": "0",
"body": "Interestingly enough, instead of assuming, I also timeit'd it myself before I wrote that comment and found that `a*a*a*a*(1+a)` is 1.4% faster than `a**4 * (1+a)` on my machine, so clearly it is not always `>>` faster. I suppose it's because it's a hard-coded exponent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:30:51.103",
"Id": "36139",
"Score": "0",
"body": "@askewchan, if you are going to do a**4 * (1+a), then you should do it as b=a*a and get b*b*(1+a) which saves you a multiply."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:33:57.297",
"Id": "36142",
"Score": "1",
"body": "@askewchan: no, it's much likelier to be because each Python op is pretty slow. Try `import dis` and then `dis.dis(lambda a: a*a*a*a*(1+a))` and `dis.dis(lambda a: a**4 * (1+a))`. There are multiple factors at play: Python operation overhead; speed of multiplication vs exponentiation; there's even a difference between `x**4.0` and `x**4`. There are a number of tradeoffs going on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T15:43:33.550",
"Id": "36144",
"Score": "0",
"body": "Cool - dis.dis(lambda ....) is very good input. Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T16:25:46.703",
"Id": "36155",
"Score": "0",
"body": "@askewchan You mean that it’s maybe not `>>` faster but just `>` faster? To be fair, that relation wasn’t supposed to be proportional or anything, just to show that the first are relative similar with a minor difference to the third and a larger difference to the last one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T20:37:01.233",
"Id": "36177",
"Score": "2",
"body": "From the Press et al., Numerical Recipes book, regarding polynomial evaluation: [\"Come the (computer) revolution, all persons found guilty of such criminal behavior will be summarily executed, and their programs won’t be!\"](http://numericalrecipes.wordpress.com/about/)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:45:35.910",
"Id": "23442",
"ParentId": "23441",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23442",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T14:15:48.850",
"Id": "23441",
"Score": "3",
"Tags": [
"python",
"performance",
"numpy"
],
"Title": "Are these list-comprehensions written the fastest possible way?"
}
|
23441
|
<p>I have a method that parses XML into an array of hashes.</p>
<p>Here is the original XML:</p>
<pre class="lang-xml prettyprint-override"><code><rowset name="skillqueue" key="queuePosition" columns="queuePosition,typeID,level,startSP,endSP,startTime,endTime">
<row queuePosition="0" typeID="20495" level="3" startSP="2829" endSP="16000" startTime="2013-03-04 16:25:50" endTime="2013-03-05 01:02:20"/>
<row queuePosition="1" typeID="19767" level="4" startSP="40000" endSP="226275" startTime="2013-03-05 01:02:20" endTime="2013-03-07 06:40:31"/>
</rowset>
</code></pre>
<p>Here is the final array of hashes:</p>
<pre class="lang-ruby prettyprint-override"><code>[{:queuePosition=>"0", :typeID=>"20495", :level=>"3", :startSP=>"2829", :endSP=>"16000", :startTime=>"2013-03-04 16:25:50", :endTime=>"2013-03-05 01:02:20"}, {:queuePosition=>"1", :typeID=>"19767", :level=>"4", :startSP=>"40000", :endSP=>"226275", :startTime=>"2013-03-05 01:02:20", :endTime=>"2013-03-07 06:40:31"}]
</code></pre>
<p>Here is the method, which uses <a href="http://nokogiri.org/" rel="nofollow">Nokogiri</a> for parsing:</p>
<pre class="lang-ruby prettyprint-override"><code>def get_training_queue(xml_data)
queue = []
xml_data.xpath("//row").each do |skill_in_queue|
skill = {}
skill_in_queue.attributes.each do |details|
skill[details[0].to_s.to_sym] = details[1].to_s
end
queue << skill
end
queue
end
</code></pre>
<p>This works great, but it feels a bit inelegant. </p>
<ul>
<li>I'm curious if there is a better way to create the hashes within the internal loop? </li>
<li>I am calling <code>to_s</code> because I couldn't figure out a way to pull out just the key/value without doing so, and it 'feels' like I'm missing some more elegant way of doing that.</li>
</ul>
|
[] |
[
{
"body": "<p>Notes:</p>\n\n<ul>\n<li>Use functional <code>Enumerable#map</code> instead of imperative pattern <code>obj = []</code> + <code>Enumerable#each</code> + <code>Array#<<</code>.</li>\n<li>Use <a href=\"http://ruby-doc.org/core-2.0/Kernel.html#method-i-Hash\" rel=\"nofollow\">Kernel#Hash</a> to build a hash from its pairs. Note that this method is very ugly and some prefer a more OOP approach, in that case check <a href=\"http://rdoc.info/github/rubyworks/facets/master/Enumerable#graph-instance_method\" rel=\"nofollow\">Enumerable#mash</a> from Facets.</li>\n<li>Use <code>nokogiri_node.text</code>.</li>\n<li>Arguments in blocks can be unpacked.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>require 'nokogiri'\nrequire 'facets'\n\ndef get_training_queue(xml_data)\n xml_data.xpath(\"//row\").map do |skill_in_queue|\n skill_in_queue.attributes.mash do |name, attribute|\n [name.to_sym, attribute.text]\n end\n end\nend\n</code></pre>\n\n<p>All those <code>each</code>s and in-place updates show that you think in imperative terms instead of functional, check <a href=\"http://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">this wiki page</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T15:44:09.893",
"Id": "36236",
"Score": "0",
"body": "I had failed to get around to messing with facets up to this point - so interesting solution. Both answers presented in this thread were helpful, but Flambino offered two helpful solutions so I'm going to go ahead and issue them the answer. Upvote though :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T09:30:38.263",
"Id": "36292",
"Score": "0",
"body": "@Ecnalyr: no problem, the solutions are almost identical. Make sure you read a bit about FP though, great stuff!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T18:34:19.207",
"Id": "23451",
"ParentId": "23449",
"Score": "4"
}
},
{
"body": "<p>Start by using <code>map</code> instead of <code>each</code> plus <code><<</code>; creating an array and then adding to it isn't very Ruby-like.</p>\n\n<p>Second, <a href=\"http://nokogiri.org/Nokogiri/XML/Node.html#method-i-attributes\" rel=\"nofollow\"><code>Node#attributes</code></a> is a hash already, so one way to go is to modify a duplicate of it, rather than \"manually\" copying each key/value to a new hash. Also, the keys are strings so <code>to_s.to_sym</code> can be replaced by just <code>to_sym</code>.</p>\n\n<p>To do the hash-conversion, I've used the same <code>keys.each</code> approach as what Rails uses in its <a href=\"http://api.rubyonrails.org/classes/Hash.html#method-i-symbolize_keys-21\" rel=\"nofollow\"><code>symbolize_keys!</code> method</a>.</p>\n\n<pre><code>def get_training_queue(xml_data)\n xml_data.xpath(\"//row\").map do |row|\n skill = row.attributes.dup\n skill.keys.each do |key|\n skill[key.to_sym] = skill.delete(key).to_s\n end\n skill\n end\nend\n</code></pre>\n\n<p>Here's a different, super-brief, approach that uses the <code>Hash[ [key, value] , ... ]</code> syntax</p>\n\n<pre><code>def get_training_queue(xml_data)\n xml_data.xpath(\"//row\").map do |row|\n Hash[ row.attributes.map { |k, v| [k.to_sym, v.to_s] } ]\n end\nend\n</code></pre>\n\n<p>Either one should give you the right result, though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T23:54:22.093",
"Id": "36271",
"Score": "0",
"body": "you can safely remove that `to_a` :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T00:03:12.443",
"Id": "36273",
"Score": "0",
"body": "@tokland Good call. Wonder why I even put that in there... :P"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T18:34:32.187",
"Id": "23452",
"ParentId": "23449",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23452",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T17:53:00.983",
"Id": "23449",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails",
"parsing",
"xml"
],
"Title": "Parsing data from XML using Ruby and Nokogiri"
}
|
23449
|
<p>I wrote the following function that takes a string and returns a new string with each word capitalized: first letter uppercase, following letters lower-cased.</p>
<p>It works, but I would be interested in seeing how a more sophisticated Haskell programmer would do this (if there is already a built-in, great, but still interested in an example implementation).</p>
<pre><code>ghci> let capWord word = [toUpper $ head word] ++ (map toLower $ tail word)
ghci> let capitalize sentence = unwords $ map capWord $ words sentence
ghci> capitalize "the quick brown fox jUMPS OVER thE LaZY DOG"
"The Quick Brown Fox Jumps Over The Lazy Dog"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T11:00:00.640",
"Id": "36219",
"Score": "1",
"body": "FIY, I asked a question concerning the `capitalize` function: http://stackoverflow.com/questions/15222013/how-to-abstract-over-a-back-and-forth-transformation"
}
] |
[
{
"body": "<p><code>head</code> and <code>tail</code> are <a href=\"http://www.haskell.org/haskellwiki/Partial_functions\">partial functions</a>, meaning that they are only defined for non-empty lists and will fail on empty ones. Because of this your <code>capWord</code> function is also partial and its strongly considered a bad practice to define such functions. In fact, the <code>head</code> and <code>tail</code> are also considered a bad heritage and in <a href=\"http://hackage.haskell.org/package/classy-prelude\">some alternative preludes</a> it's been deliberately decided not to export such functions. So, firstly, you can redefine your function with pattern matching and make it total.</p>\n\n<p>Secondly, you're introducing a redundant list for the first letter, instead you can prepend it using the <code>:</code> (pronounced \"cons\") operator.</p>\n\n<p>Summing up we get the following definition:</p>\n\n<pre><code>capWord [] = []\ncapWord (h:t) = toUpper h : map toLower t\n</code></pre>\n\n<p>Alternatively (essentially the same):</p>\n\n<pre><code>capWord word = case word of\n [] -> []\n (h:t) -> toUpper h : map toLower t\n</code></pre>\n\n<p>The <code>capitalize</code> function is fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T23:55:38.150",
"Id": "36189",
"Score": "1",
"body": "Thanks, I read up on partial functions, and how to avoid them http://www.haskell.org/haskellwiki/Avoiding_partial_functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T10:48:10.277",
"Id": "36218",
"Score": "1",
"body": "`words` will never return an empty string, so making `capWord` local to capitalize would also be okay. But since `capWord` is also useful on it's own, your solution is best."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T20:49:18.437",
"Id": "23459",
"ParentId": "23456",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "23459",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T19:51:51.103",
"Id": "23456",
"Score": "5",
"Tags": [
"beginner",
"strings",
"haskell"
],
"Title": "Capitalizing a string"
}
|
23456
|
<p>I have an upload form on my site and I'm trying to sanitize and transform input data.</p>
<p>I will be straight forward to you - this is my first object-oriented style code! The reason I don't just want to use regular function, is that I would like to keep my codes divided in logical blocks. I called this one <em>Filter</em>. It has, so far 2 methods in it.</p>
<p>Before I will tell you what I'd like to improve, here is my <em>Filter Class</em>:</p>
<pre><code>class Filter {
public static function Text($data, $tags = 1, $displace = 1, $characters = 1, $numbers = 0, $punctuation = 0, $linespacing = 2, $whitespaces = 1, $transform = 0) {
if ($tags === 1) {
$data = filter_var($data, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
}
if ($displace === 1) {
$data = str_replace('`', '\'', $data);
}
if ($characters === 1) {
$unwanted_characters = array(
'<',
'>',
'{',
'}',
'*',
'|',
'\\',
'%',
'^',
'~',
'‘',
'getURL',
'javascript',
'activex',
'x00',
'x04',
'x08',
'x0d',
'x1b',
'x20',
'x7f',
'%7b',
'%7d',
'%7c',
'%5c',
'%5e',
'%7e',
'%60',
'%25',
'%27'
);
$data = str_replace($unwanted_characters, '', $data);
}
if ($numbers === 1) {
$data = preg_replace('/\d/', '', $data);
}
if ($punctuation === 1) {
$unwanted_punctuation = array(
',',
'.',
':',
';',
'!',
'?',
'#',
'№',
'@',
'$',
'&',
'*',
'=',
'/',
'[',
']'
);
$data = str_replace($unwanted_punctuation, '', $data);
}
if ($linespacing === 0) {
$data = preg_replace("/(\r?\n){0,}\n+/", " ", $data);
}
if ($linespacing === 1) {
$data = preg_replace("/(\r?\n){1,}/", "\n", $data);
}
if ($linespacing === 2) {
$data = preg_replace("/(\r?\n){2,}/", "\n\n", $data);
}
if ($linespacing === 3) {
$data = preg_replace("/(\r?\n){3,}/", "\n\n\n", $data);
}
if ($linespacing === 4) {
$data = preg_replace("/(\r?\n){4,}/", "\n\n\n\n", $data);
}
if ($linespacing === 5) {
$data = preg_replace("/(\r?\n){5,}/", "\n\n\n\n\n", $data);
}
if ($whitespaces === 1) {
$data = preg_replace("/[ ]+/", " ", $data);
$data = join("\n", array_map("trim", explode("\n", $data)));
$data = join("\r", array_map("trim", explode("\r", $data)));
}
if ($transform === 1) {
$data = mb_strtolower($data);
}
if ($transform === 2) {
$data = mb_strtoupper($data);
}
return $data;
}
public static function Links($data) {
$data = preg_replace('%(((f|ht){1}tp://|(f|ht){1}tps://)[-a-zA-^Z0-9@:\%_\+.~#?&//=]+)%i', '<a href="\\1" target="_blank">\\1</a>', $data);
$data = preg_replace('%([[:space:]()[{}])(www.[-a-zA-Z0-9@:\%_\+.~#?&//=]+)%i', '\\1<a href="http://\\2" target="_blank">\\2</a>', $data);
if (preg_match("/[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}/i", $data, $email)) {
$replacement = '<a href="mailto:' . $email[0] . '" target="_blank">' . $email[0] . '</a> ';
$data = preg_replace("/[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}/i", $replacement, $data);
}
return $data;
}
}
</code></pre>
<p>I use it as follows:</p>
<pre><code>$description = Filter::Text($_POST['description'], $tags = 1, $displace = 1, $characters = 1, $numbers = 0, $punctuation = 0, $linespacing = 2, $whitespaces = 1, $transform = 0);
</code></pre>
<p>and</p>
<pre><code>$description = Filter::Links($description);
</code></pre>
<p>If you have anything in mind that you would like to say to improve it, please go ahead. </p>
<p>I personally don't like to pass everytime a huge set of variables, such as <code>$tags = 1, $displace = 1, $characters = 1, $numbers = 0 ...</code>. What I would like to do is to set default values at my class's methods just once and then change only specific ones in case I have to.</p>
<p>For example, to show what I mean, in order to filter my description field with keeping default values but one (which is <code>$transform</code> in the example below):</p>
<pre><code>$description = Filter::Text($_POST['description'], $transform = 1);
</code></pre>
<p>Now, instead of writing that huge set of default variable, I could only pass the variable that's value is different from default. </p>
<p>It doesn't work this way so far. Not sure what I'm missing?</p>
|
[] |
[
{
"body": "<p>OK...first off: this isn't OOP. OOP is about objects talking to each other, delegating tasks to each other to get stuff done. What you're doing here is just using classes as modules. There's nothing inherently wrong with that, but it doesn't automatically make your code <em>object oriented</em>. Just letting you know that before some OOP zealot starts calling you the devil and telling you you're doing it wrong. :)</p>\n\n<p>As for your args issue...What you have here is a bunch of boolean flags (and a number for line spacing). An int has at least 31 bits, meaning it can hold pretty much all of the flags. Use constants with them, and you end up with a more concise set of arguments that you can specify by name.</p>\n\n<p>Consider:</p>\n\n<pre><code>class Filter {\n const DEFAULTS = 0;\n const TAGS = 0x01;\n const DISPLACE = 0x02;\n const CHARACTERS = 0x04;\n const DIGITS = 0x08;\n const PUNCTUATION = 0x10;\n const SPACES = 0x20;\n const TOUPPER = 0x40;\n const TOLOWER = 0x80;\n\n public static function Text($data, $flags = 0, $linespacing) {\n if (!$flags) {\n $flags = self::TAGS | self::DISPLACE | self::CHARACTERS | self::SPACES;\n }\n\n if ($flags & self::TAGS) {\n ... do tags stuff ...\n }\n ... handle other flags similarly ...\n }\n}\n</code></pre>\n\n<p>Now, you can say</p>\n\n<pre><code>$text = Filter::Text($data, Filter::TAGS | Filter::CHARACTERS | Filter::TOUPPER, 2);\n</code></pre>\n\n<p>This could be even shorter if the constants were global, but eh.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T06:22:29.310",
"Id": "36204",
"Score": "0",
"body": "thanks for your reply! I agree with you that it's NOT using OO approach fully but at the same time, if talking applying to my project globally - it kind of does - because, I don't repeat my codes and editing one single block of code changes the behavior everywhere else! I think those zealots, like you called them :) will understand, as I'm just starting with this. Concerting your answer, I'm not sure that I understood how to apply what you were talking about! Is there a way you could post it with an example on CodePad maybe, please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T06:36:08.223",
"Id": "36205",
"Score": "0",
"body": "@Ilia: http://codepad.org/BQOIjTYE Note the output says \"I'd strip tags here\" but not \"I'd strip spaces here\", because the last line doesn't include the SPACES flag. Also, note that you can specify flags by name once they're consts. This not only lets readers know what the numbers mean...it also provides a clue as to what flags can be used, cause they're all named in the class."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T23:47:33.860",
"Id": "23465",
"ParentId": "23457",
"Score": "3"
}
},
{
"body": "<p>Answer has been accepted however it misses out a LOT of stuff. Rather than go through it all in detail, consider:</p>\n\n<pre><code>class Filter {\n\nvar $opts=array(\n 'tags'=>1, 'displace'=> 1, 'chars'=>1\n ,'numbers'=>0, 'punct'=>0, 'linspacing'=>2\n ,'whitespace'=>1, 'transform'=>1\n);\n\npublic function __constructor($opts=false)\n{\n $this->setopts($opts);\n}\n\npublic function setopts($opts=false)\n{\n if (false!==$opts) {\n $this->opts=$opts;\n }\n return $this->opts;\n}\n\nprivate function extendFilter(&$filter, $srch, $replace)\n{\n $ar=false;\n if (is_array($replace)) {\n $ar=true;\n }\n foreach ($keys as $idx=>$key) {\n $filter[$key] = $ar ? $replace[$idx] : $replace;\n } \n}\n\npublic function Text($data) \n{\n\n if ($this->opts['tags']) {\n $data = filter_var($data\n , FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);\n }\n\n $unwanted=array();\n if ($this->opts['displace']) {\n $unwanted['`']='\\'';\n }\n\n if ($this->opts['chars']) {\n $this->extendFilter($unwanted, array(\n '<',\n '>',\n '{',\n '}',\n '*',\n '|',\n '\\\\',\n '%',\n '^',\n '~',\n '‘',\n 'getURL',\n 'javascript',\n 'activex',\n 'x00',\n 'x04',\n 'x08',\n 'x0d',\n 'x1b',\n 'x20',\n 'x7f',\n '%7b',\n '%7d',\n '%7c',\n '%5c',\n '%5e',\n '%7e',\n '%60',\n '%25',\n '%27'\n ), '');\n }\n\n\n if ($this->opts['punctuation']) {\n $this->extendFilter($unwanted, array(\n ',',\n '.',\n ':',\n ';',\n '!',\n '?',\n '#',\n '№',\n '@',\n '$',\n '&',\n '*',\n '=',\n '/',\n '[',\n ']'\n ), '');\n $data = str_replace($unwanted_punctuation, '', $data);\n }\n\n $data = str_replace(array_keys($unwanted), array_values($unwanted), $data);\n\n if ($this->opts['numbers']) {\n $data = preg_replace('/\\d/', '', $data); \n }\n\n $regex=\"/(\\r?\\n){\" . (integer)$opts['linespacing'] . \",}\\n+/\"\n $ch=(integer)$opts['linespacing'] \n ? \" \" \n : str_repeat(\"\\n\", $opts['linespacing']);\n $data = preg_replace($regex, $ch, $data);\n\n if ($this->opts['whitespaces']) { \n // ! most people would consider newline to be whitespace \n // - breaking linespacing\n // but also tab\n // if I spent time thinking about there's much cleaner, efficient ways to do this....\n $data = preg_replace(\"/[ ]+/\", \" \", $data);\n $data = join(\"\\n\", array_map(\"trim\", explode(\"\\n\", $data)));\n $data = join(\"\\r\", array_map(\"trim\", explode(\"\\r\", $data)));\n }\n\n if (1===$this->opts['transform']) {\n $data = mb_strtolower($data);\n }\n if (2===$this->opts['transform']) {\n $data = mb_strtoupper($data);\n }\n\n return $data; \n}\n\npublic static function Links($data) {\n $data = preg_replace('%(((f|ht){1}tp://|(f|ht){1}tps://)[-a-zA-^Z0-9@:\\%_\\+.~#?&//=]+)%i', '<a href=\"\\\\1\" target=\"_blank\">\\\\1</a>', $data);\n $data = preg_replace('%([[:space:]()[{}])(www.[-a-zA-Z0-9@:\\%_\\+.~#?&//=]+)%i', '\\\\1<a href=\"http://\\\\2\" target=\"_blank\">\\\\2</a>', $data);\n\n // tis is not the best email regex ever.\n if (preg_match(\"/[^@\\s]+@([-a-z0-9]+\\.)+[a-z]{2,}/i\", $data, $email)) {\n $replacement = '<a href=\"mailto:' . $email[0] . '\" target=\"_blank\">' . $email[0] . '</a> ';\n $data = preg_replace(\"/[^@\\s]+@([-a-z0-9]+\\.)+[a-z]{2,}/i\", $replacement, $data);\n }\n return $data;\n }\n\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T07:57:23.987",
"Id": "36284",
"Score": "0",
"body": "Thanks for your effort! I have a question though! How do you apply it? You want to say, that you would have to create a new instance all the time? Please provide your code with working example on CodePad or anywhere else."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T07:59:12.987",
"Id": "36285",
"Score": "0",
"body": "If you have better `email regex` could you please share and point out the drawbacks of mine? I'd be deeply appreciate!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T09:32:40.753",
"Id": "36293",
"Score": "0",
"body": "Yes it retains state therefore needs to be implemented as an instance rather than called statically (can't see the point in static classes in PHP myself). Email regex? See - http://stackoverflow.com/questions/3836323/php-email-address-validation-question/3838764#3838764"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-10T08:41:47.160",
"Id": "36527",
"Score": "0",
"body": "Thanks for you effort, my friend! +1 even thought it's not exactly what I was asking for but it helped me in getting the idea of object-oriented style in a close look! Your regex for email does the same work as mine but in more concise way? Correct!?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:46:43.820",
"Id": "23508",
"ParentId": "23457",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23465",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T20:29:14.683",
"Id": "23457",
"Score": "2",
"Tags": [
"php"
],
"Title": "Filter Class to sanitize and transform input data - Improvements?"
}
|
23457
|
<p>I wrote a simple SPI Master implementation to send characters to a LCD screen. Only the output is actually implemented in this so there is no rx register. This only sends a character out when write is asserted. I would appreciate any feedback and wanted to test out stackexchange for HDL. </p>
<pre><code>library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;
-- Entity and Architecture Definitions
entity spi_master is
generic (
REG_SIZE : integer := 8;
CLK_DIV : integer := 25); -- This runs 2x slower then sys clock
-- so to divide 50 Mhz to 1Mhz div by 25 not 50
port (
clk: in std_logic; -- 1 Mhz provided by system
data: in std_logic_vector(REG_SIZE-1 downto 0);
write: in std_logic; -- begin sending out register contents
cpol: in std_logic;
cpha: in std_logic;
rst: in std_logic;
spi_clock: out std_logic;
mosi: out std_logic;
ss: out std_logic);
end entity spi_master;
architecture spi_master of spi_master is
signal spi_clk : std_logic; -- temp spi clock (twice as slow as clk)
signal tx_reg : std_logic_vector(REG_SIZE-1 downto 0); -- temp transmit
register
signal count : integer; -- count
signal toggle_count : integer;
type machine is (ready, low_cpha, high_cpha);
signal state : machine;
signal spi_en : std_logic;
signal write_strobe : std_logic;
signal write_strobe_sync0 : std_logic;
signal write_strobe_sync1 : std_logic;
begin
spi_clock <= spi_clk;
process(clk,write_strobe_sync1, rst)
begin
if(rst = '0') then
mosi <= 'Z';
state <= ready;
count <= REG_SIZE;
ss <= '1';
elsif rising_edge(clk) then
case state is
when ready =>
tx_reg <= data; -- load temp register with data
mosi <= 'Z';
count <= (REG_SIZE*2); -- running 2x slower then clock
toggle_count <= CLK_DIV;
spi_clk <= cpol;
ss <= '1';
if (write_strobe_sync1 = '1' and cpha = '0') then
spi_en <= '0'; -- delay the enable half an spi_clk period
ss <= '0';
state <= low_cpha;
elsif(write_strobe_sync1 = '1' and cpha = '1') then
spi_en <= '1';
ss <= '0';
state <= high_cpha;
else
state <= ready;
end if;
when low_cpha =>
if(toggle_count = 0) then -- toggle spi_clk CLK_DIV
toggle_count <= CLK_DIV; -- count for 1Mhz
if(spi_en = '1') then
count <= count - 1;
if(count /= 16) then
spi_clk <= not spi_clk; -- makes this 2x slower then clk
end if;
else -- send out mosi even if spi_clk isnt enabled for low cpha
mosi <= tx_reg(REG_SIZE-1); -- shift out mosi
tx_reg <= tx_reg(REG_SIZE-2 downto 0) & '0';
spi_en <= '1';
end if;
if(cpol /= spi_clk ) then
mosi <= tx_reg(REG_SIZE-1);
tx_reg <= tx_reg(REG_SIZE-2 downto 0) & '0';
end if;
if(count = 0) then
state <= ready;
else
state <= low_cpha;
end if;
else
toggle_count <= toggle_count - 1;
end if;
when high_cpha =>
if(spi_en = '1') then
-- run spi at CLK_DIV
if(toggle_count = 0) then
count <= count - 1;
toggle_count <= CLK_DIV;
if(count /= 0) then
spi_clk <= not spi_clk; -- makes this 2x slower then clk
-- shift out data to mosi
if(cpol = spi_clk ) then
mosi <= tx_reg(REG_SIZE-1);
tx_reg <= tx_reg(REG_SIZE-2 downto 0) & '0';
end if;
end if;
-- Change to the next state
if(count = 0) then
state <= ready;
else
state <= high_cpha;
end if;
else
toggle_count <= toggle_count - 1;
end if;
else
spi_en <= '1';
end if;
end case;
end if;
end process;
-- Syncronize asyncrounous input
latch_write: process(write, write_strobe_sync1, rst)
begin
if(write_strobe_sync1 = '1' or rst = '0') then
write_strobe <= '0';
elsif rising_edge(write) then
write_strobe <= '1';
end if;
end process;
sync_write: process(clk, rst, write_strobe)
begin
if(rst = '0') then
write_strobe_sync0 <= '0';
write_strobe_sync1 <= '0';
elsif rising_edge(clk) then
write_strobe_sync0 <= write_strobe;
write_strobe_sync1 <= write_strobe_sync0;
end if;
end process;
end architecture spi_master;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T13:19:37.043",
"Id": "36226",
"Score": "2",
"body": "Please at least indent your code consistently!"
}
] |
[
{
"body": "<p>Never saw HDL before, but the following came to mind</p>\n\n<ol>\n<li><p>Indentation seems wrong, I would have expected <code>case state</code> to be indented</p>\n\n<pre><code>elsif rising_edge(clk) then\n\ncase state is\n</code></pre></li>\n<li><p><code>mosi <= 'Z';</code> <- Why 'Z', that could use a comment</p></li>\n<li><p><code>if(rst = '0') then</code> it seems from your code that the brackets are unnecessary, you should either put them everywhere or nowhere for style consistency</p></li>\n<li><p>Obvious newbie remark: <code>tx_reg <= tx_reg(REG_SIZE-2 downto 0) & '0';</code> How is this different from <code>tx_reg <= '0'</code> ? </p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T13:18:55.343",
"Id": "36225",
"Score": "5",
"body": "2) 'Z' is a specific HDL value that means a lot to us hardware types without a comment. 4) `&` is a concatenation operator in VHDL (not bitwise and)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T21:10:47.357",
"Id": "23460",
"ParentId": "23458",
"Score": "1"
}
},
{
"body": "<p>First thing you need to do is get your sensitivity lists correct.</p>\n\n<pre><code>process (clk)\n</code></pre>\n\n<p>is all that is required for a synchronous process and</p>\n\n<pre><code>process (clk, rst)\n</code></pre>\n\n<p>if you have an asynchronous reset signal.</p>\n\n<p>You don't need all the other signals unless it is a combinational process (like latch_write is) but it's error-prone, so I find it much safer to make everything a clocked process. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T13:21:41.257",
"Id": "23483",
"ParentId": "23458",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T20:36:11.850",
"Id": "23458",
"Score": "2",
"Tags": [
"hdl",
"vhdl"
],
"Title": "Simple SPI Master"
}
|
23458
|
<p>I wrote a script to perform <code>svn update</code> on all the SVN repositories inside a folder. It would have been great if the folder containing all these repositories itself was a repository, but it was not setup like that, which is why I opted to write this script.</p>
<pre><code>$timestamp = get-date -f "yyyy-M-d-h-m-s"
$SvnLogPath="C:\out\svnlogs\"
if(test-path -path $SvnLogPath)
{
write-host "SVN Log path doesn't exist. So I am creating it . . ."
new-item -type directory $SvnLogPath | out-null
}
$logfile = "${SvnLogPath}svn_update_${timestamp}.log"
new-item -type file $logfile | out-null
$BaseDir="C:\TRUNK\"
$RepositoryList = "Alpha","Bravo","Charlie","Delta","Echo","Foxtrot","Golf","Hotel"
# BUILDING FULL PATHS
$FullPaths = $RepositoryList | %{ $BaseDir+$_}
# ISSUING SVN UPDATE TO EACH DIR
$FullPaths | % {svn update $_ 2>&1 | ft -AutoSize -Wrap | Out-File -Append $logfile }
# OPEN LOG FILE AFTER THE COMPLETION
notepad $logfile
</code></pre>
<p>Can this script be further simplified and written more idiomatically?</p>
<p>PS: I am using only <code>svn update</code> without credentials as they are stored in the shell already.</p>
|
[] |
[
{
"body": "<p>Personally, I would look to use:</p>\n\n<pre><code>$FullPaths = $RepositoryList | %{ Join-path $BaseDir $_ }\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>$FullPaths = $RepositoryList | %{ $BaseDir+$_}\n</code></pre>\n\n<p>You could alternatively also do something like:</p>\n\n<pre><code>$FullPaths = Join-path $BaseDir \"*\\.svn\" | Resolve-Path | Split-Path\n</code></pre>\n\n<p>This would build a list of all subfolders of $BaseDir that have a .SVN folder.</p>\n\n<p>Resolve path will return the path with ..SVN\\ and split path will remove the folder.</p>\n\n<p>If you have .LOG registered with Notepad, you could also use </p>\n\n<pre><code>Invoke-Item $logFile\n</code></pre>\n\n<p>This may be more flexible if someone else runs the script and would rather see output in a different editor.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T13:35:15.057",
"Id": "25682",
"ParentId": "23468",
"Score": "4"
}
},
{
"body": "<h2>Reusable Commands</h2>\n\n<p>One of the most important ideas in PowerShell is the Get/Update/Set pattern. A clear delineation between resources (nouns) and commands (verbs) helps to write code that is useful not only for scripting, but also in the interactive shell.</p>\n\n<p>We only need a couple of new commands. First we need to <code>Find</code> the working copies under some directory, then <code>Update</code> each working copy. The list of <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms714428(v=vs.85).aspx\" rel=\"nofollow noreferrer\">approved verbs for PowerShell</a> is a great resource for help with naming your commands. Let's use these names.</p>\n\n<ul>\n<li>Find-SvnWorkingCopy (<code>Find</code> looks for an object in a container)</li>\n<li>Update-SvnWorkingCopy (<code>Update</code> brings a resource up-to-date)</li>\n</ul>\n\n<h2>Functions and Modules</h2>\n\n<p>Now you're convinced that we should create reusable commands with these great new names. What next? PowerShell v2 introduced the concept of a module, which is just a file that contains functions. (<em>Of course, you could just create a new script for each command but it helps to keep things tidy by bundling all of the functions together in one file.</em>)</p>\n\n<p>What should our functions look like? Yes they will need to take some parameters. But more importantly, they should return objects to the pipeline, even if they aren't a \"getter\" function! This makes it easier to review what impact a function had.</p>\n\n<h2>Some actual code</h2>\n\n<p>Luckily for us, somebody else already found a way to <a href=\"https://stackoverflow.com/questions/9015393/powershell-script-to-find-all-svn-working-copies\">find all the svn working copies underneath a directory</a>. We can reuse that.</p>\n\n<p><em>SvnTools.psm1</em></p>\n\n<pre><code>function Find-SvnWorkingCopy\n{\n Param (\n [Parameter(ValueFromPipeline=$true,Mandatory=$true)]\n $BasePath\n )\n process\n {\n $prev = \"^$\"\n Get-ChildItem -Recurse -Force -Include \".svn\" -Path $BasePath |\n Where-Object {\n $_.PSIsContainer -and $_.Fullname.StartsWith($prev)-eq $false\n } |\n ForEach-Object {\n $prev=$_.Fullname.TrimEnd(\".svn\")\n $prev\n }\n }\n}\n</code></pre>\n\n<p>I took some liberties with the command <code>Update-SvnWorkingCopy</code>. In addition to calling \"svn update\" like your original script, it also calls \"svn info\" and parses the results to find the current revision number and include that in the object returned to the pipeline.</p>\n\n<p><em>SvnTools.psm1 (continued)</em></p>\n\n<pre><code>function Update-SvnWorkingCopy\n{\n Param (\n [Parameter(ValueFromPipeline=$true,Mandatory=$true)]\n $WorkingCopy\n )\n process {\n svn update $WorkingCopy > $null\n [String[]] $result = svn info $WorkingCopy\n [String] $revStr = $result -like \"Revision:*\"\n [int] $revNumber = $revStr.Replace(\"Revision: \", \"\")\n New-Object -TypeName PSObject -Prop @{\n WorkingCopy=$WorkingCopy;\n Revision=$revNumber;\n } | Write-Output\n }\n}\n</code></pre>\n\n<p>Now we can reap the benefits from creating these commands. Here's your original script, rewritten to take advantage of our new module using just one line.</p>\n\n<p><em>UpdateMyWorkingCopies.ps1</em></p>\n\n<pre><code>Import-Module C:\\path\\to\\module\\SvnTools.psm1\nFind-SvnWorkingCopy -BasePath \"C:\\TRUNK\\\" | Update-SvnWorkingCopy\n</code></pre>\n\n<p>You could easily redirect the output to a file. If you don't, it will show up on screen looking something like this.</p>\n\n<pre><code>WorkingCopy Revision\n----------- --------\nC:\\TRUNK\\Alpha 31\nC:\\TRUNK\\Bravo 42\nC:\\TRUNK\\Charlie 16\n</code></pre>\n\n<h2>References</h2>\n\n<p>The Scripting Guy! blog on TechNet has a really excellent series about <a href=\"http://blogs.technet.com/b/heyscriptingguy/archive/tags/windows+powershell/guest+blogger/sean+kearney/build+your+own+cmdlet/\" rel=\"nofollow noreferrer\">building your own PowerShell cmdlet</a> that I recommend reading.</p>\n\n<p><strong>Coding Style</strong></p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/2031927/190298\">https://stackoverflow.com/a/2031927/190298</a></li>\n<li><a href=\"https://stackoverflow.com/questions/5260125/whats-the-better-cleaner-way-to-ignore-output-in-powershell\">https://stackoverflow.com/questions/5260125/whats-the-better-cleaner-way-to-ignore-output-in-powershell</a></li>\n<li><a href=\"http://web.archive.org/web/20110109180531/http://www.powershellcommunity.org/Wikis/BestPractices/tabid/79/topic/Naming/Default.aspx\" rel=\"nofollow noreferrer\">http://www.powershellcommunity.org/Wikis/BestPractices/tabid/79/topic/Naming/Default.aspx</a></li>\n</ul>\n\n<h2>Bonus Points</h2>\n\n<p>For bonus points, install the module into one of the module path folders (<code>$env:PSModulePath</code>) so that you can import it from the shell more easily.</p>\n\n<p>And if you want to get even more fancy, implement another command called <code>Get-SvnWorkingCopy</code> which parses all of the results from <code>svn info</code>. It should integrate nicely with the two commands we already created here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T13:36:48.657",
"Id": "526688",
"Score": "0",
"body": "This almost works perfectly! The only thing not quite right (here in 2021!) is that the Rev # stays the same throughout the loop. I'm going to see why it's not changing, and I'll be back."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T06:05:56.560",
"Id": "26060",
"ParentId": "23468",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "26060",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T04:10:42.847",
"Id": "23468",
"Score": "8",
"Tags": [
"powershell"
],
"Title": "Updating multiple svn repositories using powershell"
}
|
23468
|
<p>School HABTM AthleticDirector</p>
<p>I am building a tool for assigning athletic directors (ADs) to schools. The tool has a school menu/filter which, when selected, shows a list of ADs already assigned to the school, and those yet to be assigned.</p>
<p>The tool can be used in two ways:</p>
<ol>
<li>in a stand-alone fashion, where you arrive at the tool with no school id, then select a school, OR</li>
<li>where you arrive FROM the school list via an "assign ADs" link, in which case the school id is known.</li>
</ol>
<p>I have this working, but it seems like there might be a better way. Mainly, I'm wondering if there's some way to not need to support retrieving the school id in two different manners. Though maybe that's inevitable?</p>
<p>Here's my code:</p>
<p>When viewing the school list, the Assign AD link is as so, passing the school id as a param:</p>
<pre><code>// e.g. /assign_school_ads/5
echo $this->Html->link(__('Assign ADs'), array('action' => 'assign_school_ads', $school['School']['id']));
</code></pre>
<p>The controller is then written to handle the school $id either as a param (from the assign link) or as data (from a school menu selection) </p>
<pre><code>//School Controller
public function assign_school_ads($id = null) {
$this->School->id = ($id) ? $id : $this->data['School']['school_id'];
if ($id AND !$this->School->exists()) {
throw new NotFoundException(__('Invalid school.'));
}
$assignedSchoolADs = $this->School->getSchoolADs();
// school menu
$schools = $this->School->find('list', array(
'conditions' => array(
'School.status' => true,
),
));
$this->set(compact('assignedSchoolADs', 'schools'));
}
//Model
public function getSchoolADs() {
$params = array(
'contain' => array(
'AthleticDirector' => array(
'fields' => array ('AthleticDirector.name'),
'order' => array ('AthleticDirector.name' => 'ASC'),
'conditions' => array ('AthleticDirector.status' => true),
),
),
'conditions' => array(
'School.id' => $this->id
),
'fields' => array(
'School.id AS schoolID'
),
);
return $this->find('first', $params);
}
//View
<?php
$data = $this->Js->get('#SchoolFilter')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#SchoolSchoolId')->event(
'change', $this->Js->request(
array('action' => 'assign_school_ads'), array(
'update' => '#content',
'data' => $data,
'async' => true,
'dataExpression' => true,
'method' => 'POST'
)
)
);
// School Filter
$schoolFilter = $this->Form->create('School', array_merge(array('id' => 'SchoolFilter'), $this->params['pass']));
$schoolFilter .= $this->Form->input('school_id', array('label'=>'Schools', 'empty'=>'- select -', 'default' => $this->params['pass']));
$schoolFilter .= $this->Form->end();
?>
<div class="schools index">
<h2><?php echo __('Assign School Athletic Directors'); ?></h2>
<div id ="searchFilters">
<?php
echo $schoolFilter;
?>
</div>
<!-- EXISTING AD LIST -->
<table>
<?php
if (!empty($assignedSchoolADs)) {
if (!empty($assignedSchoolADs['AthleticDirector'])) {
foreach($assignedSchoolADs['AthleticDirector'] as $ad){
echo '
<tr>
<td>' . $ad['name'] . '</td>
<td>' . $ad['AthleticDirectorsSchool']['id'] . '</td>
</tr>';
}
} else {
echo '
<tr>
<td>There are no Athletic Directors assigned to this school.</td>
</tr>';
}
} else {
echo '
<tr>
<td>Please select a school.</td>
</tr>';
}
?>
</table>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T05:37:34.820",
"Id": "23469",
"Score": "3",
"Tags": [
"php",
"cakephp"
],
"Title": "CakePHP Best strategy for getting HABTM data in multiple ways within the same tool"
}
|
23469
|
<p>I encountered a problem at <a href="http://regexone.com/example/6" rel="nofollow">http://regexone.com/example/6</a>?
You can view the problem by clicking the link.
There was required a regular expression to extract the method name, filename and the line number from a particular stack trace in an android development application.</p>
<p>I used the following regular expression to solve the problem :</p>
<pre><code>at widget.List.([a-zA-Z]+).([A-Za-z]+\.java).(\d{3,4}).
</code></pre>
<p>The expression works for the problem but i don't think its the correct regular expression as there is no hat(^) and dollar ($) included in it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T11:50:50.407",
"Id": "36222",
"Score": "0",
"body": "If you want to actually solve the problem rather than merely pass the test cases then you also need to take into account that packages can contain multiple components separated by a dot, that all names can begin with an underscore and can contain digits except at the first character, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T15:35:57.827",
"Id": "36235",
"Score": "0",
"body": "You are falsely assuming a regex should contain `^` and `$`."
}
] |
[
{
"body": "<p>If you wish to include the hat <code>^</code> and dollar <code>$</code> signs, then the regex can be rewritten as:</p>\n\n<pre><code>^.*\\s+at widget\\.List\\.(\\w+)\\((\\w+\\.java)\\:(\\d+)\\)$\n</code></pre>\n\n<p>Ofcourse, you can still use <code>\\d{3,4}</code> instead of <code>\\d+</code> but that'll result in you missing the errors in line numbers less than 100(like 1 to 99).</p>\n\n<p>Similarly, you can use <code>\\w+</code> in place of <code>[a-zA-Z]+</code> or simply, <code>[A-z]+</code> will work too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T11:59:29.767",
"Id": "36223",
"Score": "0",
"body": "Thats a perfect regular expression built by you @Back in a Flash. Good one !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T11:45:03.137",
"Id": "23472",
"ParentId": "23471",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23472",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T11:20:34.653",
"Id": "23471",
"Score": "2",
"Tags": [
"regex"
],
"Title": "To extract specific information in the stack trace using regular expression"
}
|
23471
|
<p>The <a href="http://www.doctrine-project.org/" rel="nofollow">Doctrine Project</a> is a collection of open source libraries and tools for dealing with database abstraction and Object-Relational Mapping written in PHP.</p>
<h1>Doctrine 2</h1>
<p>When we say <em>Doctrine 2</em> it usually refers to Doctrine ORM Project. The ORM sits on top of the database abstraction layer (called DBAL). It also uses Doctrine Common (which provides extensions to core PHP functionality).</p>
<p><strong>Side projects</strong></p>
<p>Then you have <em>side</em> projects dedicated to some DBMS which provide transparent persistence for PHP objects:</p>
<ul>
<li><a href="http://www.doctrine-project.org/projects/mongodb-odm.html" rel="nofollow">MongoDB ODM</a></li>
<li><a href="http://www.doctrine-project.org/projects/couchdb-odm.html" rel="nofollow">CouchDB ODM</a></li>
<li><a href="http://www.doctrine-project.org/projects/phpcr-odm.html" rel="nofollow">PHPCR ODM</a></li>
</ul>
<p><strong>Documentation</strong></p>
<ul>
<li><a href="http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/" rel="nofollow">Doctrine 2 ORM Manual</a></li>
<li><a href="http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/" rel="nofollow">Doctrine 2 DBAL Manual</a></li>
<li><a href="http://docs.doctrine-project.org/projects/doctrine-common/en/latest/" rel="nofollow">Doctrine 2 Common Manual</a></li>
<li><a href="http://groups.google.com/group/doctrine-user" rel="nofollow">Doctrine Users Mailing List</a></li>
<li><a href="https://github.com/doctrine" rel="nofollow">Doctrine on Github</a> (with separate repository for each project)</li>
</ul>
<h1>Doctrine 1</h1>
<p>The first version doesn't have a separate project for the relational mapper and the database abstraction layer. It requires PHP 5.2.3+ and the latest version is 1.2.4.</p>
<ul>
<li><a href="http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/index.html" rel="nofollow">Doctrine 1.2 Manual</a></li>
<li><a href="https://github.com/doctrine/doctrine1" rel="nofollow">Doctrine 1 code on Github</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T11:48:21.780",
"Id": "23473",
"Score": "0",
"Tags": null,
"Title": null
}
|
23473
|
The Doctrine Project is a collection of open source libraries and tools for dealing with database abstraction and Object-Relational Mapping written in PHP.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T11:48:21.780",
"Id": "23474",
"Score": "0",
"Tags": null,
"Title": null
}
|
23474
|
<p><a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="nofollow">Test-driven development</a> (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes a failing automated test case that defines a desired improvement or new function, then produces code to pass that test and finally refactors the new code to remove duplication and to improve its design.</p>
<p>TDD tends to lead to low-coupled, highly-cohesive designs, with no more functionality than necessary to satisfy requirements. The test serves as the first consumer of the new interface, and provides immediate feedback on its clarity and usability. Developers give themselves incentive to write easily testable, stateless, simple modules, all hallmarks of good design according to the <a href="http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29" rel="nofollow">SOLID</a> design principles.</p>
<p>It is one of the practices of <a href="http://en.wikipedia.org/wiki/Extreme_Programming" rel="nofollow">Extreme Programming</a>. It is often said that TDD is not about testing, but rather about design.</p>
<p>Hello World: </p>
<pre><code>def test_hello_world
assert.are_equal "hello world", hello_world
end
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T11:50:23.777",
"Id": "23475",
"Score": "0",
"Tags": null,
"Title": null
}
|
23475
|
Test Driven Development involves writing a failing automated test to specify what is to be built. The test is then made to pass by writing code which satisfies the tested condition. Finally, the code is refactored.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T11:50:23.777",
"Id": "23476",
"Score": "0",
"Tags": null,
"Title": null
}
|
23476
|
<p>Excerpt from the <a href="http://en.wikipedia.org/wiki/Unix" rel="nofollow">Wikipedia page</a>:</p>
<blockquote>
<p>Unix is a multitasking, multi-user computer operating system
originally developed in 1969 by a group of AT&T employees at Bell
Labs. Today, it is a modern OS with many commercial flavors and
licensees. It has also greatly influenced the development of a free
alternative: GNU/Linux.</p>
<p>Unix was originally written in assembly but has since been rewritten
in C. It has been branched many times both commercially and open
source. One popular variant is the BSD variant which originated from
the University of California, Berkeley. It also gave rise to Linux.</p>
</blockquote>
<h2>Notable Variants</h2>
<ul>
<li>Irix (Silicon Graphics)</li>
<li>AIX (IBM)</li>
<li>Solaris (Sun Microsystems)</li>
<li>HP-UX (Hewlett Packard)</li>
</ul>
<p>Unix is officially trademarked as UNIX.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T11:52:28.377",
"Id": "23477",
"Score": "0",
"Tags": null,
"Title": null
}
|
23477
|
<p>I am a young programmer with the ability to learn more. I created a public site where a user can upload multiple pictures at once. The code works successfully and inserts the images into a MySQL database. As I improved the code further by reducing the size of multiple uploaded pictures at once, only one picture was uploaded into the folder and MySQL. Could anyone please help me on this? Is there any style or code to reduce the size of multiple images uploaded by the user?</p>
<p>DS in my code is DIRECTORY_SEPARATOR define in initialize file.</p>
<pre><code>if(isset($_POST['submitImage']))
{
$file = $_FILES['upload'];
$errors = array();
if(empty($file))
{
$errors[] = ' The file could not be empty ';
}
else
{
foreach( $file['name'] as $key => $value )
{
$extensions = array("jpeg","jpg","png");
$file_ext=explode('.',$file['name'][$key]);
$file_ext=end($file_ext);
//$file_ext=strtolower(end(explode('.',$file['name'][$key])));
if(in_array($file_ext,$extensions ) === false)
{
$errors[] = "extension not allowed";
}
else
{
$filetmp = $file['tmp_name'][$key];
$terget_path = SITE_ROOT.'j2reimage'.DS.'image'.DS;
$dat = strftime("%Y-%m-%d %H:%M:%S", time());
if(file_exists($terget_path))
{
//move_uploaded_file( $filetmp, $terget_path.'/'.$file['name'][$key]);
mysql_query("insert into 4j2memberimage values ('', $memmem->id,'{$file['name'][$key]}', '$dat')");
if(move_uploaded_file($filetmp, $terget_path.'/'.$file['name'][$key] ))
{
$exe = explode(".", $file['name'][$key]);
$ext = $exe[1];
$w = 250;
$h = 250;
$target = $terget_path.DS.$file['name'][$key];
$newcopy = SITE_ROOT.'j2reimage'.DS.'reCopy'.DS.$file['name'][$key];
list($w_orig, $h_orig) = getimagesize($target);
$scale_ratio = $w_orig / $h_orig;
if (($w / $h) > $scale_ratio)
{
$w = $h * $scale_ratio;
}
else
{
$h = $w / $scale_ratio;
}
$img = "";
$ext = strtolower($ext);
if ($ext == "gif")
{
$img = imagecreatefromgif($target);
}
else if($ext =="png")
{
$img = imagecreatefrompng($target);
}
else
{
$img = imagecreatefromjpeg($target);
}
$tci = imagecreatetruecolor($w, $h);
imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
if(@imagejpeg($tci, $newcopy, 80))
{
//return true;
$terger_path = $target;
//$terger_path = SITE_ROOT.DS.$this->img_path.DS.$this->filename;
return unlink($terger_path) ? true : false;
}
}
//end of if file_exists
}
else
{
$errors[] = 'Upload extention could not be located';
}
}
//redirect_to('inb.php');
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>In your HTML View you can use this\n<code><file name=\"upload[]\" accept=\"image/*\" multiple></code> <strong>multiple</strong> and <strong>accept</strong> attribute is only available in HTML5 dosen't work in old browsers.</p>\n\n<pre><code><?php\n $files = null;\n $errors = null;\n\n define('IMAGE_TARGET',SITE_ROOT.'j2reimage'.DS.'image');\n\n if(!empty($_POST['submitImage']))\n {\n $files = $_FILES['upload'];\n $errors = array();\n\n if(!empty($files))\n {\n //Move extension list to here you don't need redeclarate variables inside loop\n $valid_extensions = array('jpeg','jpg','png','gif'); \n\n foreach($files as $file)\n {\n\n //Don't use explode for extensions\n //$file_ext = explode('.',$file['name'][$key]);\n //Use pathinfo\n $path_parts = pathinfo($file); \n $file_ext = $path_parts['extension'];\n\n //$file_ext=strtolower(end(explode('.',$file['name'][$key])));\n\n if(in_array($file_ext,$valid_extensions) === false)\n {\n $errors[] = \".$file_ext extension not allowed\";\n }\n else\n {\n $filetmp = $file['tmp_name'][$key];\n\n $dat = strftime(\"%Y-%m-%d %H:%M:%S\", time());\n\n if(file_exists(IMAGE_TARGET.DS.$file['name']))\n {\n //move_uploaded_file( $filetmp, $terget_path.'/'.$file['name'][$key]); \n mysql_query(\"INSERT INTO 4j2memberimage VALUES ('', $memmem->id,'{$file['name']}', '$dat')\"); \n\n //if(move_uploaded_file($filetmp, $terget_path.'/'.$file['name'][$key] ))\n\n //Use copy insteds of move_uploaded_file sometimes you have right problems in some servers.\n\n if(copy($filetmp, IMAGE_TARGET.DS.$file['name'] ))\n { \n $exe = explode(\".\", $file['name']);\n $ext = $exe[1];\n $w = 250;\n $h = 250;\n $target = IMAGE_TARGET.DS.$file['name']; \n $newcopy = IMAGE_TARGET.DS.'thumb_'.DS.$file['name'];\n\n list($w_orig, $h_orig) = getimagesize($target);\n $scale_ratio = $w_orig / $h_orig;\n\n if (($w / $h) > $scale_ratio)\n {\n $w = $h * $scale_ratio;\n }\n else\n {\n $h = $w / $scale_ratio;\n }\n\n $img = '';\n $ext = strtolower($ext);\n\n switch($ext) {\n case 'gif':\n $img = imagecreatefromgif($target); \n break;\n case 'png':\n $img = imagecreatefrompng($target); \n break;\n case 'jpeg':\n case 'jpg':\n $img = imagecreatefromjpeg($target);\n break; \n }\n\n $tci = imagecreatetruecolor($w, $h);\n imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);\n\n if(@imagejpeg($tci, $newcopy, 80))\n {\n //return true;\n $target_path = $target; \n //$terger_path = SITE_ROOT.DS.$this->img_path.DS.$this->filename;\n file_put_contents($target_path,$img);\n //return unlink($target_path) ? true : false; \n }\n }\n //end of if file_exists \n }\n else\n {\n $errors[] = 'Upload extention could not be located'; \n }\n }\n //redirect_to('inb.php'); \n }//foreach \n }\n else\n {\n $errors[] = ' The file could not be empty '; \n }//if\n }//if\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T21:07:59.050",
"Id": "30011",
"ParentId": "23481",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T12:59:29.370",
"Id": "23481",
"Score": "2",
"Tags": [
"php"
],
"Title": "Reduce size of multiple uploaded images"
}
|
23481
|
<p>The working hours are saved in Database like</p>
<pre><code>{"1" : "11:00 - 14:30", "2" : "17:30 - 23:00"}
</code></pre>
<p>Now i wrote a function like, which test is the shop is opened or close at the moment. Can someone please suggest if there is a better way to do this? And how i can check if the timing are like</p>
<pre><code>{"1" : "11:00 - 14:30", "2" : "17:30 - 02:00"}
</code></pre>
<p>Where <code>02:00</code> o clock is next day's time.
here is my funciton.</p>
<pre><code>$working_hours = json_decode('{"1" : "11:00 - 14:30", "2" : "14:39 - 23:00"}');
$is_open = false;
$time = time();
foreach ($working_hours as $key=>$value)
{
$working_hour = explode(" - ", $value);
$from = strtotime($working_hour[0]);
$to = strtotime($working_hour[1]);
if ($time >= $from && $time <= $to)
{
$is_open = true;
break;
}
}
echo "\n***********************";
echo "\n". date("d.m.Y H:i", $time);
if($is_open)
echo "\nOpend";
else
echo "\nClosed";
echo "\n***********************";
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:07:14.997",
"Id": "36256",
"Score": "0",
"body": "OK, you've convinced me that NoSQL is a really bad idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T08:30:11.767",
"Id": "36288",
"Score": "0",
"body": "**how it is bad idea :)**\nAnd how I can do it better in Many to Many relations"
}
] |
[
{
"body": "<p>If 02:00 consider the next day, then you'll need to decide on some cut-off for what's considered 'today' and what's considered 'tomorrow'.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T15:31:41.147",
"Id": "36234",
"Score": "0",
"body": "Yes i think if $to < $from then $to should be considered as tomorrow."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T14:29:54.887",
"Id": "23486",
"ParentId": "23482",
"Score": "1"
}
},
{
"body": "<p>I would do some preparation, that will convert this</p>\n\n<pre><code>{\"1\" : \"11:00 - 14:30\", \"2\" : \"17:30 - 02:00\"}\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>{\"1\" : \"00:00 - 02:00\", \"2\" : \"11:00 - 14:30\", \"3\" : \"17:30 - 23:59\"}\n</code></pre>\n\n<p>E.g. this way (code wasnt run or tested):</p>\n\n<pre><code>$working_hours = json_decode('{\"1\" : \"11:00 - 14:30\", \"2\" : \"14:39 - 23:00\"}');\n$last_key = count($working_hours); // make it better if keys are more random\n\n// parse to\\from as decimal hour values, there could be a better way\nlist($from, $to) = explode(\" - \", $working_hours[$last_key]);\n$from_arr = explode($from,\":\");\n$from_dec = $from_arr[0] + $from_arr[1]/60;\n$to_arr = explode($to,\":\");\n$to_dec = $to_arr[0] + $to_arr[1]/60;\n\n// if the last period has \"strange\" order\nif ($to_dec < $from_dec)\n{\n // cut the last period with 24:00\n $working_hours[$last_key] = $from_arr[0].\":\".$from_arr[1].\" - 23:59\";\n // add new period for early morning\n array_unshift($working_hours, \"00:00 - \".$to_arr[0].\":\".$to_arr[1]); // you dont have to push it to 1st position, can also add it to the end of array\n}\n\n$is_open = false;\n$time = time();\n... // your code follows\n</code></pre>\n\n<p>Anyway looks even more ugly. But i'm affraid there is no way to handle wrond data structures a pretty way ))</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T22:26:43.010",
"Id": "23593",
"ParentId": "23482",
"Score": "1"
}
},
{
"body": "<p>Easiest solution (to the time problem) is to change your logic (just a tiny bit).</p>\n\n<blockquote>\n<pre><code>if ($time >= $from && $time <= $to)\n</code></pre>\n</blockquote>\n\n<p>To:</p>\n\n<pre><code>if (($to > $from && ($time >= $from && $time <= $to)) || \n ($to < $from && ($time >= $from || $time <= $to)))\n</code></pre>\n\n<p>You just change whether to restrict the time to be between the two, or to restrict it to be greater than one or less than the other in the case that the <code>$to</code> time is less than <code>$from</code>.</p>\n\n<hr>\n\n<p>As far as cleaning up your code: this is about as idiomatic as <a href=\"/questions/tagged/php\" class=\"post-tag\" title=\"show questions tagged 'php'\" rel=\"tag\">php</a> will get. Though you should definitely extract this to a function as appropriate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-23T18:21:11.063",
"Id": "105518",
"ParentId": "23482",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T13:07:18.650",
"Id": "23482",
"Score": "4",
"Tags": [
"php",
"datetime"
],
"Title": "Check if the shop is open or closed"
}
|
23482
|
<p>I have three functions (out of a medium 2 digit number of functions) which use up 80% of CPU time, so I kind of wonder if there are points for optimization that I am missing.</p>
<p>Function 1, Extracting a bilinear interpolated point from a width * height float value image:</p>
<pre><code>float ExtractBilinear(float* image, int w, int h, float x, float y)
{
int x0 = (int)floor(x);
int y0 = (int)floor(y);
int x1 = x0 + 1;
int y1 = y0 + 1;
float c00, c01, c11, c10;
c00 = c01 = c11 = c10 = 0.0f;
if(x0 < -1 || x1 > w || y0 < -1 || y1 > h)
{
return 0.0f;
}
if(x0<0)
{
c00 = 0.0f;
c01 = 0.0f;
}
else
{
if(y0<0)
{
c00 = 0.0f;
}
else
{
c00 = image[y0*w + x0];
}
if(y1 < h)
{
c01 = image[y1*w + x0];
}
else
{
c01 = 0.0f;
}
}
if(x1 < w)
{
if(y0<0)
{
c10 = 0.0f;
}
else
{
c10 = image[y0*w + x1];
}
if(y1 < h)
{
c11 = image[y1*w + x1];
}
else
{
c11 = 0.0f;
}
}
else
{
c10 = 0.0f;
c11 = 0.0f;
}
float c0 = c10 * (x - x0) + c00 * (x1 - x);
float c1 = c11 * (x - x0) + c01 * (x1 - x);
return c1 * (y - y0) + c0 * (y1 - y);
}
</code></pre>
<p>Function 2: Taking 2 float samples of data (one is image data, one is simulated data), and calculating the sum of squared differences error, with a scalar 'a' to minimize the error as much as possible. SampleX is the size of the input, compX the size of the output, and offX is deprecated, and always 0 (due to legacy code I am keeping it in there).</p>
<pre><code>float PatternMatcher::GetSADFloatRel(float* sample, float* compared, int sampleX, int compX, int offX)
{
if (sampleX != compX)
{
return 50000.0f;
}
float result = 0;
float* pTemp1 = sample;
float* pTemp2 = compared + offX;
float w1 = 0.0f;
float w2 = 0.0f;
float w3 = 0.0f;
for(int j = 0; j < sampleX; j ++)
{
w1 += pTemp1[j] * pTemp1[j];
w2 += pTemp1[j] * pTemp2[j];
w3 += pTemp2[j] * pTemp2[j];
}
float a = w2 / w3;
result = w3 * a * a - 2 * w2 * a + w1;
return result / sampleX;
}
</code></pre>
<p>Function 3: a 2 dimensional convolution over the image with rotations being applied. This is working multi-threaded, and is, actually, the most CPU intensive function in our whole algorithm. </p>
<p><code>Input</code>: image is the original float image. </p>
<p><code>convolution_image</code> holds the highest result for that particular thread (I start #CPU Cores - 2 threads, and each thread has its own copy of <code>convolution_image</code>, <code>r_map_image</code> and <code>orientation_map_image</code>). </p>
<p><code>r_map_image</code> saves the currently found radius at that position (with highest convolution value). <code>orientation_map_image</code> saves the angle, and goes from 0..180. </p>
<p><code>middleReflex</code> is a pre-calculated map of where the image has to be invalidated due to unavoidable reflexes happening in the optical system. </p>
<p><code>kernel1DAll</code> holds the pre-calculated sample of what an area has to look like to be used later in the algorithm. </p>
<p><code>startMin</code>, <code>startMax</code> hold the angles in which the calculation for the current thread should run (for example, with 3 threads, 0..60, 61..120, 121..180) </p>
<p><code>outer</code> is a Circle, containing a position (2D coordinates), and a radius, and every point outside that circle is completely unimportant and should be ignored.</p>
<pre><code>void rotateImageConvolution(float* image, float* convolution_image, unsigned char* r_map_image, unsigned char* orientation_map_image, unsigned char* middleReflex, float* kernel1DAll, int startMin, int startMax, Circle outer)
{
const int imgsize = Width*Height;
printf("Started thread from %d to %d\n", startMin, startMax);
float half_w = Width/2.0f;
float half_h = Height/2.0f;
const int radius = int(sqrt(half_w*half_w + half_h*half_h) + 0.5f);
const int RotateW = 2*radius + 1;
const int s = RotateW * RotateW; //* nAngles;
float* rotate_image = (float*)malloc(s*sizeof(float));
float* summingup_image = (float*)malloc(s*sizeof(float));
for(int a = startMin ; a<startMax ; a++)
{
float theta = (float)(PI*a/nAngles);
const float costheta = cos(theta);
const float sintheta = sin(theta);
Cos[a] = costheta;
Sin[a] = sintheta;
for(int j = 0; j<RotateW; j++)
{
int y = j - radius;
float ysina = y*sintheta;
float ycosa = y*costheta;
for(int i = 0; i<RotateW; i++)
{
int x = i - radius;
float xf = x*costheta - ysina + Width/2;
float yf = x*sintheta + ycosa + Height/2;
rotate_image[j*RotateW + i] = ExtractBilinear(image, Width, Height, xf, yf);
}
}
for(int j = 0; j<RotateW; j++)
{
int yoff = j*RotateW;
float subSum = 0.0f;
int num = 0;
for(int kx=0; kx<=half_Integ_L && kx < RotateW; kx++)
{
subSum += rotate_image[yoff + kx];
num++;
}
summingup_image[yoff] = subSum/num;
for(int i=1; i<RotateW; i++)
{
float sum = subSum;
int istart = i - half_Integ_L;
int iend = i + half_Integ_L;
if(istart>=0)
{
num--;
subSum -= rotate_image[yoff + istart];
}
if(iend<RotateW)
{
num++;
float endv = rotate_image[yoff + iend];
sum += endv;
subSum += endv;
}
summingup_image[yoff+i] = sum/num;
}
}
for(int i=0;i<imgsize;i++)
{
if(middleReflex[i] == 0xFF)
{
convolution_image[i] = 0.0f;
r_map_image[i] = 10;
orientation_map_image[i] = 0;
continue;
}
int x = i%Width - Width/2;
int y = i/Width - Height/2;
float d = sqrt((i/Width - outer.y) * (i/Width - outer.y) + (i%Width - outer.x) * (i%Width - outer.x));
if(d >= outer.r-16)
{
convolution_image[i] = 0.0f;
r_map_image[i] = 10;
orientation_map_image[i] = 0;
continue;
}
int xx = (int)floor(x*costheta + y*sintheta + radius + 0.5f);
int yy = (int)floor(-x*sintheta + y*costheta + radius + 0.5f);
float I[KWIDTH];
for(int ky=-half_MaxK; ky<=half_MaxK; ky++)
{
int dy = yy + ky;
int ii = ky+half_MaxK;
if(dy >= 0 && xx >=0 && dy < RotateW && xx < RotateW)
{
I[ii] = summingup_image[dy*RotateW + xx];
}
else I[ii] = 0.0f;
}
for(int ik = NKernel-1; ik>=0; ik--)
{
float *pKernel = kernel1DAll + ik*KWIDTH;
float convrst = 0.0f;
int r0 = ik + half_MinK;
for(int x0 = -r0; x0<=r0; x0++ )
{
int ii = x0 + half_MaxK;
convrst += (I[ii]*pKernel[KWIDTH-ii-1]);
}
if(convolution_image[i] <= convrst)
{
convolution_image[i] = convrst;
r_map_image[i] = (unsigned char)r0;
orientation_map_image[i] = (unsigned char)a;
}
}
}
}
free(summingup_image);
free(rotate_image);
}
</code></pre>
<p>Am I doing something horribly wrong with this code with regards to performance? The code does what it is supposed to do, but unless running on a high-end system, it can take really long to finish. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T10:17:01.787",
"Id": "47040",
"Score": "0",
"body": "From a language use standpoint, things like `if (cond) var = thing; else var = other_thing;` can be shortened using the ternary operator, making your code shorter and scan better in my eyes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T20:16:11.140",
"Id": "47342",
"Score": "0",
"body": "Is `float` faster than `double` on your platform? On my Intel Mac `double` can be much quicker. Your arrays etc may need to be in `float` for space reasons, but perhaps the functions can use `double` internally."
}
] |
[
{
"body": "<p>How often is the third function called? </p>\n\n<p>The allocation of the images could be a bottleneck. You could try to reuse the memory for the images by passing them to the function instead of reallocating and freeing them every time.</p>\n\n<p>Also things like <code>Width/2.0f</code>, <code>Height/2.0f</code> and <code>PI*a/nAngles</code> should not be evaluated every time they are needed if they are not changed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T09:25:40.507",
"Id": "29716",
"ParentId": "23485",
"Score": "2"
}
},
{
"body": "<p>Pre-computing things is useful when it is possible. As some one has already said in your case may be advisable to precomunte things as Width/2. But, if Width is defined through a \"Define\" your compiler shall be able to do this optimization by itself.</p>\n\n<p>But, I believe that the problem in your code is mainly another one. You have a first loop between startMin and StartMax and than another nested loop from o to imageSize (which i expect being a large number). And this ends up to be the most time expensive part of your code.</p>\n\n<p>There you have other two loops such as:\n<code>for(int ik = NKernel-1; ik>=0; ik--)</code>\nor\n<code>for(int ky=-half_MaxK; ky<=half_MaxK; ky++)</code></p>\n\n<p>This you may think that is an \"optimized\" loop, but actually it isn't, because <strong>the compiler is (generally) designed to be really good at optimizing loops from 0 to N</strong>.</p>\n\n<p>Thus you can have significant improvement. Write your two inner loops in such way and then just compute your index (ik and ky) by subtracting an offset.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T14:00:01.687",
"Id": "29735",
"ParentId": "23485",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "29735",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T13:39:07.563",
"Id": "23485",
"Score": "3",
"Tags": [
"c++",
"optimization",
"performance"
],
"Title": "Not sure if I missed some obvious CPU brakes"
}
|
23485
|
<p>I wrote <a href="http://jsfiddle.net/abitdodgy/7rFb6/6/" rel="nofollow noreferrer">this code</a> to allow users to select multiple images, and each image can be selected multiple times. It feels convoluted, though, and prone to errors, such as forgetting to do something associated with an action.</p>
<p>How can I make it more object-oriented or reusable?</p>
<pre><code>var images = [];
function removeImage(image) {
while((index = images.indexOf(image)) !== -1) {
images.splice(index, 1);
}
}
function decrementImage(image) {
var index = images.indexOf(image);
images.splice(index, 1);
}
function countOccurrences(image) {
var occurrences = 0;
for (i = 0; i < images.length; i++) {
if (images[i] === image) occurrences += 1
}
return occurrences;
}
$('#image-container').on('click', 'img', function () {
var image = $(this),
source = image.attr('src');
image.data('selected', true).addClass('selected').siblings('.controls').show();
images.push(source);
image.siblings('span.count').html(countOccurrences(source));
});
$('#image-container').on('mouseleave', '.image-wrapper', function () {
$(this).children('.controls').hide();
});
$('#image-container').on('mouseenter', 'img', function () {
var image = $(this),
controls = image.siblings('.controls');
if (image.data('selected') === true) {
controls.show();
}
});
$('#image-container').on('click', '[data-action="remove"]', function () {
var controls = $(this).parents('div.controls'),
image = controls.siblings('img')
source = image.attr('src');
image.data('selected', false).removeClass('selected');
controls.hide();
removeImage(source);
image.siblings('span.count').html(countOccurrences(source));
});
$('#image-container').on('click', '[data-action="increment"]', function () {
var image = $(this).parents('.controls').siblings('img'),
source = image.attr('src');
images.push(source);
image.siblings('span.count').html(countOccurrences(source));
});
$('#image-container').on('click', '[data-action="decrement"]', function () {
var image = $(this).parents('.controls').siblings('img'),
source = image.attr('src');
decrementImage(source);
var count = countOccurrences(source)
image.siblings('span.count').html(count);
if (count < 1) {
image.siblings('.controls').hide();
image.data('selected', false).removeClass('selected');
}
});
$(document).click(function () {
console.log(images);
});
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><div id="image-container">
<div class="image-wrapper">
<img src="http://i.imgur.com/nIZvrpS.jpg" width="100" height="100" data-selected="false" />
<div class="controls">
<a href="#" data-action="remove">Remove</a>
<a href="#" data-action="increment">Increment</a>
<a href="#" data-action="decrement">Decrement</a>
</div>
<span class="count">0</span>
</div>
<div class="image-wrapper">
<img src="http://i.imgur.com/lUaIBXc.jpg" width="100" height="100" data-selected="false" />
<div class="controls">
<a href="#" data-action="remove">Remove</a>
<a href="#" data-action="increment">Increment</a>
<a href="#" data-action="decrement">Decrement</a>
</div>
<span class="count">0</span>
</div>
<div class="image-wrapper">
<img src="http://i.imgur.com/DQzWfza.jpg?1" width="100" height="100" data-selected="false" />
<div class="controls">
<a href="#" data-action="remove">Remove</a>
<a href="#" data-action="increment">Increment</a>
<a href="#" data-action="decrement">Decrement</a>
</div>
<span class="count">0</span>
</div>
</div>
</code></pre>
|
[] |
[
{
"body": "<p>Your code is actually very good. </p>\n\n<p>I'd advice against using OOP there. It's an overused tool which, when not necessary, only makes things more complex. JavaScript works very well without it. I'd recommend a more functional style. So, if you want to make your code more reusable, you could abstract your functions to work with any kind of collection. You could also use existing functions to define others:</p>\n\n<pre><code>function removeFirst(array,obj) {\n array.splice(array.indexOf(obj), 1);\n};\nfunction without(array,obj){\n return array.filter(function(element){\n return element !== obj;\n });\n};\nfunction count(array,obj){\n return array.length - without(array,obj).length;\n};\n</code></pre>\n\n<p>Then, counting an image would be, for example:</p>\n\n<pre><code>count(images,my_image);\n</code></pre>\n\n<p>But before I'd suggest checking some functional JavaScript libraries such as <code>underscore.js</code>, which already implement similar functions in very clever manners. Using them in your daily code will make it smaller, simpler, more readable and robust.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T17:54:55.843",
"Id": "23496",
"ParentId": "23489",
"Score": "2"
}
},
{
"body": "<p>Funny. I just answered a Facebook interview test question asking a similar thing. I'm out of time to cater it exactly to your question, but thought you might want to see it. Here was my answer:</p>\n\n<pre><code><html>\n<head>\n <script src=\"/assets/js/custom.js\"></script>\n</head>\n<body>\n <div class=\"content\">\n <img src=\"\" class=\"image imageUser userCurrent\" />\n <img src=\"\" class=\"image imageGroup\" />\n </div>\n <div class=\"siderbar\">\n <img src=\"\" class=\"image imageUser userGroup\" />\n </div>\n</body>\n</code></pre>\n\n<p></p>\n\n<p>With this script:</p>\n\n<pre><code>$(function() {\nfunction initImageControls() {\n var controlSettings = { \"options\": [ \n {\"Edit\",\"edit\"},\n {\"View\",\"view\"},\n ...\n {\"Delete\",\"delete\"}\n ] },\n controls = $( \"<div>\" )\n .addClass( \"controls\" )\n .addClass( \"controls24\" )\n .css(\"display\", \"none\");\n $.each(controlSettings.options, function(value){\n $( \"<div>\" )\n .addClass( \"control\" )\n .addClass( \"control-\" + value[1] )\n .data( \"value\", value[1] )\n .appendTo( controls );\n });\n $( \".control\" )\n .on(\"click\", { \"imageAction\": $(this).data(\"value\"), \"target\": $(this).parent().data(\"target\") }, imageControl ); // passing action and object to perform it on\n\n $( \"body\" ).append(controls);\n\n}\nfunction imageControl(event) {\n var target = event.data.target,\n imageAction = event.data.imageAction;\n ...do whatever...\n}\n$( \".image\" ) {\n .on({\n click: function(){\n showFullImage($(this));\n },\n mouseenter: function(){\n var $this = $(this),\n offset = $this. offset(),\n target = $this.data(\"id\");\n $(\".controls\")\n .css( \"right\", offset.left + $this.width() )\n .css( \"bottom\", offset.top + $this.height() )\n .data(\"target\",target)\n .show();\n }\n mouseleave: function(){\n $(\".controls\")\n .data(\"target\",null)\n .hide();\n }\n });\n}\n});\n</code></pre>\n\n<p>and this CSS:</p>\n\n<pre><code>@import \"config.scss\";\n@import \"icons24x24/*.png\";\n/* ... */\n\n/***** controls *****/\n.controls { \nposition: absolute; }\n.control { \n @include ir; /* mixin to replace text with image - mixins included via config */\n float: left; }\n.controls24 .control { /* separating this out allows micro and macro control sets */\n width: 24px;\n height: 24px;\n margin-left: 2px; }\n\n.control-edit { @include icons24x24-sprite(icon-edit); // sprites generated via Compass\n.control-edit:hover { @include icons24x24-sprite(icon-edit-on);\n.control-edit { @include icons24x24-sprite(icon-view);\n.control-edit:hover { @include icons24x24-sprite(icon-view-on);\n/* ... */\n.control-edit { @include icons24x24-sprite(icon-delete);\n.control-edit:hover { @include icons24x24-sprite(icon-delete-on);\n</code></pre>\n\n<p>I think it's much better to remove all that excess code from the core HTML. I know this answer may create more questions than answers, but it's the direction you should take. Let me know if you have questions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T18:32:58.397",
"Id": "27913",
"ParentId": "23489",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23496",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T15:50:01.700",
"Id": "23489",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"jquery",
"image"
],
"Title": "Selecting multiple images"
}
|
23489
|
<p>I have this little utility/helper which serializes a form into a javaScript object.</p>
<pre><code>$.fn.serializeObject = function(fn) {
var o = {},
a = this.serializeArray(),
that;
$.each(a, function() {
that = this;
if($.isFunction(fn)){
that = fn(that.name, that.value);
}
if(o[this.name] !== undefined) {
val = that.value || '';
if(!o[that.name].push) {
o[that.name] = [o[that.name]];
}
o[that.name].push(that.value);
} else {
o[that.name] = that.value;
}
});
return o;
};
</code></pre>
<p>A typical usage of this plugin will be:</p>
<pre><code>someNameSpace = {
//...
processForm: function (form) {
return JSON.stringify(form.serializeObject(function (key, val) {
return {
name: key,
value: encodeURIComponent(val)
};
}));
}
//...
};
</code></pre>
<p>Any suggestions on how to improve this piece of code?</p>
<ul>
<li>Maybe improve performance</li>
<li>Maybe its the API-Design</li>
<li>Code readability..</li>
</ul>
<p>See <a href="https://gist.github.com/adardesign/5091258#file-jquery-serializeobject-js" rel="nofollow">original gist</a></p>
|
[] |
[
{
"body": "<p>First of all, I'm barely even sure what's going on here:</p>\n\n<pre><code>if(o[this.name] !== undefined) {\n val = that.value || '';\n if(!o[that.name].push) {\n o[that.name] = [o[that.name]];\n }\n o[that.name].push(that.value);\n} else {\n o[that.name] = that.value;\n}\n</code></pre>\n\n<p>All the <code>this</code>/<code>that</code> is pretty confusing to look at, especially with all the square brackets mixed in. More descriptive names would help immensely.</p>\n\n<p>But also, you check for <code>o[this.name]</code> but then you define <code>o[that.name]</code>. So if my <code>fn</code> function makes all the names identical, it won't work. For instance, if I have 3 inputs (a = 1, b = 2, and c = 3) in a form, and I supply a <code>fn</code> like so:</p>\n\n<pre><code>$(form).serializeObject(function (name, value) {\n return {\n name: \"x\",\n value: value\n };\n});\n</code></pre>\n\n<p>I get:</p>\n\n<pre><code>{ \"x\": 3 }\n</code></pre>\n\n<p>instead of the expected <code>x: [1, 2, 3]</code></p>\n\n<p>It'd be much easier to just let me manipulate the objects directly. You wouldn't have any this/that to bother with, and I could simplify my <code>fn</code> to</p>\n\n<pre><code>$(form).serializeObject(function (object) {\n object.name = \"x\";\n});\n</code></pre>\n\n<p>No need to build and return a new object.</p>\n\n<p>Other things I noticed:</p>\n\n<ul>\n<li><p>Don't use <code>... === undefined</code>. Unfortunately, <code>undefined</code> is not a reserved word, meaning that <code>undefined</code> <em>can be defined</em> in some JS runtimes. So if somewhere, some joker has written <code>undefined = 23;</code> it'll break your code. Use <code>typeof x === 'undefined'</code> instead.</p></li>\n<li><p>Don't use jQuery to do a simple loop. A <code>for</code> loop works quite well, with less overhead and no context-switching. </p></li>\n<li><p>Don't use jQuery just to check it something's function. Use <code>typeof x === 'function'</code> instead.</p></li>\n<li><p>Don't use <code>x.push</code> to check if something's an array. Use <code>x instanceof Array</code>. For all you know, <code>x.push</code> could mean anything. (User <a href=\"https://codereview.stackexchange.com/users/22820/winner-joiner\">winner-joiner</a> adds: watch out for frame/iframe situations <a href=\"https://stackoverflow.com/questions/6473273/why-are-myarray-instanceof-array-and-myarray-constructor-array-both-false-wh\">where <code>instanceof</code> doesn't work</a>)</p></li>\n<li><p>You have a <code>val</code> variable which is 1) not used, 2) not declared (thus implicitly global!), and 3) if it were used, it'd mess up. I my <code>fn</code> returns a value of, say, <code>false</code> on purpose, it'd become an empty string, because <code>false || '' => ''</code>. Don't do anything clever with the values; especially not <em>after</em> the user's <code>fn</code> may have changed them. Assume the values are correct, regardless of what they are.</p></li>\n</ul>\n\n<p>And again: Use descriptive variable names. It took me quite a while to figure out your code.</p>\n\n<p>I'd write it like this:</p>\n\n<pre><code>$.fn.serializeObject = function (decorator) {\n var source = this.serializeArray(),\n serialized = {},\n i, l, object;\n\n for( i = 0, l = source.length ; i < l ; i++ ) {\n object = source[i];\n\n if( typeof decorator === 'function' ) {\n decorator(object);\n }\n\n if( serialized.hasOwnProperty(object.name) ) {\n if( !(serialized[object.name] instanceof Array) ) {\n serialized[object.name] = [ serialized[object.name] ];\n }\n serialized[object.name].push(object.value);\n } else {\n serialized[object.name] = object.value;\n }\n }\n return serialized;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T14:00:56.757",
"Id": "36311",
"Score": "0",
"body": "Thanks so much! really helpful! I will update the gist according to your recommendations and would you mind to please take a second look at it?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T22:30:37.483",
"Id": "23510",
"ParentId": "23491",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23510",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T16:20:17.497",
"Id": "23491",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"api",
"serialization"
],
"Title": "Object serializer"
}
|
23491
|
<p>I've never had a serious attempt at writing an encryption algorithm before, and haven't read much on the subject. I have tried to write an encryption algorithm (of sorts), I would just like to see if anyone thinks it's any good. (Obviously, it's not going to be comparable to those actually used, given that it's a first attempt)</p>
<p>Without further adieu:</p>
<pre><code>def encode(string, giveUserKey = False, doubleEncode = True):
encoded = [] #Numbers representing encoded characters
keys = [] #Key numbers to unlonk code
fakes = [] #Which items in "encoded" are fake
#All of these are stored in a file
if giveUserKey:
userkey = random.randrange(2 ** 10, 2 ** 16)
# Key given to the user, entered during decryption for confirmation
# Could change range for greater security
else:
userkey = 1
for char in string:
ordChar = ord(char)
key = random.randrange(sys.maxsize)
encoded.append(hex((ordChar + key) * userkey))
keys.append(hex(key))
if random.randrange(fakeRate) == 0:
fake = hex(random.randrange(sys.maxsize) * userkey)
encoded.append(fake)
fakes.append(fake)
if doubleEncode:
encoded = [string.encode() for string in encoded]
keys = [string.encode() for string in keys]
fakes = [string.encode() for string in fakes]
hashValue = hex(hash("".join([str(obj) for obj in encoded + keys + fakes]))).encode()
return encoded, keys, hashValue, fakes, userkey
def decode(encoded, keys, hashValue, fakes, userkey = 1):
if hash("".join([str(obj) for obj in encoded + keys + fakes])) != eval(hashValue):
#File has been tampered with, possibly attempted reverse-engineering
return "ERROR"
for fake in fakes:
encoded.remove(fake)
decoded = ""
for i in range(len(keys)):
j = eval(encoded[i]) / userkey
decoded += chr(int(j - eval(keys[i])))
return decoded
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T16:49:41.997",
"Id": "36238",
"Score": "0",
"body": "usually an encryption algo takes input `data` and a `key`(private/symmetric) then outputs `cipher`. What's with `fakes` and `keys` in your case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T16:53:09.137",
"Id": "36239",
"Score": "0",
"body": "\"fakes\" are fake bits of data inserted in to the code. \"keys\" are the keys from the file used to determine what the characters should actually be."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T16:55:52.487",
"Id": "36240",
"Score": "0",
"body": "If two parties say `A` & `B`, then isn't it necessary to exchange these `fakes`, `keys` along with actual `cipher` and `Key`(public/symmetric)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T17:01:12.870",
"Id": "36241",
"Score": "0",
"body": "I don't quite know what you mean. fakes and keys are exchanged in that they are written in to the file which is exchanged. (There is then \"userkey\" which is not written in to the file. It can be specified by the encryptor whether this is needed. It is then told to them and needs to be entered for decryption)."
}
] |
[
{
"body": "<p>Firstly, your encryption is useless. Just run this one line of python code:</p>\n\n<pre><code>print reduce(fractions.gcd, map(eval, encoded))\n</code></pre>\n\n<p>And it will tell you what your user key is (with a pretty high probability). </p>\n\n<p>Your algorithm is really obfuscation, not encrytion. Encryption is designed so that even if you know the algorithm, but not the key, you can't decryt the message. But your algorithm is basically designed to make it less obvious what the parts mean, not make it hard to decrypt without the key. As demonstrated, retrieving the key is trivial anyways. </p>\n\n<pre><code>def encode(string, giveUserKey = False, doubleEncode = True):\n</code></pre>\n\n<p>Python convention is lowercase_with_underscores for local names</p>\n\n<pre><code> encoded = [] #Numbers representing encoded characters\n keys = [] #Key numbers to unlonk code\n fakes = [] #Which items in \"encoded\" are fake\n #All of these are stored in a file\n\n if giveUserKey:\n userkey = random.randrange(2 ** 10, 2 ** 16)\n # Key given to the user, entered during decryption for confirmation\n # Could change range for greater security\n</code></pre>\n\n<p>Why isn't the key a parameter?</p>\n\n<pre><code> else:\n userkey = 1\n\n for char in string:\n ordChar = ord(char)\n key = random.randrange(sys.maxsize)\n encoded.append(hex((ordChar + key) * userkey))\n keys.append(hex(key))\n</code></pre>\n\n<p>These just aren't keys. Don't call them that.</p>\n\n<pre><code> if random.randrange(fakeRate) == 0:\n fake = hex(random.randrange(sys.maxsize) * userkey)\n encoded.append(fake)\n fakes.append(fake)\n\n if doubleEncode:\n encoded = [string.encode() for string in encoded]\n keys = [string.encode() for string in keys]\n fakes = [string.encode() for string in fakes]\n</code></pre>\n\n<p>Since these are all hex strings, why in the world are you encoding them?</p>\n\n<pre><code> hashValue = hex(hash(\"\".join([str(obj) for obj in encoded + keys + fakes]))).encode()\n\n return encoded, keys, hashValue, fakes, userkey\n\ndef decode(encoded, keys, hashValue, fakes, userkey = 1):\n if hash(\"\".join([str(obj) for obj in encoded + keys + fakes])) != eval(hashValue):\n #File has been tampered with, possibly attempted reverse-engineering\n return \"ERROR\"\n</code></pre>\n\n<p>Do not report errors by return value, use exceptions.</p>\n\n<pre><code> for fake in fakes:\n encoded.remove(fake)\n</code></pre>\n\n<p>What if coincidentally one of the fakes looks just like one of the data segments?</p>\n\n<pre><code> decoded = \"\"\n\n for i in range(len(keys)):\n</code></pre>\n\n<p>Use <code>zip</code> to iterate over lists in parallel</p>\n\n<pre><code> j = eval(encoded[i]) / userkey\n</code></pre>\n\n<p>Using <code>eval</code> is considered a bad idea. It'll execute any python code passed to it and that could be dangerous.</p>\n\n<pre><code> decoded += chr(int(j - eval(keys[i])))\n</code></pre>\n\n<p>It's better to append strings into a list and join them.</p>\n\n<pre><code> return decoded\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:20:47.527",
"Id": "23506",
"ParentId": "23492",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23506",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T16:42:35.983",
"Id": "23492",
"Score": "4",
"Tags": [
"python",
"algorithm"
],
"Title": "Is this a good encryption algorithm?"
}
|
23492
|
<p>I have a files search function that iterates over a given directory until a given depth is reached and returns the found files. I did this via the <em>Enumerate</em> methods of the Directory class and yield return the results. Since it's very likely that I hit a directory that I can't access (e.g. system directories) or generate a too long path (if the depth is large), I have to catch the exceptions from these cases. However since I can't use <code>yield</code> in try/catch statements, I find my code pretty bloated, because I have to seperate the critical method calls from the rest.</p>
<p>Is there a better/shorter way to do this, or are there best practices for that case?</p>
<pre><code>private IEnumerable<string> SearchSubdirs(string currentDir, int currentDepth) {
IEnumerable<string> exeFiles;
try {
exeFiles = Directory.EnumerateFiles(currentDir, "*.exe");
}
catch (UnauthorizedAccessException uae) {
Debug.WriteLine(uae.Message);
yield break;
}
catch (PathTooLongException ptle) {
Debug.WriteLine(ptle.Message);
yield break;
}
foreach (string currentFile in exeFiles) {
// Ignore unistaller *.exe files
if (currentFile.IndexOf("unins", 0, StringComparison.CurrentCultureIgnoreCase) == -1) {
yield return currentFile;
}
}
if (currentDepth < maxDepth) {
IEnumerable<string> subDirectories;
currentDepth++;
try {
subDirectories = Directory.EnumerateDirectories(currentDir);
}
catch (UnauthorizedAccessException uae) {
Debug.WriteLine(uae.Message);
yield break;
}
catch (PathTooLongException ptle) {
Debug.WriteLine(ptle.Message);
yield break;
}
foreach (string subDir in subDirectories) {
foreach (string file in SearchSubdirs(subDir, currentDepth)) {
yield return file;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T17:39:35.867",
"Id": "36243",
"Score": "1",
"body": "http://msdn.microsoft.com/en-us/library/bb513869.aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T18:43:33.687",
"Id": "36247",
"Score": "1",
"body": "http://stackoverflow.com/questions/1393178/unauthorizedaccessexception-cannot-resolve-directory-getfiles-failure"
}
] |
[
{
"body": "<p>I would use Linq methods to simplify the code. Also I've extracted 2 methods to simplify the main method. And please rename <code>GetFilesWeAreLookingFor</code> to whatever your find appropriate :).</p>\n\n<pre><code>private static IEnumerable<string> GetFilesWeAreLookingFor(string currentDir)\n{\n try\n {\n return Directory.EnumerateFiles(currentDir, \"*.exe\")\n .Where(fileName => fileName.IndexOf(\"unins\", 0, StringComparison.CurrentCultureIgnoreCase) == -1);\n }\n catch (UnauthorizedAccessException uae)\n {\n Debug.WriteLine(uae.Message);\n }\n catch (PathTooLongException ptle)\n {\n Debug.WriteLine(ptle.Message);\n }\n return Enumerable.Empty<string>();\n}\n\nprivate IEnumerable<string> GetNestedFiles(string currentDir, int nestedDepth)\n{\n try\n {\n return Directory.EnumerateDirectories(currentDir)\n .SelectMany(subDirectory => SearchSubdirs(subDirectory, nestedDepth));\n }\n catch (UnauthorizedAccessException uae)\n {\n Debug.WriteLine(uae.Message);\n }\n catch (PathTooLongException ptle)\n {\n Debug.WriteLine(ptle.Message);\n }\n return Enumerable.Empty<string>();\n}\n\nprivate IEnumerable<string> SearchSubdirs(string currentDir, int currentDepth)\n{\n IEnumerable<string> filesWeAreLookingFor = GetFilesWeAreLookingFor(currentDir);\n\n if (currentDepth < _maxDepth)\n filesWeAreLookingFor = filesWeAreLookingFor.Concat(GetNestedFiles(currentDir, currentDepth + 1));\n\n return filesWeAreLookingFor;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-13T11:30:40.840",
"Id": "23834",
"ParentId": "23494",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23834",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T17:08:28.383",
"Id": "23494",
"Score": "7",
"Tags": [
"c#",
"exception-handling"
],
"Title": "Simplifying exception handling on Enumerators"
}
|
23494
|
<p>I'm currently creating a client/server application (using Java) and I want to make it fully controllable by an input stream (currently the console). At the moment only one class have to be controlled, but I want my code to stay easy to develop.</p>
<p>I found a solution but I think I can do better, so that's why I post this message: I want your advices on my method now and how I could improve it or how should it better be.</p>
<p>Here's my solution: </p>
<p>I created an interface <em>CommandControllable</em> like:</p>
<pre><code>import java.util.ArrayList;
public interface CommandControllable
{
public void execute(Command command);
public void addCommandManager(CommandManager commandManager);
public ArrayList<CommandManager> getCommandManagers();
}
</code></pre>
<p>A class Command like</p>
<pre><code>public class Command
{
protected String request;
public Command(String request)
{
this.request = request;
}
public String ToString()
{
return this.request;
}
}
</code></pre>
<p>A class CommandManager</p>
<pre><code>import java.io.InputStream;
import java.util.Scanner;
public class CommandManager implements Runnable
{
protected Scanner reader;
protected CommandControllable toControl;
protected boolean running = false;
public CommandManager(InputStream stream)
{
this.reader = new Scanner(stream);
}
@Override
public void run()
{
this.running = true;
while(this.running)
{
if(this.reader.hasNextLine())
{
Command c = new Command(this.reader.nextLine());
this.toControl.execute(c);
}
}
}
public void setControllable(CommandControllable toControl)
{
this.toControl = toControl;
}
public void stop()
{
this.running = false;
}
}
</code></pre>
<p>If I want a class to be controllable I write something like:</p>
<pre><code>public class Server implements CommandControllable
{
protected ArrayList<CommandManager> commandManagers = new ArrayList<CommandManager>();
public Server()
{
}
public void stop()
{
System.out.println("Server stopped");
}
@Override
public synchronized void execute(Command command)
{
switch(command.ToString())
{
case "quit":
stop();
break;
default:
System.out.println("Unrecognized command");
break;
}
}
@Override
public void addCommandManager(CommandManager commandManager)
{
commandManager.setControllable(this);
this.commandManagers.add(commandManager);
}
@Override
public ArrayList<CommandManager> getCommandManagers()
{
return this.commandManagers;
}
}
</code></pre>
<p>And</p>
<pre><code>public static void main(String[] args)
{
Server s = new Server();
CommandManager manager = new CommandManager(System.in);
s.addCommandManager(manager)
Thread t_manager = new Thread(manager);
t_manager.start();
}
</code></pre>
<p>Any advices on the current solution and how to improve it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T16:26:11.377",
"Id": "36346",
"Score": "2",
"body": "Just so it's said, classes with names like \"...Manager\", \"...Handler\", etc are generally frowned upon; they hint toward a class that either does too much or isn't clear about what it does."
}
] |
[
{
"body": "<p>CommandManager referes to a CommandControllable, and CommandControllable refers to a set of CommandManagers. Who controls who? Such loops in dependency graph should be avoided.</p>\n\n<p>Then, think if the Actor model can be applied in your case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T14:05:59.107",
"Id": "23565",
"ParentId": "23497",
"Score": "4"
}
},
{
"body": "<p>Just four quick notes:</p>\n\n<ol>\n<li><pre><code>public ArrayList<CommandManager> getCommandManagers();\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>public List<CommandManager> getCommandManagers();\n</code></pre>\n\n<p>See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n<li><pre><code>public String ToString()\n</code></pre>\n\n<p>is rather confusing, since there is an <code>Object.toString</code> and it's not clear from the name that which string does it return. I'd call it <code>getRequest()</code>.</p></li>\n<li><p>The <code>CommandManager</code> is not thread safe. Accessing of the <code>running</code> and <code>toControl</code> fields should be synchonized.</p>\n\n<blockquote>\n <p>If multiple threads access the same mutable state variable without appropriate synchronization,\n your program is broken. There are three ways to fix it:</p>\n \n <ul>\n <li>Don't share the state variable across threads;</li>\n <li>Make the state variable immutable; or</li>\n <li>Use synchronization whenever accessing the state variable.</li>\n </ul>\n</blockquote>\n\n<p>From <em>Java Concurrency in Practice</em> by <em>Brian Goetz</em>.</p>\n\n<p>Using an <code>AtomicBoolean</code> for the <code>reader</code> and an <code>AtomicReference</code> for <code>toControl</code> would solve it. (You might use <code>volatile</code> fields here too.)</p></li>\n<li><p>Streams and scanners usually should be closed somewhere. Although you are currently reading from <code>System.in</code> other clients might get streams for TCP connections or files which should be closed. It should be clear that whose (callee or caller) responsibility is the closing and when/where should it happen.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T16:40:57.770",
"Id": "23571",
"ParentId": "23497",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T20:19:02.790",
"Id": "23497",
"Score": "0",
"Tags": [
"java",
"object-oriented"
],
"Title": "Oriented-object approach on how to control different classes cleanly"
}
|
23497
|
<p>Thats my method to test:</p>
<pre><code> public LessonplannerRequest GetWeeklyLessonplanner(int schoolyearId)
{
Schoolyear schoolyear = _unitOfWork.SchoolyearRepository.GetById(schoolyearId);
DayOfWeek firstDayOfWeek = schoolyear.FirstDayOfWeek;
DateTime currentDate = DateTime.Now.Date;
DateTime startDateOfWeek = _dateService.GetFirstDateOfWeek(currentDate, firstDayOfWeek);
DateTime endDateOfWeek = _dateService.GetLastDateOfWeek(currentDate, firstDayOfWeek);
var periods = _unitOfWork.PeriodRepository.GetWeeklyPeriods(schoolyearId, startDateOfWeek, endDateOfWeek );
var weeks = _dateService.GetAllWeekStartingDays(startDateOfWeek, endDateOfWeek, firstDayOfWeek);
var request = new LessonplannerRequest
{
Periods = periods,
Weeks = weeks,
};
return request;
}
</code></pre>
<p>Thats my unit test:</p>
<pre><code> // Arrange
Mock<IUnitOfWork> unitOfWorkMock = new Mock<IUnitOfWork>();
Mock<IDateService> dateServiceMock = new Mock<IDateService>();
Mock<TLPContext> contextMock = new Mock<TLPContext>();
Mock<IGenericRepository<Schoolyear>> schoolyearRepositoryMock = new Mock<IGenericRepository<Schoolyear>>();
Mock<ILessonplannerRepository> lessonplannerRepoMock = new Mock<ILessonplannerRepository>();
int schoolyearId = 1;
DateTime start = new DateTime(2010, 1, 1);
DateTime end = new DateTime(2010, 1, 2);
unitOfWorkMock.Setup(s => s.SchoolyearRepository).Returns(schoolyearRepositoryMock.Object);
unitOfWorkMock.Setup(s => s.PeriodRepository).Returns(lessonplannerRepoMock.Object);
dateServiceMock.Setup(s => s.GetFirstDateOfWeek(DateTime.Now.Date, DayOfWeek.Sunday)).Returns(start);
dateServiceMock.Setup(s => s.GetLastDateOfWeek(DateTime.Now.Date, DayOfWeek.Sunday)).Returns(end);
schoolyearRepositoryMock.Setup(s => s.GetById(schoolyearId)).Returns(new Schoolyear() { FirstDayOfWeek = DayOfWeek.Sunday });
ILessonplannerService service = new LessonplannerService(unitOfWorkMock.Object, dateServiceMock.Object);
// Act
LessonplannerRequest request = service.GetWeeklyLessonplanner(schoolyearId);
// Assert
dateServiceMock.Verify(d => d.GetFirstDateOfWeek(DateTime.Now.Date, DayOfWeek.Sunday));
dateServiceMock.Verify(d => d.GetLastDateOfWeek(DateTime.Now.Date, DayOfWeek.Sunday));
lessonplannerRepoMock.Verify(d => d.GetWeeklyPeriods(schoolyearId, start, end));
Assert.That(request.Periods, Is.Empty);
Assert.That(request.Weeks, Is.Empty);
</code></pre>
<p>In my method to test all calls to a repository or dateService are already unit tested itself thus I am mocking them not to have an integration test...</p>
<p>I ask myself wether my assertion for empty lists make sense. And If not what would you test. Actually in this method everything is already tested just the creation of the LessonplannerRequest is not tested...</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:01:18.247",
"Id": "36255",
"Score": "0",
"body": "My very first impression is that your `GetWeeklyLessonPlanner()` method and its class might be doing too much. How much more than the method to test is there in the class? Is it just that method, the constructor and dependency fields? Generally try and post complete classes; that will make it easier for others to get the code working and provide assistance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:23:23.530",
"Id": "36263",
"Score": "0",
"body": "There is still a SaveLessonplanner() method with 5 lines of code. Why do you have the impression, that my class is doing too much?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:38:40.337",
"Id": "36265",
"Score": "0",
"body": "Just a first thought when I saw that `IUnitOfWork` is actually hiding an additional dependency of your method. I'm still figuring out what's actually happening."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:41:19.637",
"Id": "36267",
"Score": "0",
"body": "\"I'm still figuring out what's actually happening\" Then when did you your last mocking parade? ;P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T22:45:54.600",
"Id": "36270",
"Score": "0",
"body": "A few weeks back probably. My confusion wasn't so much about the test/mocks, but more about what the code under test actually does (and I still don't understand the greater purpose)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T19:50:55.810",
"Id": "36361",
"Score": "0",
"body": "\"and I still don't understand the greater purpose\" maybe therefore I did this question ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T19:51:08.523",
"Id": "36362",
"Score": "0",
"body": "@Elisa can you provide the code for `IDateService` implementation (`GetFirstDateOfWeek`, `GetLastDateOfWeek`, `GetAllWeekStartingDays` methods)? Obviously it's not under test, but in my answer I suggested to refactor it based on assumptions that may not be correct..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-13T20:01:08.473",
"Id": "36788",
"Score": "0",
"body": "all these 3 methods could also be written as extension methods almaz."
}
] |
[
{
"body": "<p>Almost everything is perfect. Some notes:</p>\n\n<ul>\n<li>Do use <code>var</code> to avoid repeating in cases like <code>Mock<IUnitOfWork> unitOfWorkMock = new Mock<IUnitOfWork>()</code></li>\n<li>Move mocks initialisation and wiring up to <code>SetUp</code> method to avoid copy-pasting in different test methods, and leave only actual setups that provide test data in test method</li>\n<li>It's hard to unit test the code that uses <code>DateTime.Now</code>. For example your test may fail when running near midnight (since you call <code>DateTime.Now</code> several times, and subsequent calls may return the next day). I would suggest to add the <code>UtcNow</code> property to your <code>IDateService</code> and always use it instead of <code>DateTime.Now</code> (I prefer to force using UTC time since it forces you to think about time zones). Then, most likely you won't need methods like <code>GetFirstDateOfWeek</code> in <code>IDateService</code> (if they depend on inputs only), they could be just extension methods to <code>DateTime</code>.</li>\n<li>You don't need to verify that <code>GetFirstDateOfWeek</code> and <code>GetLastDateOfWeek</code> were called, just make sure that result matches expected value. The reason is because the call to those methods does not guarantee that returned values were used correctly. And when all tests pass without those calls - it only shows that you should add more tests to verify that returned values were used properly</li>\n</ul>\n\n<p>As a result you'll have something like this:</p>\n\n<pre><code>[Test]\npublic void WhenWeekStartOnSunday...ShouldReturnSomething\n{\n const int schoolyearId = 1;\n var currentDate = new DateTime(2010, 1, 1).ToUniversalTime();\n var periods = new [] {...}; //specify test periods here\n\n //Arrange\n _schoolyearRepositoryMock.Setup(s => s.GetById(schoolyearId)).Returns(new Schoolyear() { FirstDayOfWeek = DayOfWeek.Sunday }); \n _dateServiceMock.Setup(s => s.UtcNow).Returns(currentDate);\n _lessonplannerRepoMock.Setup(lp => lp.GetWeeklyPeriods(schoolyearId, new DateTime(2010, 1, 1), \n new DateTime(2010, 1, 5))) //specify the dates expected according to \"currentDate\" value.\n .Returns(periods);\n\n var service = new LessonplannerService(_unitOfWorkMock.Object, _dateServiceMock.Object); \n\n // Act\n LessonplannerRequest request = service.GetWeeklyLessonplanner(schoolyearId);\n\n // Assert \n Assert.That(request.Periods, Is.SameAs(periods));\n Assert.That(request.Weeks, Is.Empty); //verify here expected list of weeks according to logic of the method\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:36:07.277",
"Id": "36264",
"Score": "0",
"body": "I'd go one further and say that schoolyearId should be const."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:40:06.423",
"Id": "36266",
"Score": "0",
"body": "@almaz \"The reason is because the call to those methods does not guarantee that returned values were used correctly\" But the call to those methods guarantee that the methods are called at all. What do you think?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:49:05.983",
"Id": "36268",
"Score": "0",
"body": "@Elisa what if you find the way to avoid calling those methods and yet produce proper results? Then you would have to change unit tests because they started to fail. If values returned by e.g. `GetFirstDateOfWeek` are actually valuable, then in certain use cases output will depend on them, and there should be a test that checks it. If there is no way to verify the proper usage of `GetFirstDateOfWeek`... then it does not influence results, and it means that you don't need to call it :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:52:59.490",
"Id": "36269",
"Score": "0",
"body": "You need to verify mock method calls when it is the function being tested, e.g. when functionality under test should send an email you would write assertion as `_emailSenderMock.Verify(e = > e.SendEmail(expected_parameters));`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T07:15:06.937",
"Id": "36281",
"Score": "0",
"body": "Updated the answer to verify that periods are passed through"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T12:31:25.047",
"Id": "36301",
"Score": "0",
"body": "I don't agree with the reasoning for testing `Weeks` for emptiness instead of a specific instance. You're making an assumption about implementation details of the `IDateService` instance, while actually for what is to be tested the exact dates are completely irrelevant. The start date could even be after the end date, and the `LessonplannerService` class - and its tests - should still work correctly, because it just ties those other services together. (I wouldn't even have chosen the dates myself but created them with AutoFixture for that very reason.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T15:12:46.907",
"Id": "36316",
"Score": "0",
"body": "@GCATNM I don't know the implementation of `IDateService`. I assumed that most of the methods (like `GetFirstDateOfWeek`) are pure methods, that is depend on input values only. In this case I suggested to move those methods to `DateTime`'s extension methods. In case if it depends on `IDateService` state then yes, you would need to do a setup and check for the same value in result as in your answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T17:07:19.317",
"Id": "36321",
"Score": "0",
"body": "@almaz I think I misunderstood the comment after that last line; I didn't get that this was more of a \"to be done\" for the asker than a justification for testing on emptiness. At any rate, I don't understand what the difference would be between testing for a specific instance in `Periods`, which you did, and setting up the `IDateService` stub with an instance for `Weeks`, which you didn't. That value does not depend on any decision in `LessonplannerService`, but solely on the return value of `IDateService.GetAllWeekStartingDays()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T19:38:40.777",
"Id": "36358",
"Score": "0",
"body": "@Guys maybe that was a bad example from me. I asserted an empty because I expect nothing to come as a result because my mocks do not setup data and return it. But in almaz solution he provides mock data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T19:39:18.733",
"Id": "36359",
"Score": "0",
"body": "@GCATNM yes the dates are completely irrelevant as I do not return anything from the mock data(hope I understood you right...) Thats also what my initial question is about : \"Do I test the right thing...\" Yes my startdate could be after the end date in the UNIT TEST but not in real as the date is validated on the web server."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T20:32:38.147",
"Id": "36366",
"Score": "0",
"body": "@Elisa The dates are irrelevant because the class under test does never look at them at all but just passes them around. The other classes involved may care about them, but they are stubbed out in this test, so the values never matter. The only thing this class does is tie a few services together; it doesn't even make any decisions, so the only thing there is to test is if it puts all the parameters in the right places and returns the correct values from those other services."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-13T20:03:51.513",
"Id": "36789",
"Score": "0",
"body": "@GCATNM Yes true the only this class is doing is just tie a few services together there is no class extra logic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-13T20:09:19.997",
"Id": "36790",
"Score": "0",
"body": "@almaz I upvoted your answer but gave the solution to GCATNM :) it was hard to choose between 2 good answers..."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:29:29.517",
"Id": "23507",
"ParentId": "23498",
"Score": "3"
}
},
{
"body": "<p>In addition to almaz' correct answer (except for using <code>SetUp</code> in NUnit, which is risky and can have dangerous side effects), I wouldn't test for empty collections, because those can come from anywhere and could well be the default for the properties of <code>LessonplannerRequest</code>.</p>\n\n<p>Instead, set up your mocks (which are now actually stubs because we're not verifying the calls to their methods) to return specific objects for the correct method invocations, and then assert that those objects are returned in your request object:</p>\n\n<pre><code>[Test]\npublic void GetWeeklyLessonPlanner_ReturnsCorrectRequest()\n{\n // Arrange\n Mock<IUnitOfWork> unitOfWorkMock = new Mock<IUnitOfWork>();\n Mock<IDateService> dateServiceMock = new Mock<IDateService>();\n Mock<IGenericRepository<Schoolyear>> schoolyearRepositoryMock = new Mock<IGenericRepository<Schoolyear>>();\n Mock<ILessonplannerRepository> lessonplannerRepoMock = new Mock<ILessonplannerRepository>();\n\n int schoolyearId = 1;\n DateTime start = new DateTime(2010, 1, 1);\n DateTime end = new DateTime(2010, 1, 2);\n\n unitOfWorkMock.Setup(s => s.SchoolyearRepository).Returns(schoolyearRepositoryMock.Object);\n unitOfWorkMock.Setup(s => s.PeriodRepository).Returns(lessonplannerRepoMock.Object);\n dateServiceMock.Setup(s => s.GetFirstDateOfWeek(DateTime.Now.Date, DayOfWeek.Sunday)).Returns(start);\n dateServiceMock.Setup(s => s.GetLastDateOfWeek(DateTime.Now.Date, DayOfWeek.Sunday)).Returns(end);\n\n var dayOfWeek = DayOfWeek.Sunday;\n schoolyearRepositoryMock.Setup(s => s.GetById(schoolyearId)).Returns(new Schoolyear() { FirstDayOfWeek = dayOfWeek });\n\n var expectedPeriods = new List<object>() { new object() };\n lessonplannerRepoMock.Setup(r => r.GetWeeklyPeriods(schoolyearId, start, end)).Returns(expectedPeriods);\n\n var expectedWeeks = new List<object>() { new object() };\n dateServiceMock.Setup(d => d.GetAllWeekStartingDays(start, end, dayOfWeek)).Returns(expectedWeeks);\n\n LessonplannerService service = new LessonplannerService(unitOfWorkMock.Object, dateServiceMock.Object);\n\n // Act\n LessonplannerRequest request = service.GetWeeklyLessonplanner(schoolyearId);\n\n // Assert\n Assert.That(request.Periods, Is.SameAs(expectedPeriods));\n Assert.That(request.Weeks, Is.SameAs(expectedWeeks));\n}\n</code></pre>\n\n<p>This will make sure that your stub objects' methods are called with the correct parameters, because the expected objects are only returned for those specific parameter combinations, and at the same time guarantee that those values are correctly used further on, because they are particular object references that the test can explicitly recognize.</p>\n\n<p>Note that the <code>List<object></code> will probably have to be something else in your actual code. Your code fragments didn't contain types for <code>Periods</code> and <code>Weeks</code>, so I used <code>IEnumerable<object></code> to work with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T07:02:45.193",
"Id": "36279",
"Score": "0",
"body": "Can you shed a light on side effects of using `SetUp`? I'm using it for about 8 years now and haven't noticed anything dangerous..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T10:23:53.533",
"Id": "36295",
"Score": "0",
"body": "Then you probably have a very tidy approach that doesn't let those issues come to bear. Many people will not have that. This is from James Newkirk, who led NUnit development for years before starting xUnit.net because he became dissatisfied with NUnit: http://jamesnewkirk.typepad.com/posts/2007/09/why-you-should-.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T16:31:46.057",
"Id": "36348",
"Score": "0",
"body": "@GCATNM Its an IEnumerable<Period> periods... :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T22:38:42.000",
"Id": "23511",
"ParentId": "23498",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23511",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T20:47:11.503",
"Id": "23498",
"Score": "5",
"Tags": [
"c#",
"unit-testing"
],
"Title": "Do I unit test the correct thing"
}
|
23498
|
<p>The objective of the following PHP function is simple: given an ASCII string, replace all ASCII chars with their Cyrillic equivalents.</p>
<p>As can be seen, certain ASCII chars have two possible equivalents.</p>
<p>For example: if the function is fed the string "dvigatel" it should get you "двигател". </p>
<p>The problem: if I pass "dvigat", the function will finish its execution in a fairly reasonable amount of time.</p>
<p>But, if I pass "dvigatel", which is only a couple letters longer, the execution time exceeds my 30 second PHP execution time limit. </p>
<p>Could anybody give me a few pointers here, what's wrong with this function, why does it run so slow with an 8-char string?</p>
<pre><code>function transliterate($query) {
$map=array(
"a" => array("а", "ъ"),
"b" => "б",
"c" => array("с", "ц"),
"d" => "д",
"e" => "е",
"f" => "ф",
"g" => array("г", "ж"),
"h" => "х",
"i" => array("и", "й"),
"j" => array("дж", "й"),
"k" => "к",
"l" => "л",
"m" => "м",
"n" => "н",
"o" => "о",
"p" => "п",
"q" => "я",
"r" => "р",
"s" => "с",
"t" => "т",
"u" => array("ъ", "ю", "у"),
"v" => array("в", "ж"),
"w" => "в",
"x" => array("кс", "х"),
"y" => array("ъ", "у"),
"z" => "з"
);
$query_array = preg_split('/(?<!^)(?!$)/u', $query );
$en_letters=array_keys($map);
$this->processed[]=$query;
foreach ($query_array as $letter) {
if (in_array($letter, $en_letters)) {
if (!is_array($map[$letter])) {
$query_translit=str_replace($letter, $map[$letter], $query);
} else {
foreach ($map[$letter] as $bg_letter) {
$query_translit=str_replace($letter, $bg_letter, $query);
if (!in_array($query_translit, $this->transliterations)) $this->transliterations[]=$query_translit;
}
}
} else {
$query_translit=$query;
}
if (!in_array($query_translit, $this->transliterations)) $this->transliterations[]=$query_translit;
}
foreach ($this->transliterations as $transliteration) {
if (!in_array($transliteration, $this->processed)) {
if (!preg_match("/[a-zA-Z]/", $transliteration)) {
return;
} else {
$this->transliterate($transliteration);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T17:34:51.980",
"Id": "36258",
"Score": "0",
"body": "1. If there are 2 options .. how do you resolve witch one to select ... 2. Why not do a simple replace instead of a recursive function ???"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T17:46:16.850",
"Id": "36259",
"Score": "0",
"body": "@Baba, it shouldn't resolve to select one. Rather, it should push both possible combinations into the resulting array. To your second, question - I was just considering it."
}
] |
[
{
"body": "<p>Why a recursive function for such a simple task?</p>\n\n<pre><code>$in = 'This is your input';\n$map = 'your char translation array here';\n$out = '';\nfor($i = 0; $i < strlen($in); $i++) {\n $char = $in[$i];\n if (isset($map[$char])) {\n if (is_array($map[$char])) {\n $newchar = $map[$char][0]; // whatever your multi-char selection logic is...\n } else\n $newchar = $map[$char];\n }\n $out .= $newchar;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T18:04:28.110",
"Id": "36260",
"Score": "0",
"body": "your code is much better than what I had. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T17:41:43.997",
"Id": "23502",
"ParentId": "23501",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23502",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T17:30:24.197",
"Id": "23501",
"Score": "1",
"Tags": [
"php",
"optimization",
"recursion"
],
"Title": "Given an ASCII string, replace all ASCII chars with their Cyrillic equivalents"
}
|
23501
|
<p>I have the main form with a list inside and i need to open another form and edit the list in the main. Generally i'm doing something like ...</p>
<pre><code> public class Form1 : Form
{
List<objectType> obj = new List<objectType>();
private void button_EDIT_BUTTONS_Click(object sender, EventArgs e)
{
EDIT_BUTTONS edit_b = new EDIT_BUTTONS(this);
edit_b.Show();
}
}
public partial class EDIT_BUTTONS : Form
{
Form1 main;
public EDIT_BUTTONS(Form1 mainP)
{
InitializeComponent();
main = mainP;
}
button = main.obj.Find(x => x.ID == object.ID);
............................................................
//modify button
}
</code></pre>
<p>My question is to pass the main form like this only to expose the list object or i should Create setters and getters in main form ?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T18:05:05.560",
"Id": "36261",
"Score": "1",
"body": "First you should really work on your naming conventions. Class names should start with an upper case letter, not be in full caps, and use camel casing to denote words, rather than underscores. It makes the code much easier to read for everyone else who's used to those conventions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T18:06:10.040",
"Id": "36262",
"Score": "0",
"body": "@Servy, I aswered this question a few weeks ago and you busted me for saying \"pass the whole form\". Haha got it right this time and was thinking of you when I wrote it. Funny that you should comment at the same time"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T21:53:37.213",
"Id": "36374",
"Score": "0",
"body": "Could you provide specific information about what you are doing with the buttons, what these buttons are for and what the forms do in general?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T13:07:12.050",
"Id": "36587",
"Score": "0",
"body": "i'm making buttons edit change picture change text etc"
}
] |
[
{
"body": "<p>You should only pass the list to the second form. If you pass the entire first form you are exposing somethings that wouldn't be best, and coupling the two forms tightly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T18:04:21.057",
"Id": "23504",
"ParentId": "23503",
"Score": "4"
}
},
{
"body": "<p>It would be better if an object was used in a encapsulated method of Form1.</p>\n\n<p>Create a method inside Form1, something like <code>GetButton(string Id)</code> and return the button object only, no need to expose the whole list. </p>\n\n<pre><code> public class Form1 : Form\n {\n List<objectType> obj = new List<objectType>();\n private void button_EDIT_BUTTONS_Click(object sender, EventArgs e)\n {\n EDIT_BUTTONS edit_b = new EDIT_BUTTONS(this);\n edit_b.Show();\n }\n public Button GetButton(string id)\n {\n return obj.FirstOrDefault(x => x.ID == Id);\n }\n\n }\n public partial class EDIT_BUTTONS : Form\n {\n Form1 main;\n public EDIT_BUTTONS(Form1 mainP)\n {\n InitializeComponent();\n main = mainP;\n }\n button = main.GetButton(object.ID);\n\n //modify button\n\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T18:05:30.037",
"Id": "23505",
"ParentId": "23503",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "23504",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T18:00:49.593",
"Id": "23503",
"Score": "1",
"Tags": [
"c#",
"winforms"
],
"Title": "Get Set vs passing class at init?"
}
|
23503
|
<pre><code>String slm = status.getHeader("last-modified");
SimpleDateFormat sdf = new SimpleDateFormat(
"EEE, dd MMM yyy HH:mm:ss zzz");
Date serverLastMod = null;
try {
serverLastMod = sdf.parse(slm);
} catch (ParseException e) {
Log.e("SAC XML last-modified", e.getMessage());
}
Date fileLastFetched = status.getTime();
Log.e("DATE1", serverLastMod.toGMTString());
Log.e("DATE2", fileLastFetched.toGMTString());
//if the server date is before my file date, update it, else dont
if (serverLastMod.after(fileLastFetched)) {
Log.e("DS", "YES! Getting ROSE");
XmlDom r = xml.tag("reportrose");
roseUrl = r.tag("img").attr("src").trim();
aq.download(roseUrl, file, new AjaxCallback<File>() {
public void callback(String url, File file, AjaxStatus status) {
String s = status.getMessage();
int i = status.getCode();
String e = s + " | Status Code: " + i;
if (file != null) {
getInfo();
} else {
Log.e("ACR SAC Widget Error", e);
}
}
});
} else {
Log.e("DS", "NO! Don't do anything... Wait until next check...");
}
</code></pre>
|
[] |
[
{
"body": "<p>Well, if it works, it works. There is not much to say about this small part of the code without any context. You should know this by yourself, because you should have some tests.</p>\n\n<hr>\n\n<p>For the code:</p>\n\n<p>The first catch is not suitable. If it happens, you will get a <code>NullPointerException</code> for the following if.</p>\n\n<hr>\n\n<p>Avoid abbreviations. There are a lot of bad examples in this code, the most noticeable one is <code>String e = s + \" | Status Code: \" + i;</code></p>\n\n<hr>\n\n<p>Reduce indentation levels:</p>\n\n<pre><code>if (serverLastMod.after(fileLastFetched)) {\n...\n} else {\n Log.e(\"DS\", \"NO! Don't do anything... Wait until next check...\");\n}\n</code></pre>\n\n<p>could be:</p>\n\n<pre><code>if (!serverLastMod.after(fileLastFetched)) // or last <= current\n{\n log...\n return\n}\n... rest of code...\n</code></pre>\n\n<p>and so on.<br>\nThe part ...rest of code... could probably have its own method <code>update...</code>, so the purpose is clear.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T13:44:07.570",
"Id": "23533",
"ParentId": "23512",
"Score": "3"
}
},
{
"body": "<pre><code>String s = status.getMessage();\nint i = status.getCode();\nString e = s + \" | Status Code: \" + i;\n</code></pre>\n\n<p>can be directly rewrited :</p>\n\n<pre><code>String e = status.getMessage() + \" | Status Code: \" + status.getCode();\n</code></pre>\n\n<p>or more clean with <a href=\"http://rads.stackoverflow.com/amzn/click/0321356683\" rel=\"nofollow\">Effective Java</a> (Item 51)</p>\n\n<pre><code>StringBuilder sbTmp = new StringBuilder('MaxLenghtOfNormalMessages')\nsbTmp.append(status.getMessage());\nsbTmp.append( \" | Status Code: \");\nsbTmp.append(status.getCode());\n</code></pre>\n\n<p>Put also <code>sbTmp</code> in the <code>else { .. }</code> if it is not used outside it</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T16:00:18.950",
"Id": "36319",
"Score": "1",
"body": "I do not agree with the last point (replacing with StringBuilder). The item in effective java from bloch (not extreme java) mentions string rebuilding inside loops with lots of iterations. For the given example, the `+` operator is absolutely fine. It is more readable and will most probably be replaced by the interpreter/compiler to a StringBuilder anyway. This is an example of bad premature optimization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T16:07:05.347",
"Id": "36320",
"Score": "0",
"body": "@tb- I do not know why I always change the title of Joshua Bloch book's, corrected. Perhaps `StringBuilder` looks luxury, but the main impact is given by the size of messages expected. The more efficient is to put it in the `else` : only build if necessary."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T14:58:01.230",
"Id": "23540",
"ParentId": "23512",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23533",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T00:10:38.147",
"Id": "23512",
"Score": "3",
"Tags": [
"java",
"android"
],
"Title": "Is my logic correct checking for a newer remote file?"
}
|
23512
|
<p>I have the following snippet of code that redirects a user to a specific page on successful login to the application.</p>
<pre><code>if(isset($this->params['url']['next'])) {
$url = parse_url(urldecode($this->params['url']['next']), PHP_URL_HOST);
if( $_SERVER['SERVER_NAME'] != $url || $url == false ) {
$pathtoredirect = $this->Auth->redirect();
} else {
$pathtoredirect = urldecode($this->params['url']['next']);
}
} else {
$pathtoredirect = $this->Auth->redirect();
}
$this->redirect($pathtoredirect);
</code></pre>
<p>The idea is that if a query string named 'next' exists and has a valid hostname that matches the actual sever hostname then send the user to that location otherwise send them to the default location. It should also handle really bad formatted urls by the parse_url method returning false.</p>
<p>Can anyone see any issues with the above code? Or offer improvements?</p>
<p>Thanks</p>
<p><strong>EDIT</strong></p>
<p>The next parameter can be added manually for example on a login link, but is also created automatically on the redirect when a user tries to access a protected action.</p>
<p>The reason for adding the <code>FULL_BASE_URL</code> is because the session also contains the app url, so if your app is on a subdirectory e.g. <code>domain.com/myapp/</code> and you try and access <code>domain.com/myapp/protectedlocation</code> you will get redirected to the login form with <code>domain.com/myapp/login?next=/myapp/protectedlocation</code> which will then send you off to: <code>domain.com/myapp/myapp/protectedlocation</code> <strong>adding /myapp twice!</strong> Doing the full url instead STOPS this from ever happening and doing the parse url prevents a malicious user from creating a login link with their own url as the return.</p>
<pre><code>public function redirect($url, $status = null, $exit = true)
{
if($this->Session->read('Auth.redirect'))
{
$url.= '?next=' . urlencode(FULL_BASE_URL.$this->Session->read('Auth.redirect'));
}
$this->Session->delete('Auth.redirect');
return parent::redirect($url, $status, $exit);
}
</code></pre>
|
[] |
[
{
"body": "<p>There is no need to <code>urldecode()</code> the url parameters, Cake does this for you. In fact, you are decoding twice, which is usually a bug.</p>\n\n<p><code>$url</code> actually contains the hostname. That is very confusing and you should rename that.</p>\n\n<p>Also, that is really deep nesting for such a simple piece of code and a lot of code duplication.</p>\n\n<p>I implemented pretty much the same functionality once.</p>\n\n<p>If you only want to redirect to internal resources, maybe an option would be to only allow relative urls (e. g. <code>http://example.com/login?next=/dashboard</code>). That would save you a lot of trouble:</p>\n\n<pre><code>$defaultRedirect = $this->Auth->redirect(); \n\nif(empty($this->params['url']['next'])) { \n return $this->redirect($defaultRedirect); \n} \n\n$path = $this->params['url']['next']; \n\nif (strpos($path, '/') === 0) { \n return $this->redirect($path); \n} \n\n$this->redirect($defaultRedirect);\n</code></pre>\n\n<p>This also works around the inconsistencies of <code>$_SERVER['SERVER_NAME']</code>.</p>\n\n<p>Why are you expecting weird urls?</p>\n\n<p>Consider matching the path to your defined routes if you want to redirect to actions of your application only.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T18:16:24.080",
"Id": "36325",
"Score": "0",
"body": "The problem I had with using relative urls was that the next parameter can sometimes contain the app url itself, because it is populated from the session auth redirect. So if the app is a directory for example like: http://domain.com/myapp/login?next=/myapp/location`. And because `$this->redirect()` already assumes it's on the app and will prepend the passed return url with the app, so it would do `/myapp/myapp/location` and give a 404. Doing the FULL url for the return stops this from happening (see updated OP). And I do the check to stop someone trying to redirect a user to a bad location."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T14:19:30.120",
"Id": "23538",
"ParentId": "23513",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T00:12:38.633",
"Id": "23513",
"Score": "2",
"Tags": [
"php",
"cakephp"
],
"Title": "CakePHP return url validator"
}
|
23513
|
<p>I define a <code>Pixel</code> data with different size like this.</p>
<pre><code>data Pixel = RGB8 Word8 Word8 Word8
| RGBA8 Word8 Word8 Word8 Word8
| RGB16 Word16 Word16 Word16
| RGBA16 Word16 Word16 Word16 Word16
| Empty
deriving (Eq)
</code></pre>
<p>and <code>Num</code> instance</p>
<pre><code>instance Num Pixel where
x + Empty = x
Empty + x = x
(RGB8 ru gu bu) + (RGB8 rv gv bv) = RGB8 (ru + rv) (gu + gv) (bu + bv)
(RGBA8 ru gu bu au) + (RGBA8 rv gv bv av) = RGBA8 (ru + rv) (gu + gv) (bu + bv) (au + av)
(RGB16 ru gu bu) + (RGB16 rv gv bv) = RGB16 (ru + rv) (gu + gv) (bu + bv)
(RGBA16 ru gu bu au) + (RGBA16 rv gv bv av) = RGBA16 (ru + rv) (gu + gv) (bu + bv) (au + av)
x - Empty = x
Empty - x = x
(RGB8 ru gu bu) - (RGB8 rv gv bv) = RGB8 (ru - rv) (gu - gv) (bu - bv)
(RGB16 ru gu bu) - (RGB16 rv gv bv) = RGB16 (ru - rv) (gu - gv) (bu - bv)
(RGBA8 ru gu bu au) - (RGBA8 rv gv bv av) = RGBA8 (ru - rv) (gu - gv) (bu - bv) (au - av)
(RGBA16 ru gu bu au) - (RGBA16 rv gv bv av) = RGBA16 (ru - rv) (gu - gv) (bu - bv) (au - av)
_ * _ = error "Not support multiply"
abs = id
signum _ = error "Not support signum"
fromInteger _ = error "Not support fromInteger"
</code></pre>
<p>It's very ugly and bored. I think Haskell is a Elegant language, so can I have a better style to write this?</p>
|
[] |
[
{
"body": "<p>Above all, such an instance doesn't make any sense. A composite entity can't have much in common with a number, which the fact that your instance consists of just partial and undefined functions is only the evidence of. </p>\n\n<hr>\n\n<p>With regards to your concern about the verbosity of the instance declaration, it was caused by you choosing an incorrect approach to type declaration. </p>\n\n<p>Pixels of different bit-depths are appropriately described as different types, and not different constructors of the same type. The analogy is right before you: <code>Word8</code> and <code>Word16</code> are different types, not constructors. </p>\n\n<p>Taking the said above into account I recommend you to reapproach your problem the following way:</p>\n\n<pre><code>-- The separate datatypes. Note the absense of `Empty` constructors, as there\n-- is no such thing as empty pixel. There are black and transparent pixels,\n-- which should be described as `PixelRGB8 0 0 0` or `PixelRGBA8 0 0 0 0`,\n-- but not empty. And for dealing with missing pixels we have a `Maybe` type.\ndata PixelRGB8 = PixelRGB8 Word8 Word8 Word8\n-- ...\ndata PixelRGBA16 = PixelRGBA16 Word16 Word16 Word16 Word16\n\n-- We're taking an analogous approach to Num/Integral typeclasses, while \n-- combining both the \"to\" and \"from\" functionality in a single typeclass.\nclass Pixel a where\n -- whether its toPixelRGBA16 or possibly toRGBA64Pixel should depend on\n -- the highest precision type you want to be dealing with\n toPixelRGBA16 :: a -> PixelRGBA16\n fromPixelRGBA16 :: PixelRGBA16 -> a\n -- And here's addition for pixels of same type:\n addPixel :: a -> a -> a\n\ninstance Pixel PixelRGB8 where\n toPixelRGBA16 = error \"TODO\"\n fromPixelRGBA16 = error \"TODO\"\n addPixel = error \"TODO\"\n\ninstance Pixel PixelRGBA16 where\n toPixelRGBA16 = id\n fromPixelRGBA16 = id\n addPixel = error \"TODO\"\n\n-- Here's addition for pixels of differing types:\naddArbitraryPixel :: (Pixel a, Pixel b) => a -> b -> PixelRGBA16\naddArbitraryPixel a b = addPixel (toPixelRGBA16 a) (toPixelRGBA16 b)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T03:45:57.180",
"Id": "36277",
"Score": "0",
"body": "But I need pixel addition and pixel has different data type (8-bit, 16-bit). Do you have any idea to define a pixel? Thanks for answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T06:56:31.567",
"Id": "36278",
"Score": "0",
"body": "@Pikaurd Volkov's right.\n\nAs for what you should do, check the `Vector a` type from the following link:\nhttp://learnyouahaskell.com/making-our-own-types-and-typeclasses\n\nThe article is a good introduction to the subject."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T08:20:02.020",
"Id": "36286",
"Score": "0",
"body": "@abuzittingillifirca Thanks your link. I'll try to rewrite it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T14:44:28.903",
"Id": "36314",
"Score": "0",
"body": "@Pikaurd See the updates to the answer"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T02:10:52.457",
"Id": "23517",
"ParentId": "23516",
"Score": "4"
}
},
{
"body": "<p>I agree with the other answers saying that you should have different types for your different pixels.</p>\n\n<p>That said, you can probably define a single polymorphic type and write a lot less code:</p>\n\n<pre><code>data Pixel a n = Pixel (a n) n n n\n\ndata NoAlpha n = NoAlpha\n\nnewtype Alpha n = Alpha n\n\ntype PixelRGB8 = Pixel NoAlpha Word8\n\ntype PixelRGBA8 = Pixel Alpha Word8\n\ntype PixelRGB16 = Pixel NoAlpha Word16\n\ntype PixelRGBA16 = Pixel Alpha Word16\n</code></pre>\n\n<p>Then, you can define pixel addition once for all the types (with a little helper for the alpha types):</p>\n\n<pre><code>class AddAlpha a where\n addAlpha :: (Num n) => a n -> a n -> a n\n\ninstance AddAlpha NoAlpha where\n addAlpha _ _ = NoAlpha\n\ninstance AddAlpha Alpha where\n addAlpha (Alpha a) (Alpha b) = Alpha (a + b)\n\naddPixels :: (Num n, AddAlpha a) => Pixel a n -> Pixel a n -> Pixel a n\n-- I'll leave the definition up to you.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T06:31:42.183",
"Id": "24747",
"ParentId": "23516",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23517",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T01:39:50.757",
"Id": "23516",
"Score": "4",
"Tags": [
"haskell",
"functional-programming"
],
"Title": "Is there a way to simple Haskell class instance?"
}
|
23516
|
<p>This code works but is there a simple / better way to do this?</p>
<p>It starts from a particular point (<code>starthere</code>) in the array, looks for first <code>stop</code> value to the left of start point, and the first <code>stop</code> to the right side.</p>
<p>Basically returns the closest values' positions to a start point both sides. (I'll make this a function.)</p>
<pre><code>var arr = ['f','f','stop','stop','f','f','starthere','f','f','f','stop','stop','f','f','f','f'];
var i = arr.indexOf('starthere');
while (i--) {
if (arr[i] == 'stop') {
document.write(i + '</br>');
break;
}
}
for (var i = arr.indexOf('starthere'); i < arr.length; i++) {
if (arr[i] == 'stop') {
document.write(i);
break;
}
}
</code></pre>
<p>Returns <code>3</br>10</code></p>
|
[] |
[
{
"body": "<p>There is an overload of <code>.indexOf</code> that takes a second parameter indicating the starting location for the search. That can be used to find the <code>stop</code> after <code>starthere</code>. Then you can use <code>.slice</code> to grab the part of the array before <code>starthere</code> with <code>lastIndexOf</code> to find the <code>stop</code> that comes before:</p>\n\n<pre><code>var i = arr.indexOf('starthere');\nvar stopafter = arr.indexOf('stop', i);\nvar stopbefore = arr.slice(0, i).lastIndexOf('stop');\ndocument.write(stopbefore + '</br>' + stopafter);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T04:12:04.037",
"Id": "23520",
"ParentId": "23519",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23520",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T03:49:22.550",
"Id": "23519",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Searching for the closest \"stop\" elements surrounding a start point"
}
|
23519
|
<p>So I wrote an asynchronous version of <code>AutoResetEvent</code>:</p>
<pre><code>public sealed class AutoResetEventAsync {
private readonly Task<bool> falseResult = Task.FromResult(false);
private readonly ConcurrentQueue<Handler> handlers = new ConcurrentQueue<Handler>();
private readonly Task<bool> trueResult = Task.FromResult(true);
private int isSet;
public AutoResetEventAsync(bool initialState) {
this.isSet = initialState ? 1 : 0;
}
public void Set() {
this.isSet = 1;
Handler handler;
// Notify first alive handler
while (this.handlers.TryDequeue(out handler))
if (handler.TryUnsubscribe()) {
handler.Invoke();
break;
}
}
public Task<bool> WaitAsync() {
return this.WaitAsync(CancellationToken.None);
}
public Task<bool> WaitAsync(TimeSpan timeout) {
if (timeout == Timeout.InfiniteTimeSpan)
return this.WaitAsync();
var tokenSource = new CancellationTokenSource(timeout);
return this.WaitAsync(tokenSource.Token);
}
public Task<bool> WaitAsync(CancellationToken cancellationToken) {
// Short path
if (this.TryReset())
return this.trueResult;
if (cancellationToken.IsCancellationRequested)
return this.falseResult;
// Wait for a signal
var completionSource = new TaskCompletionSource<bool>(false);
var handler = new Handler(() => {
if (this.TryReset())
completionSource.TrySetResult(true);
});
// Subscribe
this.handlers.Enqueue(handler);
if (this.TryReset()) {
// Unsubscribe
handler.TryUnsubscribe();
return this.trueResult;
}
cancellationToken.Register(() => {
// Try to unsubscribe, if success then the handler wasn't invoked so we could set false result,
// else the handler was invoked and the result is already set.
if (handler.TryUnsubscribe())
completionSource.TrySetResult(false);
});
return completionSource.Task;
}
private bool TryReset() {
return Interlocked.CompareExchange(ref this.isSet, 0, 1) == 1;
}
private sealed class Handler {
private readonly Action handler;
private int isAlive = 1;
public Handler(Action handler) {
this.handler = handler;
}
public void Invoke() {
this.handler();
}
public bool TryUnsubscribe() {
return Interlocked.CompareExchange(ref this.isAlive, 0, 1) == 1;
}
}
}
</code></pre>
<p>In my application it works well. </p>
<p>The question is: am I missing some concurrency issue? </p>
<p>I tested concurrent invocation of <code>WaitAsync</code> method, so, maybe you could suggest a better test scenario?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T22:11:01.317",
"Id": "36331",
"Score": "0",
"body": "The code is missing any public documentation, so one is left to wonder what exactly is the intended behavior. For example: it `WaitAsync()` supposed to be FIFO?"
}
] |
[
{
"body": "<p>Your code does have race conditions, so it won't work correctly. I think your main problem is that you make some “destructive” operation (e.g. dequeue a handler from the queue) without knowing that the followup operation will actually succeed and not handling the eventual failure in any way.</p>\n\n<p>For example, the following sequence of events could happen:</p>\n\n<ol>\n<li>The class is created in unset state.</li>\n<li><code>WaitAsync()</code> is called, creating a <code>Handler</code>, adding it to the queue and returning a <code>Task</code>.</li>\n<li><code>Set()</code> is called, setting <code>isSet</code> to <code>1</code>.</li>\n<li>The handler from step 2 is dequeued.</li>\n<li><code>WaitAsync()</code> is called from another thread. Since <code>isSet</code> is <code>1</code>, it sets <code>isSet</code> back to <code>0</code> and immediately returns a completed <code>Task</code>.</li>\n<li>Back on the previous thread, <code>TryUnsubscribe()</code> is called in the handler from step 4 and succeeds.</li>\n<li>The handler is <code>Invoke()</code>d, but <code>TryReset()</code> fails.</li>\n<li><code>Set()</code> now returns.</li>\n</ol>\n\n<p>After this, the <code>Task</code> from step 2 is now orphaned, it will never be completed, because its handler is not in the queue anymore.</p>\n\n<hr>\n\n<p>I suggest you don't write code like this by yourself, but instead use code written by others with more experience in concurrent programming. Specifically, you could use <a href=\"http://blogs.msdn.com/b/pfxteam/archive/2012/02/11/10266923.aspx\" rel=\"nofollow\">Stephen Toub's <code>AsyncAutoResetEvent</code></a> or <a href=\"http://nitoasyncex.codeplex.com/wikipage?title=AsyncAutoResetEvent&referringTitle=Documentation\" rel=\"nofollow\"><code>AsyncAutoResetEvent</code> from Stephen Cleary's AsyncEx library</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T07:17:08.000",
"Id": "36339",
"Score": "0",
"body": "Thank you for that. I saw `AsyncAutoResetEvent` that you mention, but it uses lock. I want to make a lock-less implementation of `AutoResetEvent` to get an experience in concurrent programming. I also spot another concurrency issue in `WaitAsync` method where it ignores the result of `TryUnsubscribe` method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T14:40:25.540",
"Id": "36343",
"Score": "0",
"body": "@SHSE Yeah, I wouldn't be surprised if there were other issues in your code. I just answered with the first significant race I discovered."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T14:44:18.280",
"Id": "36344",
"Score": "0",
"body": "@SHSE Also, I'm not sure trying to be lock-less is worth it here, since this code is not likely to be in a tight loop. Of course, if you're doing this to learn, that might not matter much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T18:07:56.313",
"Id": "36353",
"Score": "0",
"body": "I ended up with [this code](https://gist.github.com/SHSE/5107198#file-autoreseteventasync-cs), it isn't lock-less but it hasn't any instance wide locks."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T22:48:32.000",
"Id": "23557",
"ParentId": "23522",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "23557",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T06:50:10.537",
"Id": "23522",
"Score": "6",
"Tags": [
"c#",
".net",
"asynchronous"
],
"Title": "AutoResetEventAsync, am I missing something?"
}
|
23522
|
<p>I need to select all checked checkboxes, <strong>except</strong> checkboxes having a class <code>.checkall</code>.</p>
<p>HTML:</p>
<pre><code><input type="checkbox" value="1961" class="checkbox">
<input type="checkbox" name="checkall" class="checkbox checkall">
</code></pre>
<p>Script:</p>
<pre><code>$("input.checkbox:checkbox:checked:not(.checkall)").each(function () {
var checkbox = $(this), machineId = checkbox.val()
}
</code></pre>
|
[] |
[
{
"body": "<p>I just posted on your other post about this, use:</p>\n\n<pre><code>$(\"input[type=checkbox]:checked:not(.checkall)\")\n</code></pre>\n\n<p>This is the 'regular' way to check for input tags of a particular type, it's much clearer than your way. I'm not sure what the significance of the <code>.checkbox</code> class is but it seems like it's not necessary to my.</p>\n\n<p>I also recommend you cache your check boxes in a variable and search that multiple times. That way you're only searching the check boxes each time instead of the whole DOM.</p>\n\n<pre><code>// in document ready\nvar checkboxes = $('input[type=checkbox]');\n\n// When you need to find the checked check boxes\nvar checked = checkboxes.find(':checked:not(.checkall)');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T08:38:31.280",
"Id": "23526",
"ParentId": "23523",
"Score": "6"
}
},
{
"body": "<p>Addionally to @Tyriar's answer:</p>\n\n<p>You possibly could optimize the selection even more depending on where the checkboxes are in the HTML by making the selector more specific and possibly modifying the HTML to help with that. </p>\n\n<p>For example, if all checkboxes are the same element, add it's ID (or class) as a parent in the selector:</p>\n\n<pre><code>$(\"#mytable input[type=checkbox]:checked:not(.checkall)\")\n</code></pre>\n\n<p>Also <code>:not</code> isn't very efficient. If the \"check all\" checkboxes were, for example, in the <code>thead</code> of a table while the checkboxes you need are in the <code>tbody</code> then use:</p>\n\n<pre><code>$(\"#mytable tbody input[type=checkbox]:checked\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T12:49:49.687",
"Id": "23532",
"ParentId": "23523",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23526",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T07:32:20.890",
"Id": "23523",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Limited checkbox selection"
}
|
23523
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.