Recent Entries 10
- pattern minor 112d agoFill a vector with uniformly distributed random complex numbersI want to fill an array of complex numbers using a uniform generator. I thought up the next code. (`Complex` is a simple fixed-point complex data type.) ``` std::generate(inputData.begin(), inputData.end(), []()-> Complex { static std::default_random_engine generator; static std::normal_distribution distribution(0.0, 0.5); // mean = 0.0, stddev = 0.5 return Complex(distribution(generator), distribution(generator)); }); ``` So I though up using static variables within the lambda expression. Is that inefficient? Alternatively I would create them outside of the lambda, and put them on the capture list. But I don't need them outside of the lambda, so this seems cleaner to me.
- pattern minor 112d agoGetting enum values of Pseudo-Enum classesBy "Pseudo-Enum" classes I mean cases where someone's used a class with public static properties to emulate enum behaviour; e.g. as described here. Per the example below, this is useful for classes such as `[System.Management.Automation.VerbsCommon]`, where there is a list of values we're interested in, but no "Get All Values of This Type" method. I wrote this function for the above type, and it works well for that, but maybe I've missed a trick / there are likely other scenarios that this code could cover which I've not thought of yet. ``` Clear-Host function Get-EnumValues { [CmdletBinding()] param ( [Parameter(Mandatory,ValueFromPipeline)] [Type]$Type ) process { if ($Type) { Write-Verbose ("Type: {0}" -f $Type.ToString()) Write-Verbose ("IsEnum? {0}" -f $Type.IsEnum) if ($Type.IsEnum) { [System.Enum]::GetNames($Type) } else { #handle pseudo-enums (i.e. for cases where this trick's been used https://stackoverflow.com/a/15713789/361842) $Type.GetFields() | ?{$_.IsStatic -and $_.IsPublic} | select -ExpandProperty Name } } else { Write-Verbose ("TypeName is Null") $null } } } $t = [type][System.ConsoleColor] Get-EnumValues $t -Verbose $t = [type][System.Management.Automation.VerbsCommon] Get-EnumValues $t -Verbose ``` Output: `VERBOSE: Type: System.ConsoleColor VERBOSE: IsEnum? True Black DarkBlue DarkGreen DarkCyan DarkRed DarkMagenta DarkYellow Gray DarkGray Blue Green Cyan Red Magenta Yellow White VERBOSE: Type: System.Management.Automation.VerbsCommon VERBOSE: IsEnum? False Add Clear Close Copy Enter Exit Find Format Get Hide Lock Move New Open Optimize Push Pop Remove Rename Reset Resize Set Search Show Skip Step Join Redo Split Switch Select Undo Unlock Watch ` I'm aware that the shorthand coding style sometimes frowned upon, such as: `$Type.GetFields() | ?{$_.I
- pattern minor 112d agoClient to connect to server and show a text menuFirst of all: Sorry for my English, that said... I am developing an obligatory for my University, so far it has a class that provides the user with options to connect to a server (once connected it should offer other functionalities, but I only reached the connection option so far), it only shows console options, and checks they are correctly chosen, nothing else. The class has everything (including itself) static, the reason is simple: I didn't considered necessary to instantiate that class, not even once (what is allowed by using Singleton Pattern), and so I decided going everything static inside it. I showed my code to my teacher, who said It was an awful design more or less :( well, he suggested I used Singleton and I explained that I understood Singleton to be only useful when you wanted (needed) only one instance for the class, I don't need even one! He said static variables are global, which could cause conflict with other variable names and then I would have to remember the static variable names I used so as to avoid conflict, so I highlighted that the class has everything private (except a method called ShowStartMenu() which is internal, and is the one called in the Main) and then he almost exploded... He told me it wasn't a good design because it didn't allow extensibility (what if I wanted to add more options to the menu, I had to add them in that class... which is exactly what I intended, is that wrong?), and had other disadvantages I could ask my design teacher ¬¬ So, I want to show you my code and ask you what do you think about it. ``` using System; namespace ARIP.Client.Console { internal static class ClientOptions { private const int START_MENU_CONNECT_TO_SERVER_OPTION = 1; private const int START_MENU_END_APPLICATION_OPTION = 0; private static int _minOption; private static int _maxOption; private static int _givenOption; #region General Client-Option's Functions private sta
- pattern minor 112d agoCSV parsers and OrderedDictionaryI wrote the following (static) class to read files easily in C#. However, it is a static class, so I wonder if there would be a gain to make it a non static method (and therefore, passing arguments as the separator and the path as attributes of the class). Besides, the `OrderedDictionary` class may not be a good choice (it is not generic but it preserves the order of the columns), and I don't know if there is a nice workaround for this. ``` using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; namespace MySolution.FileUtils { /// /// Various helpers to read through the lines of a file. /// public static class LinesEnumerator { public static string ReadFirstLine(string path) { using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader sr = new StreamReader(fs)) { return sr.ReadLine(); } } /// /// Enumerates the lines of a file. /// /// The path of the file. /// The maximum number of lines to read. /// The lines of a file, as a IEnumerable public static IEnumerable LinesReader(string path, int maxLines = Int32.MaxValue) { string line; int lineNumber = 0; using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader sr = new StreamReader(fs)) { while ((line = sr.ReadLine()) != null && lineNumber /// Reads the lines of a CSV file and enumerates them through a csv file /// /// Path to the CSV file /// Separator used by the CSV file /// A collection of ordered dictionaries, corresponding to the lines of the file public static IEnumerable DictReaderCSV(string path, char separator) { using (FileStream f
- pattern minor 112d agoExtending functionality of org.springframework.batch.item.file.transform.DefaultFieldSetI would like to be able to set token values (defaultFieldSet.tokens) and names (defaultFieldSet.names) on `org.springframework.batch.item.file.transform.DefaultFieldSet` using a `java.util.Properties` object. Specifically, the keys of the Properties object will serve as the names and the corresponding Properties values will serve as the tokens. Here's the code that I have to do this: ``` import java.util.Properties; import java.util.Set; import org.springframework.batch.item.file.transform.DefaultFieldSet; import org.springframework.batch.item.file.transform.FieldSet; /** * PropertiesFieldSetFactory is a factory to create * a {@link FieldSet} from a {@link Properties} object. */ public class PropertiesFieldSetFactory { /** * Creates a {@link FieldSet} by setting its token values equal to the {@link Properties} values * and its token names equal to the {@link Properties} keys. * Note: Passing a null argument to this method will cause a {@link NullPointerException} * to be thrown. * * @param properties used to populate the {@link FieldSet} * @return {@link FieldSet} that has token values and names from the passed in {@link Properties} object */ public static FieldSet create(Properties properties) { final Set tokenNamesSet = properties.stringPropertyNames(); final int numberOfTokens = tokenNamesSet.size(); final String[] tokenNames = tokenNamesSet.toArray(new String[numberOfTokens]); final String[] tokenValues = new String[numberOfTokens]; for (int tokenPosition = 0; tokenPosition < numberOfTokens; tokenPosition++) { String tokenName = tokenNames[tokenPosition]; tokenValues[tokenPosition] = properties.getProperty(tokenName); } return new DefaultFieldSet(tokenValues, tokenNames); } } ``` My concern with this approach is in regards to unit testing. For example, I have the following method (in another class) that needs to be unit
- pattern minor 112d agoPrimitive Extensions - Replaces static primitive methodsI got annoyed having to do things like `string.IsNullOrEmpty(myString)` when it seemed as if `myString.IsNullOrEmpty()` would perfectly suffice. Therefore, I wrote a small, simple library to wrap the static methods of primitives in extension methods. I don't suppose there is much to critique about the code itself, as most methods are one-liners, but I'm wondering if what I have done violates any best-practice principles. Is there some insightful reasoning behind why these methods were left out in the first place? The class dealing with strings is also very long, as I separated the classes based on which primitive they operated on, so all the `Parse` and `TryParse` methods belong to the string class. I also further wrapper the `Parse` methods, making `private ParsePrimitive` and `public ToPrimitive` methods. Is that an unnecessary layer of confusion? CharExtensions.cs ``` using System.Globalization; namespace PrimitiveExtensions { public static class CharExtensions { public static double GetNumericValue(this char c) { return char.GetNumericValue(c); } public static UnicodeCategory GetUnicodeCategory(this char c) { return char.GetUnicodeCategory(c); } public static bool IsControl(this char c) { return char.IsControl(c); } public static bool IsDigit(this char c) { return char.IsDigit(c); } public static bool IsHighSurrogate(this char c) { return char.IsHighSurrogate(c); } public static bool IsLetter(this char c) { return char.IsLetter(c); } public static bool IsLetterOrDigit(this char c) { return char.IsLetterOrDigit(c); } public static bool IsLower(this char c) { return char.IsLower(c); } public static bool IsLowSurrogate(this char c) {
- pattern minor 112d agoMySQL connection using a static connectionI have been using a static class to connect and retrieve information from a MySQL database and also reading about how static works in php. I'm still not sure if the code is bad or not and why (besides the usual static are dangerous). Also, code improvements suggestions will be appreciated. ``` class Database { const STOREDPROCEDURE = 1; const ADHOC = 2; private static $instance; private static function call() { if (!isset(self::$instance)) { self::$instance = new MySQLi('localhost', 'root', '', 'alfred'); if (self::$instance -> connect_error) throw new Exception(self::$instance -> connect_error); self::$instance -> set_charset('utf8'); } return self::$instance; } public static function query() { // $arguments = func_get_args(); $count = count($arguments); // $references = array(); for ($i = 2; $i prepare($query); if ($count > 2) call_user_func_array(array($stmt, 'bind_param'), $references); // $stmt -> execute(); $stmt -> store_result(); // $result = array(); while ($metadata = $stmt -> result_metadata()) { // $fields = array(); foreach ($metadata -> fetch_fields() as $field) { $reference[$field -> name] = ''; $fields[$field -> name] = &$reference[$field -> name]; } // call_user_func_array(array($stmt, 'bind_result'), $fields); // $rows = array(); while ($stmt -> fetch()) { $row = new stdClass(); foreach ($fields as $name => $value) $row -> $name = $value; array_push($rows, $row); } // array_push($result, empty($rows) ? null : $rows); // $stmt -> next_result(); } // $stmt -> free_result();
- pattern major 112d agoBusiness with dbcontext and static classMany speak of using dependency injection. I do not use repository. The entity framework is uow/repository. What is wrong with using static class like the one below? My context is a new instance per request. ``` public class TenantManager { public static IEnumerable GetAll(AppDbContext context) { return context.Tenants; } public static Tenant GetById(int id, AppDbContext context) { return context.Tenants.Find(id); } public static Tenant Create(Tenant entity, AppDbContext context) { var tenant = context.Tenants.Add(entity); context.SaveChanges(); return tenant; } public static void Update(Tenant entity, AppDbContext context) { context.Entry(entity).State = EntityState.Modified; context.SaveChanges(); } public static void Delete(int id, AppDbContext context) { var tenant = context.Tenants.Find(id); context.Tenants.Remove(tenant); context.SaveChanges(); } } ```
- pattern minor 112d agoStatic utility functions to turn arrays into SQL statementsI have an object that houses only static functions. The functions are stand alone and are not dependent on the state of the object. I hear that static functions are a nightmare in terms of testing, an anti-pattern if you will. I get it, the state of the object could be impossible to predict.. But these are stateless. My question is, Should I place these functions into a class of their own or am I ok by leaving them as static methods? ``` class Utility { public static function arrayToInsertStatement($table, array $data) { $sql = "INSERT INTO %s (%s) VALUES (:%s)"; return sprintf($sql, $table, implode(', ', array_keys($data)), implode(', :', array_keys($data))); } public static function arrayToSelectStatment($table, array $fields, $whereStatement) { $sql = "SELECT %s FROM %s %s"; if ($whereStatement) { $whereStatement = sprintf(" WHERE %s", $whereStatement); } return sprintf($sql, implode(',', $fields), $table, $whereStatement); } public static function arrayToUpdateStatement($table, array $data, $whereStatement = null) { $t_sql = "UPDATE %s SET %s%s"; $sets = self::arrayToKeyedArray($data); if ($whereStatement) { $whereStatement = sprintf(" WHERE %s", $whereStatement); } return sprintf($t_sql, $table, implode(',', $sets), $whereStatement); } public static function arrayToWhereStatement($data, $joinType = 'AND') { $joiner = sprintf(" %s ", $joinType); return implode($joiner, self::arrayToKeyedArray($data)); } public static function arrayToOrderBy(array $data) { $o = []; foreach ($data as $field => $direction) { $directionBool = substr(strtolower($direction), 0, strlen($direction)) === substr('descending', 0, strlen($direction)); $o[] = sprintf($field . ' %1$s', ($directionBool ? 'DESC' : 'ASC')); } return implode($o, ','); } public static function arrayToKeyedArray($data) { return array_map(function($value) { return sprintf('%1$s = :%1$s', $value)
- pattern minor 112d agoCalculating the number of elements of an underlying data structureI read many comments on this question that one really shouldn't use local classes for functionality like which my code provides, but I couldn't really put things into perspective and decide what better alternatives are there, if any (in terms of solving the problem locally). Some mentioned lambdas, although they also pinpointed that with recursion problems can arise if it is declared with the `auto` keyword. I would like to keep the logic inside of this method. Is it clean code or not? What do you think? (please don't mention `(int)size_t` casting; it's personal) The algorithm itself calculates the number of elements of the underlying data structure, excluding folders (`AnyMap` instances). ``` typedef std::map AnyMap; using boost::any_cast; class MyExtendedAnyMap { private: AnyMap data; // stores values and other AnyMaps as well that act as a folder basically public: int size() const { if(data.empty()) return 0; int calcedSize = 0; struct GoRec{ static void go(const AnyMap& anyMap, int& calcedSize){ for(const auto& kv : anyMap){ if(kv.second.type() == typeid(AnyMap)){ go(any_cast(kv.second), calcedSize); } else{ calcedSize++; } } } }; for(const auto& kv : data){ if(kv.second.type() == typeid(AnyMap)){ GoRec::go(any_cast(kv.second), calcedSize); } else{ calcedSize++; } } return calcedSize; } // ... } ```