instruction
stringlengths
71
39k
I'm about a week into learning pdo. I've created, with help from an example online, a database connection function. I have a config file with all my info (username, pass, database, host) and a function inside a file called db.php. Everything works great with the function below. Though, I have to put dataConnect() ...
I have a set of Service, and I want to partition them into ServiceClass, and have a reference from a Service to the Service class its belong. I am storing the reference in Dictionary<Service, ServiceClass>. In the code below, I want to split into five service classes. I feel the code below is not well written, such as ...
I've prepared a function using cURL to get a remote file to the local storage: /** * cURL - Get Remove File * * Function using CURL the get a remote file to the local storage. * * @param str $url Full remote URL * @param str $xml_path Internal path to the storage the file * @param str $xml...
Does this looks ok to everyone? NSFetchRequest *oldFetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *oldEntryEntity = [NSEntityDescription entityForName:@"Entry" inManagedObjectContext:oldContext]; [oldFetchRequest setEntity:oldEntryEntity]; int numbe...
I'm architecting a basic SSO solution to pass a user between two sites. Site A handles authentication against a user database and then generates links to Site B which pass a HMAC token comprising a nonce and the user's ID. The HMAC is hashed with a shared secret between the two sites. The following shows the token gene...
Recently I've tried to teach myself basic things about MySQL databases, however I received some help on Stack Overflow with creating a good database structure trying to avoid redundancy as much as possible. I finally came up with the database structure below and would like to know if that's the way to go and if not, wh...
I implemented a fixed sized priority queue. How can I improve my code? public class FixedSizedPriorityQueue { private final int capacity; private boolean sorted = false; private double smallest = Double.POSITIVE_INFINITY; private ArrayList<Double> list; protected static final Comparator<Double> com...
I found nvie's git branching model simple enough to grasp and suitable for my projects - but the frontend supplied at GitHub was far too complex for me to understand. Hence, I wrote this script to start and finish tasks, automatically running the related commands to speed it all up a bit (without it becoming too abstra...
I connected to the db, pull the data using fetch_assoc() (fetch_all(NUMB) is not available on the machine we are working with else this would be less of an issue). I get the returned data and load it into an array. However, it ends up in as an numeric array embedded inside another assoc array. What is the best way to h...
I have a feeling I might be doing it wrong, what major things would you improve in this code? The code is basically handling a tour on first login, showing it only for first login users (activated externally via calling activate) and preventing the step to apear again if the user has already seen it. I intentionally us...
I have this JavaScript to make a sidebar widget stick to a fixed position once the page is scrolled down, once you scroll to the bottom of the page where the footer div is I then un-sticky it so that the stickied div does not overlap the footer. It works great but I am not very good with JavaScript, so I am hoping to c...
I've just finished coding a Shunting-Yard algorithm implementation, following Wikipedia's C code example and I've got it to finally work. However, looking at my code now, the two "worker" methods seem bloated. I was wondering what your opinion was regarding the current code stubs and whether or not they need to be spli...
I'm working on a fairly mundane ASP.NET MVC app that allows users to do basic CRUD operations on a number of different domain objects. I'm trying to minimize duplicate code and boring, monkey code as much as possible, so I'm using AutoMapper to map types and MVC's scaffolding feature to spit out forms. I have a standar...
Pseudocode: // B = nxn binary matrix // Bm = resulting matrix for (i=1; i<=n; i++) { for (j=1; j<=n; j++) { if (B[i,j] == 1) { for (k=1; k<=n; k++) { Bm[i,j] = B[i,j] | B[k,j]; } } } } This is the Warshall algorithm written (in my way): B = [1 1 0 0 0; 0 0 0 1 0; 0 0 0 0 1...
I found out the hardway that access to DbContext in .NET is not threadsafe. I have a singleton for logging things using a dbcontext. The original version uses something like public Logger{ private MyContext context; private static Logger instance = new Logger(); private Logger(){ //init stuff, including cont...
Below is my method in checking if entity already exist. public boolean isExist(String genreName) throws PersistenceException{ EntityManager em = EMF.get().createEntityManager(); boolean flag = false; try{ Genre genre = em.find(Genre.class, genreName); if (genre != null) flag = t...
This is a code automatically converted from VB 6.0 to C#.net What is a safe and correct way to get rid of that GOTO statement? public bool IsDirty(bool checkChildrenInd) { bool result = false; //Determine if this object is 'dirty', or has been updated since it was created. if (Parent.NewInd) { ...
I am pretty new to TDD and is following problems on spoj.pl for practice. I need help with following code; it was my first attempt. Problem: Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. St...
I wrote this MySQL stored procedure to emulate DROP USER IF EXISTS (not available in MySQL). Any comments or identified bugs? DROP PROCEDURE IF EXISTS DropUserIfExists; DELIMITER $$ CREATE PROCEDURE DropUserIfExists(MyUserName VARCHAR(100)) BEGIN DECLARE foo BIGINT DEFAULT 0 ; SELECT COUNT(*) ...
Is this a good method to Read\Write packets using System.Text; namespace namespace { public unsafe class DataPacket { public DataPacket(byte[] buffer) { _buffer = new byte[buffer.Length]; System.Buffer.BlockCopy(buffer, 0, _buffer, 0, buffer.Length); } p...
The following code is from a university assignment of mine to write a classification algorithm (using nearest neighbour) to classify whether or not a given feature set (each feature is the frequency of words in an email) is spam or not. We are given a CSV file (the training data) with the frequencies, and an integer (...
I am trying to read a line ending in \r\n from a Handle. This is an HTTP header. I’m fairly new to functional programming, so I tend to use a lot of case expressions and stuff. This makes the code very long and ugly. handleRequest :: HostName -> Handle -> IO () handleRequest host handle = do requestLine <- readHead...
I am a single developer on a numerics project. As it is growing, I would like to improve the Makefile the general organisation of the project structuring of the files workflow As it stands now I have a few classes (where a few depend on each other) and a main.cc. In total maybe 20 files. From that the executable is ...
I am developing a meta-data framework for monitoring systems such that I can easily create data adapters that can pull in data from different systems. One key component is the unit of measurement. To compare datasets which have different units I need to convert them to a common unit. To build adapters I need to have a ...
I'm looking at some code that goes a bit like this: class Foo { public int Frob; public int Frib; } class Bar { public Foo Left; public Foo Right; } public void ProcessBars(Bar[] bars) { this.LeftFrobs = new int[bars.Count]; this.RightFrobs = new int[bars.Count]; this.LeftFribs = new int[bars.Count]; t...
I've created this very small header that allows direct creation of threads from lambdas. I can't find anything else similar on the net so I want to know whether there are any problems with this that I have not thought of. It is based on tinythread++, but can easily be altered to work with pthread or other threading lib...
These two methods do the exact same thing (or at least they are supposed to!). They both pass a simple test based on a mock context. Neither has been exposed to any integrated testing yet. Would one of the methods be preferred over the other (and why)? Does anyone see any glaring mistakes in the LINQ version (this...
I couldn't find an example on how to have a custom function inherit jQuery's functions while leaving the original jQuery function I'm inheriting from unchanged (I wanted my function to have a read but didn't want it to get added to $.Deferred) This works, but I really suspect it isn't the right way to do it. var Deferr...
I'm upgrading/rewriting our online client portal and wondering if my log in page code looks okay so far. during this rewriting/learning process I am upgrading a number of things: PHP 5.2 to 5.3.5, MYSQL 4.1 to 5.5, md5() to SHA512 using pbkdf2, salt and multiple iterations, MySQL functions to PDO, HTML4 to 5. I'm learn...
This is my first Wordpress plugin. I would love some input from the WP/PHP/JavaScript gurus out there. It's a simple plugin that saves a post using ctrl-Q and opens a preview in a new or current window. <?php add_action('admin_menu', 'plugin_admin_add_page'); add_action('admin_init', 'plugin_admin_init'); a...
my connection code: <?php try { $pdo = new PDO("mysql:host=localhost;dbname=game; charset=utf8", "root"); } catch(PDOException $e){ echo $e->getMessage(); } ?> my class code: <?php include './database/config.php'; class DB { public function dataWarrior($battle,$name,$type){ global $pdo...
How can I improve this code? jQuery: $.ajax({ url: "get_attributes.php", type: "post", datatype: "json", data: { wtype: red_type }, success: function (data) { var toAppend = ''; if (typeof data === "object") { toAppend += "<tbody>"; toAppend += "<tr></td><td...
I plan to use the following approach to audit the tables that represent user-editable configuration of an automated system (over the course of system's life these will be inevitably extended in their numbers and stuffed with more columns). This approach will not be applied to main data tables as those are automatically...
I am using scrapy framework for data scraping and dumping item in MySQL database. Here is my pipeline that is inserting output to MySQL, but its taking so much time. Any suggestions on how to optimize this? class MysqlOutputPipeline(object): def __init__(self): dispatcher.connect(self.spider_opened, signals.spide...
I have two classes one base Foo class and one derived Bar class. Each class has its own associated settings class that can create a new instance from the Load method. This way all derived class settings can be stored in one list of FooSettings. public abstract class FooSettings { public int a; public int b; ...
please review my implementation of a FIFO data structure that guarantees thread-safe access without locking. I removed the license header block and all Doxygen comments. The original version (along with some tests) is available from here: https://github.com/fat-lobyte/atomic_queue It should compile with Clang >= 3.1, ...
def sieve_of_erastothenes(number): """Constructs all primes below the number""" big_list = [2] + range(3, number+1, 2) # ignore even numbers except 2 i = 1 # start at n=3, we've already done the even numbers while True: try: # use the next number that has not been removed already ...
I'm teaching myself code using Zed Shaw's Learn Python The Hard Way, and I got bored during one of the memorization lessons so I thought I would make a random D20 number generator for when I play RPGS. How can I make this code better? Is there anything stupid I'm doing? import random name = raw_input('Please Type in...
I've written a Base64 encoder/decoder, which works great. Now I want to see if I can get it working better. I've optimized as much as I can think of, but it may be missing some things. The encoder can encode a 160 MB file in 30 seconds, but the decoder takes nearly 60. So far the optimizations I've done are: Pre-alloc...
This function is used to get the mime type of any given file. The intended purpose was to have it working within any of our servers that vary from the latest PHP version down to PHP 4. /** * Get the mime type for any given file. * * @param str $filename Path to the file including the filename * * @return mixed bol...
I have written an code to find if a given tree is a BST. Need help in refactoring it. Some of the things I am looking are. Getting Rid of temp variables (As suggested by Martin Fowler) Combining leftTreeMax and RighTreeMin methods Better naming of methods. Also it will be great if someone can suggest other refactorin...
Problem statement: Write a CashWithDrawal function from an ATM which, based on user specified amount, dispenses bank notes. Ensure that the following is taken care of: Minimum number of bank notes are dispensed Availability of various denominations in the ATM is maintained Code should support parallel withdrawal...
Between .NET's built-in collection libraries and LINQ extension methods, I never have to use arrays. An unfortunate consequence of this is that I am probably less competent in working with this very important Type than I should be. To help myself get a better grip on the Array class, I wrote some C# helper methods th...
I have created this extension method that can be used to run a function with a timeout applied to it. Is this a sensible way of doing it? public static class FuncExtensions { public static T RunUntil<T>(this Func<T> predicate, TimeSpan timeout, string taskName) { var result = default(T); Action ...
First I tried to fetch this program as close to pseudo code where I must follow all imported items, all method definitions, and all defined variables; anything else was my choice. After I created working program that best represent the sample run of output we were provided in my homework documentation, I decided to cre...
The following program is supposed to be a (command line) calculator that parses expression following syntax similar to Lisp's S-expressions. Some examples: $ echo "(+ 5 5)" | ./a.out 10.000000 $ echo "(+ (- 3 2) (* 9 2))" | ./a.out 19.000000 $ echo "(/ 24 6 2)" | ./a.out 2.000000 $ echo "(/ 24 (/ 6 2))" | ./a.out 8.00...
I'm quite new to Python and would love to gather feedback on my code. I've written a piece a script that allows me to search all file or directory names within a folder matching a particular pattern. The caller can specify if the function should be recursive or not. It's only a basic script I would love to know how it ...
I am a high-school freshman who is kinda new to Ruby, and I am doing a small project on Ruby. One of the big things that I want to get out of this project is how to follow the "Ruby standards" that programmers should follow. Being as new as I am, I have no clue what I should/shouldn't do with this program. Can anybo...
I saw that one of the interview questions could be building a pascal triangle. Is there anything wrong with this particular solution I came up with? function pascal_r($r){ $local = array(); if($r == 1){ return array(array(1)); } else { $previous = pascal_r($r - 1); array_push($local, 1)...
This is sort of a follow up to my post yesterday. I'm a relative newbie to Python and before I made a d20 dice roller for RPGs. Now I've made a dice roller for any type of dice, and I would love some feedback on this code. from random import randint def roll(sides, number_of_dice): """Rolls Dice.""" return [...
I'm learning C, specifically OOP in C. As practice, I wrote a dynamically-expanding array. dynarray.h #ifndef DYNARRAY_H #define DYNARRAY_H typedef struct DynArray { int length, capacity, *arr; void (*extend)(struct DynArray *dynArr); void (*insert)(struct DynArray *dynArr, int val); v...
I recently started to learn more about OOP in PHP and I created a website for testing. I have 4 classes: database, user, posts, comments. This is a simple database.class.php: class DB { protected $pdo; protected $engine = 'mysql'; protected $host = 'localhost'; protected $db_name = 'test'; ...
I could use some review on this Auth class, as I'm sure it could use many improvements! I wrote this fairly quickly, so please forgive any overseen bugs. Example usage: // Login a user if (Auth::attempt($_POST['username'], $_POST['password'])) { echo 'You have successfully logged in.'; } // Check if the user is a ...
I really don't like the so many return statements. Anyone think that this could be refactored more? public function validate($value, Constraint $constraint) { if('' === $value || null === $value) { return; } if(!preg_match('/^[0-9]{7}([0-9]{3})[0-9]{1}$/', $value, $matches)) { $this->contex...
I'm trying to come up with a scalable way of TDD'ing my Scala code, in particular managing dependencies. In this example, I've TDD'd part of the classic river crossing problem where we have people on each side of a river and move people from one bank to another. I wanted to unit test the smaller functions on their own ...
I understand that this animation code is outdated: [UIView beginAnimations:@"Move" context:nil]; [UIView setAnimationCurve:UIViewAnimationCurveEaseIn]; [UIView setAnimationDelay:0.08]; self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); [UIView commitAnimations]; What are the m...
I have two projects, a native C++ DLL (pinvokelib.dll), and a C# console application (pinvoketest.exe) which calls the DLL. I'm curious if the way I do P/Invoke is considered best practice. Here is my C++ code: extern "C" __declspec(dllexport) int test(int val); int test(int val) { return val * 2; } And my C#: us...
How can I improve this? jQuery $(function() { $('button').button(); $('#tabs').tabs(); $('.ui-state-error').hide(); $('.btnlogin').click(function() { $('#login .ui-state-error').hide(); if($('#login_email').val().trim() == ''){ $('#login_email').focus(); } els...
Currently, I have this code snippet, but it's a little bit slow: % input image input_matrix = imread('placa.bmp'); [rows cols] = size(input_matrix); % rotation degree = 30; radians = (pi * degree) / 180; theta = radians; % output matrix t_matrix = input_matrix; t_matrix(t_matrix == input_matrix) = NaN; % transfor...
I am doing a project where I use DLL's as run-time modules or plugins. To do this, I use the Windows LoadLibrary() and FreeLibrary() API calls to call two functions exported by the DLL. I decided to make a class so dealing with the DLL's would be easier. Is there anything I can add to my class to make it better, is the...
I've written a simple program in Python which does the following: Input: an integer \$n\$ Output: a \$2^n x 2^n\$ matrix containing small \$L\$s which fill the entire matrix except one single square. Each L has its unique number, and consists of three squares. It's a fairly simple program, and you can see clearly what ...
I wrote this class which is a priority queue based on a numeric property of any object. As far as I can tell, the following code is working as intended. Are there any stylistic tendencies that I am getting wrong, or any gotchas I should look out for? //Constants PriorityQueue.MAX_HEAP = 0; PriorityQueue.MIN_HEAP = 1; ...
This script is meant to look for an id in the data attribute in each containment div, then send an Ajax call to get the amount of retweets, calculate the karma based on those retweets and then display that number in a div. This code looks like spaghetti. How do I improve this to make each function more independent? Th...
First off, let me say that this article pretty much changed how I program, for the better. Until I read this article, I was a spaghetti programming master --- if there were awards for crappiest, least organized, and impossible to read programming, I would have been world champion. But that article taught me to utiliz...
I have written this jQuery code to traverse the HTML markup. Basically, I am selecting data-icount attribute of each anchor tag and appending it to anchor text as (28) e.g. the ALL becomes ALL (38) in the example. 38 here is the sum of all the data-icounts under that li. Similarly, summers become summers (2) because it...
I would really appreciate a review of my first game. It is a Bejeweled-like game written in Python with Pygame: import pygame, random, time, sys from pygame.locals import * pygame.init() NUM_SHAPES = 7 #7 PUZZLE_COLUMNS = 6 #6 PUZZLE_ROWS = 12 #12 SHAPE_WIDTH = 50 #50 SHAPE_HEIGHT = 50 #5...
I'm using Node.js and am creating some models for my different objects. This is a simplified version of what they look like at the moment. var Foo = module.exports = function () { var values = { type: 'foo', prop1: '', prop2: '' }; function model() {} model.init = function(val) { _.extend(values...
I'm trying to write a simple class to represent a text file - which one would think should be quite easy. I don't intend to add all bells and whistles to fully represent a text file just enough to be able create/open read and write etc. The more I look at it the more I think that it's a bad idea or rather that I'm appr...
I was working on a task to implement auto suggest from an array of couple of thousands of strings. Of course, the first and the easiest implementable was to go through each element and do a[i].startWith(query). Technically the time complexity of this algorithm then would be \$O(n+(q*m))\$. Here, n equals the number of...
I've quickly made a function to deny or allow access to files that are only used thru Ajax calls. Key Generator /** * Generate a key for file access permission * * Function that returns a key to grant access to a PHP file * that will be consulted by an ajax call. * * @param str $salt Any given string to append ...
This gets every form element and calculates its width, then changes the input fields depending on the parent-form width: $ -> # Alter 'input' Width inputResize = -> $('form').each -> tF = $(this) formWidth = tF.width() tF.find('input').each -> tE = $(this) inputBorder = (tE.outerWidth() - t...
I've an AbstractMessage object (a hierarchy, actually). It represents a small text message and can be sent using different transport methods: HTTP, REST and a "mailer" transport. Each transport relies on an external library for executing the transport itself, injected using a DI container. Message itself may have diffe...
I have a class extending the Dictionary class. This class is used for storing some information (modeled in CustomClass) and accessing it through an integer ID. To extend this class I have added a TryAdd method, specific to my workflow, which implement different behaviours for the cases of trying to add a new or a alrea...
This is my socket.cpp #pragma hdrstop #include "MySocketClient.h" MySocketClient::MySocketClient() throw(SocketException){ WSAData data; InitializeCriticalSection(&sect_); if(WSAStartup(MAKEWORD(2,2),&data)!=0){ throw SocketException("Cant load WinSock library"); } connected_=false; } /...
I have a scenario wherein I have to filter a collection in a PagedCollectionView. The filter criteria are Name and status which are checkboxes with Enabled and Disabled labels. If Enabled is checked it should filter out the list with all enabled rules and vice-versa. I have given it a try, but I believe this isn't the...
I'm writing a simple automatic backup/versioning bash script. It should basically mirror a directory structure somewhere, and then copy files over there when they've been altered. The ghost files should then be named filename.YYYYMMDD-HHMMSS.ext (the included date/time being the time of last modification). This is what...
I'm currently studying Java by myself. The book I'm using (while very good) lacks feedback (obviously). While trying to write this program, I found myself solving most of the problems I've encountered by trial and error and makeshift solutions, which I fear might have led to some haphazard code. A good example would...
I'm a total newbie teaching myself via Zed Shaw's Learn Python The Hard Way and I've gotten bored over a week long memorization lesson, so I thought I would make a character generator for a pen and paper RPG I'm writing. I havent really read about if statements or things like that, so I am experimenting here. ########...
I'm new to Android and I wanted to create a class that would load an ad inside the current layout. All the layouts have a RelativeLayout id=adLayout From my main, I have: AdLoader al = new AdLoader(); al.GrabAd(this,"123"); Then on my AdLoader.java class I have: public class AdLoader { private DfpAdView adView; ...
Here's a class I created to parse XML to create an IList. It seems to me that this is something that will be done a lot in general by a lot of different programs. Is there a more standard way of doing this using .Net and C# /// <summary> /// public class CListFromXml {} /// Created By: Michael Fitzpatrick, 2012 Sept 25...
I am looking for some ideas on how this could be improved: switch ($periodValue) { case "lastmonth": $until = mktime(0, 0, 0, date('n'), 1, date('Y')); $from = mktime(0, 0, 0, date('n', $until) - 1, 1, date('Y', $until)); break; case "last3month": $until = mktime(0, 0, 0, date('n...
I have written a PDO wrapper and a class file like a model. It's looking good so far, but I'm just confuseed on where I should put the try/catch block. Would it be better to place it in the PDO wrapper (pdoDatabase.php), mobile.php (model) or test.php? pdoDatabase.php class pdoDatabase { public $db; private $sth; pr...
Please suggest ways of cleaning up this code. Hashtable newValues = e.Values; string NewPosition = null; string NewFirst = null; string NewLast = null; string NewEmail = null; int NewAppt = 0; if (newValues["Position"] == null) { NewPosition = ""; } else { NewPosition = newValues["Position"].ToString(); } if...
How can I make this more readable? public class RssFeed { string url = "http://www.pwop.com/feed.aspx?show=dotnetrocks&filetype=master"; public string responseBody; private string DATE_FORMAT = "ddd, dd MMM yyyy HH:mm:ss \\E\\D\\T"; public Story[] Getstories() { getContent(); var...
I have a data stream of bytes and I'd like to get a little endian encoded int32 from four bytes. Is there a better way than to do this like the following code? package main func read_int32(data []byte) int32 { return int32(uint32(data[0]) + uint32(data[1])<<8 + uint32(data[2])<<16 + uint32(data[3])<<24) } func ma...
I have some ViewModels that have a lot of parameters like this one: public class ProductsMainViewModel : NotificationObject, IActiveAware, ... { public ProductsMainViewModel(IProductRepository productRepository, IWarehouseRepository warehouseRepository, IUnitOfMeasureRepository unitOfMeasureRepository, ...
I have learned to make a carousel image slideshow script with JavaScript. I think it's better to learn it from the basic than just from the framework (instant script), but I'm a newbie. I wrote this script using my technique, but I think it's terrible. var runCarousel, runTimer; firstval = 0; secondva...
Task: per host concurrency limits for web crawler (map[string]Semaphore). I considered chan struct{} (chan bool) approach, but essentially it would not make code a lot easier because the main hurdle is to delete unused keys from map. And then semaphore takes constant memory - good property - as opposed to chan which gr...
http://jsfiddle.net/hrishikeshp19/VyDsu/21/ Following is my HTML body: <div id="header"> <div id="logo"> </div> <div id="headercontent1"> </div> <div id="headercontent2"> </div> </div> <div id="buttons-container"> </div> <div id="panels-container"> <div id="panel1"></div> <div id="panel2"></div> ...
I want to generate a random alphanumeric string in ruby, as succinctly and efficiently as possible. The following solution works, but is obviously not very efficient. Please review the following code, bearing in mind that I am trying to keep it as succinct and readable as possible while improving efficiency. Be sure t...
In my never-ending quest to improve my coding skills I am requesting peer input on the following code logic. I am asking because I'm -NOT- an expert, but would like to be one day. Source material and recommended read is greatly welcome (no, do NOT point me to the PHP manual) especially for code formatting, unit testing...
Context As an exercise for myself (I'm learning clojure). I wanted to implement the Depth-first search algorithm. How I did it Using recursion (def graph {:s {:a 3 :d 4} :a {:s 3 :d 5 :b 4} :b {:a 4 :e 5 :c 4} :c {:b 4} :d {:s 4 :a 5 :e 2} :e {:d 2 :b 5 :f 4} :f {:e 4 :g 1}}) (def stack [[:s]...
The createReport method takes around 30 seconds to execute and I was wondering how I could optimize it. I'm using the Interop.Excel class and the workbook I'm importing to is very formula intensive. Dim UserDate As New Data_Entry_Form.UserDate Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkS...
I am writing a networked audio application that sends the audio in 320 byte chunks, later I need to provide the player a bigger amount of bytes to play so I try to merge 2 or more chunks into one buffer and return it, well the code works but I hear some small audio artifacts, any ideas if the code is correct? -(NSData*...
For experimental and learning purposes. I was trying to create a sorting algorithm from a hash function that gives a value biased on alphabetical sequence of the string, it then would ideally place it in the right place from that hash. The reasoning is that theoretically if done right this algorithm can achieve O(n) sp...
This is my first complete program written in F# (I was from C# and occasionally do interop) and I believe there are quite a few places I didn't tackle well in terms of coding practice. Unblock Me / Rush Hour: 5 b b k j 4 c c c k j 3 a a k i l 2 d g g ...
I'm trying to learn some Scala and decided to try to tackle some Project Euler problems. For problem #48, coming from a Python background, my solution is the following one-liner: print ( (1 to 1000).map(i => BigInt(i).pow(i)).sum % BigInt(10).pow(10) ) Is this idiomatic? Is there a simpler/more readable solution?
There are three servers. I want to assign a job to a server which has least NotStarted jobs. I have achieved this, but my code is very lengthy. I don't know how to minimize my code without changing my concept. Here is my code: public List<int> GetPaServer() { List<int> PaServers = new List<int>(); using (PaEnti...
I understand that I should use prepared statements to prevent SQL injection. Unfortunately, having read the PHP docs on the matter I am none the wiser. Here is one of my simple active record SQL queries in a CI2 model, could someone show me an example of how I might turn this into a prepared statement - do I even need ...
I thought it was a good idea to use this in my C++ projects: class CRAIICall { public: typedef void (WINAPI * FnType)(HANDLE); CRAIICall(HANDLE h, FnType fun) : m_h(h), m_fun(fun) {} ~CRAIICall() { if (m_h) { m_fun(m_h); } } private: HANDLE m_h; FnType m_fun; }; and use it ...