instruction stringlengths 71 71.9k |
|---|
[Bindable]
public class ProductsCache
{
private static var _products:ArrayCollection;
public function get products():ArrayCollection{
return _products;
}
public function set products(value:ArrayCollection):void{
_products = value;
}
}
By the name of the class you see my intentions ... |
I wanted to have a python container in which every element is a key (like in a set), but still supports mapping (like a dict) between the elements.
To get a container which supports this idea the elements have to be unique like in a set and the mapping between the elements has to be bidirectional. I couldn't find such ... |
As I was trying to demystify the Android AsyncTask functionalities, I wrote this sample app to test it. Please review my code and suggest possible improvements:
public class AsyncTaskExampleActivity extends Activity implements OnClickListener{
private Boolean success = true;
private static AsyncTaskExampleActi... |
I have a block of text where several arrays are printed out, with a name and values:
VAL1=10 20 30 40 50
VAL2=4 8 15 16 23 42
I have a function that looks for the value name, and sets an array of these values:
bool FetchValueArray(char* source, char* name, char* typeFormat, int count, void* destination, size_t destEl... |
The following is a function that I wrote to display page numbers as they appear in books.
If you enter the list [1,2,3,6,7,10], for example, it would return:
1-3,6-7,10
This seemed like a nice example of how the dictionary data type can be used in Python.
Is there is an even more code-efficient way to do this?
def for... |
This code connects to COM 3 which has a broadband card and sends a command that returns the RSSI value. I use this program to see patterns in signal strength in certain areas.
#include <Windows.h>
#include <iostream>
#include <string>
int main()
{
HANDLE hSerial = CreateFile("COM3",GENERIC_READ | GENERIC_WRITE,0,0... |
I'm refactoring a set of classes which does some price calculations.
the calculation is done based on many parameters.
The code is :
public interface IParcel {
int SourceCode { get; set; }
int DestinationCode { get; set; }
int weight{get;set;}
decimal CalculatePrice();
}
public abstract class GeneralPa... |
I've created a simple asynchronous execution engine and I would like some help identifying places it can be improved. The basic function of the system is to monitor MSMQ and Service Broker queues and execute any tasks that come through on them.
Here is the code:
using System;
using System.Collections.Generic;
using S... |
As a disclaimer, this is the first function I have EVER written in Lisp or ELisp. Please, bash it as much as you would any other piece, but don't judge me for it please! :)
So, I realized I wanted a way to rename files without all the hassle of reopening the file etc. I googled and found a function at https://stackover... |
Due to software constraints, I cannot use the standard libraries, cmath, algorithm, templates, inline, or boost. I am also using standard C (ISO C99) such that array is not a reserved keyword like it is in Visual Studio.
Here is the custom sine, pow and factorial functions I wrote (assume they are all part of the same ... |
I'm working on a small program to add or remove certain entries from the Windows registry, and I'm getting all tangled up in IF and TRY conditions. I've spent hours chasing bugs, usually logical ones, trying to accomplish what is conceptually very simple. The more I work on and "improve" the code so that it works in mo... |
I'm trying to implement my own A* pathfinder, but the voices in my head scream of better ways to do this. Probably because I'm exceeding Python's default maximum recursion depth of 1000.
class PathFinder():
## grid is a list of 8 sub-lists, each containing 8 nodes.
## start and goal are tuples representing th... |
internal void ShiftSwapInstrument(SwapCurve shiftedCurve, string swapToShift)
{
if (SwapExists(shiftedCurve, swapToShift))
{
var rateToShift = shiftedCurve.Swaps.Single(r => r.Description() == swapToShift);
rateToShift.Rate = rateToShift.Rate + 1 / 10000.0;
return;
}
throw new Pdh... |
In a homework, there is an exercise in which I have a script that is used to search for a password.
One of the questions is if is possible to make it "more intelligent", and I'm stuck on it.
#!/bin/bash
space1="a b c d e f g h i j k l m n o p q r s t u v w x y z"
if [ $# -le 1 ]
then
echo "Ussage: " $0 SALT PAS... |
def range_find(pageset,upperlimit=1000):
pagerangelist=[]
for page in range(0,upperlimit):
if page in pageset and previouspage in pageset:pagerangelist[-1].append(page)
elif page in pageset and not (previouspage in pageset):pagerangelist.append([page])
else: pass
previouspage... |
I'm wondering if there is a simplier regex I could use in my code to remove the beginning and ending char in a line. Maybe combine some regex's? In this instance, it's a comma at the beginning and ending of a line. My output should be the fields seperated into CSV format.
#!/usr/local/bin/perl
use strict;
use warnings... |
I don't actually know much about how base32 (or base64) works, but I noticed that there was no official base32 implementation in PHP, so I figured I'd make one.
I Googled around a bit to figure out how it works, and found this page. Using the examples at the bottom, I hacked up this base32 class. GitHub project: http... |
If I had many different Models that could all, through logic encapsulated by an adapter, produce items of type T, then I might maintain a producer/consumer component through the techniques demonstrated in the code.
When I came up with this, it seemed novel to overlay a producer onto a linked list - the reflection in th... |
I wrote this palindrome extractor. And even though it works, and I can solve the challenge with it, it feels very Java-like. I was wondering what adjustments I could make in order for it to be more functional.
import collection.mutable._
object Level1 {
def palindrome(input:String) = input.reverse == input
d... |
Basically, I made a simple app for my Android, where it picks a random question for you, and picks specific answers. Only 1 of the answers is correct, while other's aren't.
Also, after editing the QBegin method, it started to give me questions but with wrong answers.
TextView question;
private int qType = -1;
priva... |
def range_find(pageset):
pagerangelist=[]
for page in list(pageset):
if page in pageset and page-1 in pageset:pagerangelist[-1].append(page)
elif page in pageset and not (page-1 in pageset):pagerangelist.append([page])
pagerangestringlist=[]
for pagerange in pagerangelist:
... |
I deal with hundreds and hundreds of names each week. These names (along with other pedigree information) are stored in a database. Typically, I get these names in all sorts of formats, mainly proper and in all-caps. I needed an easy way to convert the names (especially last names) to their proper format:
McDonald
Mac... |
What would you do to improve upon this boilerplate empty stored procedure, being mindful of the delicate balance between length, complexity, performance and clarity?
-- =============================================
-- Author: The usual suspects
-- Create date: 10/06/2011
-- Description:
--
-- Nice long descripti... |
Please give me any comment about these codes. Does it enough to prevent SQL injection? What I have to do to make the code better?
<?php
/**
* Description of MySql
* @name MySQL PDO
* @version 1.0
* @author Yauri
*
*/
class MySql {
private $mPDO;
public function ... |
The following function accepts a list of Topic entities, retrieved from a database using LINQ-to-Entities. Each Topic has an Id, Title and ParentId.
I want to populate an ASP.NET TreeView control, and so the function is creating a hierarchy of the Topics based on their ParentId. If a Topic has no parent, its ParentId... |
I wrote a Python method to convert an object and a subset of its attributes into a JSON string with a given field as the key.
There's a lot of string concatenation, and I'm not too sure what the best way to do that in Python is.
I'm also wondering if attr.replace('"','\"') is sufficient to sanitize input.
def to_json_w... |
I have this class hierarchy. I want to apply generics to it but don't know how to do.
AddWikiTask, ScanTask and RescanTask are subclasses of AbstractWorkerTask.
DictionaryScanner has 3 functions to check if all tasks finish. How to prevent duplicate code in 3 those functions?
This is class hierarchy
public abstract... |
I've written an algebraic notation to use for moves in a game and I'm currently writing code to parse the information from the notation. I'm doing this using regExes. This is coded in HaXe.
For example, two functions in the parser would look like this:
public function getMoveType(gameText:String):String
{
var move... |
#!/bin/bash
# Used to add/remove printers from system (lp)
# Copyright Fresh Computer Systems Pty Ltd.
GREP_OPTIONS='--color=tty'
export GREP_OPTIONS
sanity() {
# Are we root?
if [ $EUID != '0' ]; then
exitError "You must be root to run this script." 1
fi
if [ ! -x /usr/sbin/lpadmin -a ! -x... |
Detecting types in JavaScript sucks
This answer discusses the standard way to check the type of a JavaScript object (specifically, an array):
The method given in the ECMAScript standard to find the class of
Object is to use the toString method from Object.prototype.
if( Object.prototype.toString.call( someVar ) === ... |
So, I wanted to avoid an
if (...) { }
else if (...) { }
else { }
scenario to avoid duplicating code. After a little playing, I got the following working (works from the testing i've done). Am wondering if anyone has any feedback on this approach or suggestions on on possible improvement?
Sometimes I think I know what ... |
Here is some code to insert a new line escape sequence after a certain number of characters (for fixed width displays)
private string spliceNoteText(string text)
{
StringBuilder sb = new StringBuilder();
int maxWidth = 70;
int blockOfText;
for (int i = 0; i <= text.Length; i +=... |
I have the following code, which gets the data from 3 text files and puts them into 3 variables. How can I refactor this to make it smaller?
$handle = fopen($template_filename, "r");
if (filesize($template_filename) > 0)
{
$email_template = fread($handle, filesize($template_filename));
}
fclose($handle);
// get th... |
Connection stored in the xml config file.
<?xml version='1.0' ?>
<database>
<connection>
<dbtype>mysql</dbtype>
<dbname>shoutbox</dbname>
<host>localhost</host>
<port>3306</port>
<user>admin</user>
<password>admin</password>
</connection>
</database>
class DBWrapper {
/**
* Stores ... |
This code is for a simple language quiz. It fetches two words and related audio files via a JSON call, presents the user with an image that matches one of the words, and challenges the user to make the match. My code works but it's a little repetitious and ugly. I'd like to see how the experts would propose rewritin... |
I am using the following code to add nodes in a treeview. Is there a better or more compact way of doing this by using LINQ?
foreach (Plan plan in this.IncomingPlan.Plans)
{
foreach (Document doc in plan.Documents.Where(d => d.Name.Equals(this.DocumentName, StringComparison.OrdinalIgnoreCase)))
{
foreac... |
I'm working on a small project that does mathematical calculations based on selected data in a JTable. The goal is to make the program fairly adaptable for adding new mathematical calculations in the future. For reference, some of the current calculations are: calculating the mean (average) of a set of data; calculatin... |
With a DateTime object, it's easy to get, for example, 11 October 2011 by using:
d.ToString("d MMMM yyyy");
However, there seems to be no built-in method to get the output 11th October 2011.
So here's a possible extension method.
public string ToStringWithOrdinal(this DateTime d) {
var sb = new StringBuilder(d.Day);... |
I've only been coding C# a few weeks and was just hoping for a little constructive criticism of a socket server I've been working on:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace NetworkCommunication
{
public class TCPSo... |
I am looking a good way to fill up the elements of a lower triangular matrix from a list.
I currently have this:
PadRight[#, s] & /@
Prepend[Take[elems, # + {1, 0}] & /@
Partition[Accumulate[Range[0, s - 1]], 2, 1], {}]
where elems is the elements-list and s is its length.
Perhaps the best way is preallocation p... |
I feel like this isn't the most effective nor efficient way of doing things:
line.stop(true, true).show('slide', {direction: whichway}, speed-150, function() {
title.stop(true, true).fadeIn(speed-200, function() {
sub.stop(true, true).show('slide', {direction: whichway}, speed-50, function() {
subtext.stop(... |
function order_ignore_the($a, $b){
// orders sentences ascending alphabetically, ignoring the work "the"
$args = func_get_args();
foreach($args as $k=>$v){
$sort = explode(" ",$v);
$args[$k] = (strtolower($sort[0]) == "the" ? $sort[1] : $sort[0]);
}
return s... |
Any tips on how to improve this simple recursion program?
#include <iostream>
#include <cstdlib>
using namespace std;
int findSum(int*, const int, int, int);
int main()
{
int length = 5, sum = 0, n = 0;
int list[length];
for (n; n < length ; n++ )
{
list[n] = n + 1; //initializes array element... |
I want to limit the load so I rewrite the most expensive method and add caching, both memcache and cache-control:
class GeoRSS(webapp.RequestHandler):
def get(self):
start = datetime.datetime.now() - timedelta(days=60)
count = (int(self.request.get('count'
)) if not self.request.ge... |
We have several legacy programs (VB6) generating Excel report. They are scheduled tasks running on a server. Yes, violate this.
As a result, we've got lots of "dead" instances of Excel on the server. I intend to write a program to clean these dead Excels. What is the correct way to kill an idle instance? I know it's no... |
I've written a cache class which implements a last-recently-used (LRU) cache. I would like to know what you think about it and whether it's worth using it or not (due to performance issues for instance).
#include <functional>
#include <iterator>
#include <list>
#include <utility>
#include <unordered_map>
#include <boo... |
I am writing simple file validator for my java ee app and I am stack with my class api. I need specific error descriptions, but also I would like to have boolean values indicating whether file is valid or not. Please give me some hints how to do it 'smart'.
package pl.poznan.put.ims.business.attachments;
import java.u... |
I have three ways of reordering a list (think baseball order) and I am sure you can come up with more. What is a the best way?
For example if input is list is 1,2,3,4 and current is 3 then the output should be 3,4,1,2.
Another example list: 1,2,3,4 and current 4 output is 4,1,2,3.
public void reOrder(List<String> list... |
I am attempting to build a small JavaScript library (similar to jQuery)
The purpose behind this is mostly a learning exercise, so asking why I don't just use an existing library is moot.
So far I have just got my basic constructor, a 'caller' function to invoke a new object, and some basic functions for an example.
var... |
I just wrote a small card game in JavaScript, CSS and HTML. This is kind of my first project that I have cared about front-end. So I got things to work, but I am sure that this is not the smartest way to do it.
If someone could give me some guidelines on how this would have been done in a more professional way I would ... |
I found this method kinda tough to get for a beginner like me, but I tried to do my best, and here's what I came up with.
Is this good code regarding performance? Is there anything wrong with it?
var notPrime = [] ;
var prime = [] ;
var n = prompt("Enter n: ");
for(var i = 2 ; i < n ; i++ ){
if(notPrime.indexOf(... |
I'm trying to validate an HTTP Request, and first I want to get sure that all of the information has been posted (and then I'll check the correct format of each incoming data), so to get sure that no Form Spoofing attack is made. However, since this HTTP Post comes from a form, and that form contains almost 40 fields, ... |
This is a sample program that I intend to post as part of a series of beginner level Java tutorials. Please provide any feedback on improvements that would make example more clear or illustrate/emphasize best practices. The example drawns a ball object to a panel on a mouse click and then moves it randomly with anoth... |
Suppose we have an enum called "Planet" and it has a custom attribute of class "PlanetAttr",
these methods will give you the attribute value for a given Planet value:
private static PlanetAttr GetAttr(Planet p)
{
return (PlanetAttr)Attribute.GetCustomAttribute(ForValue(p), typeof(PlanetAttr));
}
private static Mem... |
I am using 2 nested SortedDictionaries to construct sparse matrix
Here is the custom simularity(sim) function I wrote . Now it has O(n^2) complexity. I looking for suggestions to improve robustness and efficiency.Thanks for any help.
double
a = 0, b = 0,
sqrta = 0,
sqrtb = 0... |
Is there anything you would change about the following function? I welcome any feedback on style, correctness, etc. Thank you for reading.
Some of my questions are:
Obviously, I catch the exception and convert it to a return value because I don't want to take down the application in case of an error. Would it be bette... |
My implementation:
Array.prototype.binarySearchFast = function(search) {
var size = this.length,
high = size -1,
low = 0;
while (high > low) {
if (this[low] === search) return low;
else if (this[high] === search) return high;
target = (((search - this[low]) / (this[high] - this[low])) * ... |
There are a several articles about true data access in MVC. I tried to make the best one according to the architecture flexibility. My way is following:
ADO .NET Entity Data Model (*.edmx from Entity Framework) with default code generation.
Common repository interface
public interface IGenericRepository<T> where T : ... |
I need to insert multiple checkbox text into a column in a mssql database, I could use a single checkbox list and make this thing easier, however, the requirements are to display separate table columns with several checkboxes , kinda like Check all the conditions that apply , but for several criterias, so I am guessin... |
I'm doing my first major jQuery development. It's a Widget for recurring events, and is as such a fairly complex beast. The full code is available at https://github.com/collective/jquery.recurrenceinput.js for those who want to check it out. I appreciate any kind of feedback about any part of the code, so anyone who wa... |
I'm doing my first major jQuery development. It's a Widget for recurring events, and is as such a fairly complex beast. The full code is available at https://github.com/collective/jquery.recurrenceinput.js for those who want to check it out. I appreciate any kind of feedback about any part of the code, so anyone who wa... |
I was given this assignment below and wrote the code below that as the solution. My instructor has been blasting me for writing inefficient code for my last several assignments, and rails at me for using strings as I do. She won't show me why its wrong but just states that it is wrong. I need to know why what I am writ... |
I have an assignment where I am required to verify if a car is a sports car or not by minimum max speed and minimum horse power. I have finished the program and it works great. I was just wanting to see if you can review my assignment and see if there is room for improvement.
using System;
using System.Collections.Gene... |
I have a string of numbers, like "31654918562314", and I want to convert it into an array of integers. The code I've written is:
string source = "31654918562314";
int[] numbers = new int[source.Length];
for (int i = 0; i < source.Length; i++)
{
numbers[i] = Convert.ToInt32(source.Substring(i, 1));
}
What improveme... |
I am writing a Unix shell in C, which uses a rather large switch in the main loop.
It is used to handle built-in commands like 'cd' or'help'. The way it works is that it parses the user input and return a 'comand_t' struct, with 'name' being the first word of the input.
The in order to switch on a string, I translate i... |
Goal
Convert the following into an IEnumerable of integers accounting for the x-y ranges:
"1,2,3,0,7,8,9,10-15"
to
{ 1, 2, 3, 0, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
Current implementation
I've written this little function and got something working, but I'm wondering if this can become more efficient or rich in feat... |
The C# code below, using LINQ to Entities, aims to merge all Class entities which have the same SubjectId and the same Students.
var sb = new StringBuilder();
var counter = 0;
using (var ctx = new Ctx())
{
var allClasses = ctx.Classes.Where(o => o.SubjectId > 0).OrderBy(o => o.Id).ToList();
foreach (var c in allC... |
I've been teaching myself Python3 for about a week now and I decided to put my skills to the test by writing a simple Tic-Tac-Toe game. Here is what I came up with:
#!/usr/bin/env python3
import random
board = [0]*9
def resetBoard():
for index, i in enumerate(board):
board[index] = 0
def printBoard():
... |
How can I make the following PHP code better, more efficient, shorter, elegant, etc? While it already works, I am still learning PHP and want to improve upon my current code:
<?php
$query = 'psoriasis';
$eSearchQueryParameters = array(
'db' => 'pubmed',
'term' => $query,
'retmode' => 'xml',
'retstart... |
So I built a little baseball "scouting report" graphic that shows stats for players. As you page through the players, their images slide in and out of the graphic. I worked out a way to do this using a jQuery queue, and it works fairly well.
The one hitch is when the graphic is changing from a player on one side of the... |
I'm somewhat new to Scala and am not sure if I'm doing things in a very Scala-esque way.
In particular, I'm not sure if I'm using Option correctly, since by calling .isDefined, I'm basically just doing ye olde Java null check. Also, the getMethodAndAnnotationFromInfaces method could probably be done better.
Please poin... |
Wouldn't it be nice to just chain assertions after a method call or is it just me? I was thinking that it'd improve readability.
Instead of:
var myObject = _objectService.GetRandomObject();
Trace.Assert(myObject!=null);
it'll just be this:
_objectService.GetRandomObject().NeverNull();
with the extension method define... |
I'm new to Clojure. How can I make this more idiomatic Clojure code? Among other things, there are three (do) blocks and I don't think using (def) as many times as I do is a recommended idea.
(defn add-phone
"Add a phone number to a given service. There are a few steps we have to take:
- Validate the service name... |
I am currently exploring the play framework. I'm about to replace the proposed templating system, using the powerful XML processing of the Scala library. Here is what I have come with:
import scala.xml._
import play.templates._
import play.mvc.results.ScalaAction
object Gui {
def asset (file:String) = "/public/"+ f... |
I was looking for a simple Event Aggregator to use in my app, but I found people get very complicated very quickly, so I thought this was easy enough to write myself. It seems to work, but I was wondering what you think and if you would change or add anything. (I know some of them raise events back on the same thread t... |
I've been wondering about simple collision in C++ for a while now, and I've tried to make up my own code.
The code posted below works when walls are placed in a perfect rectangle around the player. However, once you randomly place them in the array, as in the code, weird inconsistencies seem to occur. Sometimes the pla... |
I have written a (dynamic) TemplateArray class, for purposes to be included as a baseline for a library I am working on, and I would like feedback on any of the following:
How the code can be improved (even if it's just your subjective opinion)?
How the code can be made more efficient?
How the functions of the class c... |
PHP doesn't have a built-in functions for AES (specifically, AES-128) encoding/decoding, so I've had to implement my own, and this is what I have come up to (of course, taken from different many sources, mostly not coded by me).
My question is, are these correct? Not the code itself, but what they do. The correctness o... |
I am importing XML data to a MySql database using LINQ to Entities. The data represents which students are in which classes, and looks like...
<studentClassesData>
<studentClassEntry>
<upn>W432980573452</upn>
<className>8bcDn4</className>
</studentClassEntry>
<studentClassEntry>
<upn>W234525211334</up... |
I've prepared a small C interface so the rest of my program can access relevant system functions. I am not a C programmer, though - just C++ and D, mainly. I want to make sure that everything here is "C-ish" before committing the rest of my code to this interface.
This is just a plain old C file, compiled with a C co... |
I wrote a quick and dirty program to perform binary search with an ordered array (list) of C style strings. For example:
{"1", "12", "23", "124"} etc (though my input set is actually much different)
NOTE:
Apologies for the confusing names - string is not the string, string->ID is. (Like I said, I cobbled it together ... |
I have piece of code in C which removes any duplicate characters in a string. But I am doing it in two loops and would like it to optimize it to one loop.
void removeDuplicates(char* ptr)
{
int end = 1;
int length = strlen(ptr);
int current;
int i;
current = 1;
for(end=1; end<length; end+... |
It's long, repetitive, and hard to follow.
private void Map(object x, JToken json)
{
var objType = x.GetType();
var props = objType.GetProperties().Where(p => p.CanWrite).ToList();
foreach (var prop in props)
{
var type = prop.PropertyType;
var name = pr... |
I need to take a month (defined as a start and end date) and return a set of date ranges for each week in that month. A week is defined as Sunday through Saturday. A good way to visualize it is if you double click on your Windows date in the start bar:
The month of October 2011 has 6 weeks:
10/1-10/1
10/2-10/8
1... |
I have a flow where if a certain condition is true then I should take another approach. That condition can be triggered by different scenarios. But each condition test must be done only if the last one failed. Once a condition is true there is no further logical tests to do. My question is how to do that in an elegant ... |
I am working on an application that reads lots of data from the network and puts it in a grid. I noticed that I could save some memory by reusing existing strings instead of always using the new strings that came off the wire. So here is the class that I wrote to accomplish that. It is simple and it works. But I wa... |
Activating jQuery tabs from URL #id is www.somedomain.com/index.php#tab3
Given this my best shot, and it does work but I feel it could be far far better.
Please tell me if this is totally shockingly bad JS.
$(document).ready(function() {
//When page loads...
$(".tab_content").hide(); //Hide all content
//On Click E... |
There is as of .NET 2.0 a generic EventHandler delegate type, which can be used to define an event in terms of the EventArgs type you wish to use, without having to create a redundant delegate type to use in the event declaration.
Well, what about the EventArgs? I often find myself having to create one-offs derived fro... |
Empty Textboxes, class="loc" display "(City, State \ Country)" using italics and silver. Of course, Textboxes that do have data are displayed according to page defaults.
I noticed chaining and caching could be used. There are inheritances issues, so I am not bothering with using .addClass instead of targeting with .... |
Goal: typesafe PropertyChanged events, minimum effort implementation for PropertyChanged events, runtime reflection of properties.
Am I reinventing the wheel or have I created something worthwile? Would you use it in your next project?
public interface StaticProperty {
public boolean canGet(); /**... |
I recently posted a question looking for feedback on a script I wrote (see: Scraping PubMed query results)
Since then I have re-written it into a class, which I have posted below. How does it look? How can I improve upon it?
class PubMedQuery {
private $query;
private $searchParameters;
private $searchURL;
private $... |
Is this useful or is there an obvious other way?
The context is solving the problem of bubbling events in an asp.net site built with user controls and nested user controls. I found myself writing a ton of events.
So instead of events, i'm using a technique to allow any client to watch an arbitrary session value.
A sha... |
Using cakePHP, I would love to have your point of view about this large source code, i am not sure if its enought secure. sha1() will be removed with another script.
I found this large script can be optimized but how ?
i have many times
$this->Session->setFlash("You hav to complete each fiedls", "error");
and
$this-... |
Algorithm that I had to write is a perfect case for while, or do..while loop, however I found out that if I will implement it with a for loop I will save few lines of code and also scope of variables will be more appropriate. Take a look at the following code:
for ( var i = 1, offset = -1; currentPosition.top =... |
In order to detect run-time integer casting problems, I've created this function*:
template<typename TTo, typename TFrom>
static inline TTo int_cast(TFrom value)
{
TTo result = static_cast<TTo>(value);
if (static_cast<TFrom>(result) != value || (result >= TTo()) != (value >= TFrom()))
{
throw std::o... |
I have a situation where I have six possible situations which can relate to four different results. Instead of using an extended if/else statement, I was wondering if it would be more pythonic to use a dictionary to call the functions that I would call inside the if/else as a replacement for a "switch" statement, like ... |
I am running a math-oriented computation that spends a significant amount of its time doing memcpy, always copying 80 bytes from one location to the next, an array of 20 32-bit ints. The total computation takes around 4-5 days using both cores of my i7, so even a 1% speedup results in about an hour saved.
By using the ... |
I find the TagBuilder written in C# little poor without the ability to "host" inside it sub tags (as objects not as strings).
So I wrote a simple class that inherits TagBuilder and allow to save sub tags.
I can navigate inside it and add things to it while I move across the application.
And when I call the Top Tag Obje... |
I have this timer working already(jsbin):
HTML:
<input id="m" type="number" value="0" min="0" max="59"/>
<input id="s" type="number" value="2" min="0" max="59"/>
<input id="start" type="button" value="Start!" />
<output>00:00</output>
JavaScript:
var o = document.querySelector('output'),
m = document.querySele... |
Convert a decimal number to binary using only loops, strings, if/else statements.
This is my first C++ project and it took me a while to do it. Let me know what you think.
#include <iostream>
#include <string>
using namespace std;
string ConvertInt(int value);
string ConvertDec(double value);
void printBinary1(stri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.