instruction stringlengths 71 71.9k |
|---|
I've written a simple class that somewhat simulates multiple inheritance using mixins. It allows you to extend the functionality of multiple classes and manage any conflicts between them, should they arise.
Mixer class
abstract class Vm_Mixer {
protected $methods = array();
protected $mixins = array();
pro... |
I am writing this Monte Carlo simulation and I am facing this issue when running the code at 10,000,000 iterations. here is the code:
import random as rnd
from time import time
#get user input on number of iterations
numOfIterations = raw_input('Enter the number of iterations: ')
numOfIterations = int(numOfIterations)... |
I need to create a protocol for sending data of various types over a socket connection. so I need to serialise the data to a byte stream. I only need signed and unsigned 32 bit integers, 64 bit integers, string and binary. It is only a start but if anyone can code review this I would really appreciate it.
/* custom ... |
This program implements a sorted grep, that is, a specialized version of grep for sorted files. It uses binary search for the lines of a file that begin with a certain string.
You can copy and paste the code in a file and run it as:
$> runhaskell sgrep.hs "string to find" sorted_file
I'm looking for suggestions about ... |
Before you say anything: Due to project constraints, we cannot use Boost and we cannot use C++11 (yet; perhaps this will change some day).
The fact that I was unable to use smart pointers was nagging on me for some time, so I decided to cough up my own implementation, and it was surprisingly simple. So, I'd like you to... |
I took a challenge on CodeEval. Although the code seems to work for the examples taken from the site, I feel it is not really pretty and must be more complicated than it should be.
Description:
The sentence 'A quick brown fox jumps over the lazy dog' contains
every single letter in the alphabet. Such sentences are c... |
How could I improve this code?
I used a position interface to avoid code duplication, can it be done better?
Can I reduce the amount of code somehow?
interface PositionInterface
{
double getPosition(PageAreaInterface pArea);
}
private double getMinPosition(Collection<PageAreaInterface> pAreas, PositionInterface p... |
I have already made a function of multiplication of long numbers, addition of long numbers, subtraction of long numbers and division of long numbers. But division takes a very long time, how it could be improved? Here is my code:
/// removes unnecessary zeros
vector<int> zero(vector<int> a)
{
... |
I've recently discovered the power of sed; regular expressions seem like they'll take a lifetime to master. This tiny script uses both to add a zero before the single digit in file names.
Can this be done more easily without sed? Is the regex sound?
#!/bin/bash
# > addzero.sh <
# Adds a zero before the single digit i... |
I have the following code for binary search
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace BinarySearch
{
public class IntComparer : Comparer<int>
{
public override int Compare(int x, int y)
{
... |
I am sure you can find many weak spots, please let me know about them.
My main question is if this is a sensible approach to separate the construction phase from the constructed phase.
Basically I have a set of objects that needs to be transformed into similar (but different) objects. Once transformed I want to be abl... |
I'm trying to figure out what is best and fastest implementation of a browser-like find and highlight function inside a website using JavaScript.
This function is for one HTML element without any children. Of course it can be expanded to elements with children with some simple loops. That is not part of question.
I wro... |
I've just finished my solution to the Dining Philosopher's Problem, but I am not confident with my code because I am still newbie to the concurrency world. I would appreciate it if you could leave me some feedback.
Here is my main class:
public class DiningPhilosophersTable {
//An array holding all the chopsticks... |
I'm new to Haskell and functional programming and I did for training purpose a basic program where you can:
create a directory (consisting of a name and an array of sub-directories)
create an entry (consisting for a title and a content)
remove and entry or a directory
view an entry
do a directory listing
The availabl... |
I've put together this extremely simple text diff function a while ago:
function diff($old, $new) {
$old = trim($old);
$new = trim($new);
if($old == $new) {
return $new;
}
$old = explode(" ", $old);
$new = explode(" ", $new);
$result = "";
$length = max(... |
A small greedy algorithm to position boxes in a grid.
Version A
int lCurrentIndex = 0;
BoxInchesInterface lPreviousBbox = lSortedBboxes.iterator().next();
double lEndPositionForCurrentIndex = pDimension.getEnd(lPreviousBbox);
for (BoxInchesInterface lBbox : lSortedBboxes)
{
boolean lIsFirstIteration = lBbox == lP... |
I'm struggling for a while now with the readability of my code, I after I tried to get as much insight as possible (for my standards). On my level, I think I understand and use it all right for my level.
But I'm still having big chunks of mixed html/css in the presentation. Often I have a mediocre complex multi-dimens... |
Please review my JavaScript code below. I want to colspan and rowspan automatically if adjacent cells have sames value. For example like this.
<table id="BeforeTable" border="1">
<tr><td>A</td><td>B</td><td>B</td><td>C</td><td>D</td></tr>
<tr><td>E</td><td>F</td><td>G</td><td>C</td><td>D</td></tr>
</table>
<br>... |
For trivial reasons, I decided to have a go at differentiating dates. Low and behold having no idea how much of a non-trivial task it was to become.
It was originally a small sidetrack from a project I'm doing.
And, whilst performance isn't a huge concern here, the code I've posted below performs highly optimally in co... |
I've written a table of contents parser for a FOSS wiki project I maintain in my spare time. The class takes a HTML string, injects anchor takes before each H1,H2 etc. and then generates the contents for the headers.
My main concern is boundary checks within the code. I haven't got any unit tests for it as it's a bit h... |
I am looking for feedback on coding style. I know this function already exists, and I would never use my version over a well tested one. I am just practicing.
double Clib_atof(char s[])
{
double val, power, rtn;
int i, sign;
for (i = 0; isspace(s[i]); i++);
sign = (s[i] == '-') ? -1 : 1;
if (s[i] ==... |
I'm using the below code to try and make it easy to do sensible calculations for different variables, i.e. pressure + height is nonsensical, and pressure in atm += pressure in bar should add taking units into account. I've tried playing round with dynamic and static cast as well as CRTP on the advice of other fine memb... |
I've not posted binding specific messages to the gridview part. This shows updating that particular message or message from a list of messages databound with an XML file. My main concern is omitting redundant code in the else part. Any suggestions?
protected void grdMessage_RowUpdating(object sender, GridViewUpdateEven... |
I tried creating a quick tooltip plugin using the jquery and jquery ui position. Is the way I have used the enclosure are right and is the use of position right since in ff it seem to have some memory problem..it remembers the previous position when I refresh the page after the first time. below is the code
This need ... |
I am new to OOP and have written a products class. All is working fine but I am unsure which of the below version of a method within this class is best?
The first gets the variables from within the object and the second passes the variables into the class. Both work. I originally had it as the first version but things ... |
I made a small command line tool to help my Italian studies. Any thoughts on how it could be improved? I can't think of much but would like to be proved wrong.
import random
class RegularVerb(object):
def __init__(self, name):
self._name = name
def name(self):
return self._name
def _make(... |
I'm very new to python and scripting in general. I've come up with the following function to find the first and last IP when an IP range string is inputted. I want to only use base Python (and not download any libraries essentially).
Example:
genRange("1.2.3.*"):
Start IP = 1.2.3.0
End IP = 1.2.3.255
genRange("1.*"):
... |
I am refactoring code which contains many lines of NSString* image = [@"ipad_" stringByAppendingString:imageOrigName]; and wondered which is more optimized:
stringByAppendingString:
or
stringWithFormat:
In the first, you take one NSString object and concatenate another onto its tail. In the second, you can use a for... |
The basic idea is to replace all special expressions, e.g., [%InvoiceNo%], [%DueDate%], in a string with the properties of an object, Invoice invoice.
string str = "Your invoice [%InvoiceNo%] will be due on [%DueDate%]";
Invoice invoice = new Invoice { InvoiceNo = "123456", DueDate = DateTime.Parse("2011.12.29") };
str... |
I recently started learning binary tree. Following is the code for a typical node for a tree (no code review required for that):
typedef unsigned int uint;
template<typename T>
class BinaryNode
{
T t_Data;
BinaryNode *pt_Left, *pt_Right;
public:
BinaryNode (const T &data) : t_Data(data), pt_Left(0), pt_Right(0)... |
Here's my attempt to replace first occurrence of pattern in file with spaces. Effectively deleting it, and hopefully will allow me to "delete" it in a large file, without rewriting it.
#define MAX_LINE_LENGTH
int removeFirstOccurenceInFile(const char* fileName, const char* pattern) {
FILE* f = fopen(fileName,"r+");
... |
I would like tips on my CODE, map structure (How I should seperate the code, more files, etc). What I can do about the func.php file as a file with just a bunch of functions, doesn't seem to be the best approach for it.
And generally just a code review how I can improve on it.
createaccount.php
<?php
require_once 'init... |
I have inherited an application which uses LINQ-to-Entities for ORM and don't have a great deal of exposure to this.
There are many examples like this throughout the application. Could you tell me where to start in refactoring this code?
I appreciate that it's a large chunk of code, however the query isn't particularl... |
To illustrate how to do leader election with Apache Zookeeper I've created an straightforward application and I would like to have to threading part of the application reviewed.
I've created a simple class (Speaker) which outputs an unique identifier to a file on a regular interval. I've implemented the Runnable interf... |
What do you think about this core EF method ?
Also, Notice that it returns IQueryable:
Could that be a performance danger when extended improperly ? How ?
Please accept the fact that Includes and OrderBy parameters are string type.
public IQueryable<TEntity> GetEntitySetMultipleTables(Expression<Func<TEntity, bool>> W... |
class User {
protected $DBH;
protected $STH;
public function __construct($DBH) {
$this->DBH = $DBH;
}
public function logged_in() {
if (isset($_SESSION['userid']) && isset($_SESSION['hash'])) {
$hash = sha1($_SESSION['userid'] . $_SERVER['HTTP_USER_AGENT']);
... |
I started a hobby project which would be the first thing I do in C that is intended to be seen by someone else. I've been practicing for a while but I'm actually a beginner; I never wrote real software in C/C++ yet.
I wanted to know what is OK from my code, what is wrong and why, if it's clear/readable, and everything... |
I'm currently in the process of creating a online work schedule for internal use. For this, the client needs to show the days of a single week.
I pass a week number and a year.
From that I get the first day of that week, by using strtotime() passing an argument in the format [year]-W[weekno]-[dayofweek]. Example: strto... |
I usually spent more time on refactoring than in developing itself. But this little piece of code is really hard to refactor. I'd like to keep it as short as possible, but it's quite undarstandable:
foreach($all_headers as $uid => $h) // Intera gli headers
{
// Is the header valid?
$isInbox = $h->to == $mail... |
This method is part of my login system. Could I improve it further?
protected function _hashPassword($password = NULL, $rounds = 1000, $i = 1)
{
if (! isset($password)) throw new Exception('No password set!');
$salt = 'K^^%/m>(|{z= $1^>%>W[=4U5*p|,E';
$pepper = '08[)^,&%^^771^=>&,E[XP::4})h*I';
$din... |
I have created this class to simulate a thread-safe Singleton.
Have I missed anything?
#include <boost/thread/mutex.hpp>
class Singleton
{
public:
static Singleton& GetInstance()
{
boost::mutex::scoped_lock lock(m_mutex);
static Singleton instance;
return instance;
}
private:
static boost::mutex m... |
I have a singleton class which extends from an abstract java class. Two singleton classes extend from ItemImageThreadManager, the reason for this is to use shared scheduling functionality. A thread is created and passed into the runThread method of ItemImageThreadManager.
Is this good design?
Abstract Parent Class
publ... |
Suppose we have the following program:
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *user = getenv("USER");
char buffer[4096];
if (user) {
snprintf(buffer, sizeof buffer, "/bin/echo %s", user);
system(buffer);
}
return 0;
}
Is it... |
I'm an objective-c developer. But i'm getting familar with C. I wrote it for my own develpment in C. Please point on some errors!
The point is to store/read bytes in file named "key" in cachePath directory.
Cache.h
typedef const struct Cache *CacheRef;
/* Returns cache reference for corresponding cache path */
/* NOTE... |
I am working on a program which use OLEDB to connect to a MS Access 2007 file. My program has a possibility to add and delete records from file by using SQL statements which select deleted item by ID.
Now, I was warned that my code might cause SQL injection which would delete all entries from the file. How can I preven... |
I have written the below code to search for a string in a web page. This is working fine but I need suggestions on improving this code to start using this. This is written to work under IE.
$(document).ready(function()
{
var NotFounds = [];
function countString(s) {
var re = new RegExp(s, 'gi');
var text = documen... |
In particular, I'm not happy with case 5 in the Control class. Basically, in case 5, I would like the user to attach a student from the students array onto a module from the modules array without duplication. Any suggestions/example would be very useful.
Driver Class:
public class MyApplication {
public static void ... |
I've got a simple program written in Golang that takes a map as input and tries to solve the travelling salesman problem by using a genetic algorithm. My Crossover method is a real performance killer due to intense use of make() (allocate memory / will provoke the GC).
What I'd like to do - and yet failed to do is outs... |
Defines a simple module for timeoutable computations, with the ability to return
arbitrary intermediary results on timeout or the final value otherwise. It also
allows default return values.
The implementation uses Unix.sigalrm to define timeout intervals with second resolution.
There is a small overhead on starting ... |
To fullfil a promise, I cooked the following script :
[Code]
var
BDS: string; // No trailing backslash path
BDSCOMMONDIR: string; // No trailing backslash path
BDSPROJECTSDIR: string; // No trailing backslash path
BDSUSERDIR: string; // No trailing backslash path
//
BPLPath: string; // No trailing backslash... |
I have an simple algorithm which marks table rows with identical entries blue. The problem is that this solution takes a lot of time.
Has anyone an idea how to improve the speed of this?
$(document).ready(function(){
var tableRows = $("#sortable tbody tr");
tableRows.each(function(n){
var id = $(this).attr... |
I was thinking about doing problem 23 of Project Euler. It includes the difficulty where you have to factorize primes. I had already done that in problems I solved earlier, but it was only necessary to have a prime list until a relative small number.
So I had already implemented the algorithm when I took a look at this... |
I need a Read-Write lock that is fast and generally portable on Windows machines (including XP, otherwise I'd just use the SRWLock that was introduced with Vista). I've written this custom implementation, partly as an exercise, and partly to avoid including Boost just for the one class.
I'm an amateur, though, and con... |
function prepareEventHandlers() {
var sectionButton1 = document.getElementById("sectionButton1");
var sectionButton2 = document.getElementById("sectionButton2");
var sectionButton3 = document.getElementById("sectionButton3");
var sectionButton4 = document.getElementById("sectionButton4");
var sectio... |
I am still pretty new to Haskell and am working on a graph generator for undirected unlabeled graphs containing loops and I have a bottleneck in the following functions. So far, I have not given any thought to performance and just looked for correctness.
I know this kind of question is not really popular, but I'd be i... |
Is there a better way to do what I'm doing? If not, I'd like just a general review of how I did it and the usability of it (how it works and functions, not artistically how it looks).
Here is the working JSFiddle.
JavaScript
$(document).ready(function () {
// initlize panels
$('.panel').each(function (i) {
... |
I'm learning Python 3 at the moment, so to test the skills I've learned, I am trying the puzzles at Python Challenge.
I've created some code to solve the 2nd puzzle here. it works, but I think that the way I've done it is very convoluted. Any suggestions on how to solve the puzzle in a simpler way?
(The code basicall... |
I have been doing PHP for about three years now, with little direction other than the books I read and trial and error.
I am currently coding what I hope to be a pretty nice application and I have decided to throw myself into the fire and get torn apart (haha you think this is a nice application!!)
Over the last year ... |
In the following piece of code I am adding entries to an MS Access file using OleDB. The purpose of this post is to point out my bad programming practices and if I have created any security flaws here. I was reading somewhat about SQL injection attacks, and I wonder if this code might have any potential bugs.
First, it... |
I'm working on some image processing code that can generate pixel values outside of the normal range of 0 to 255, and I'd like to clamp them back into the valid range. I know that there are saturating SIMD instructions that make this a moot point, but I'm trying to stay within standard C++ code for the moment.
The fast... |
With regards to Safe Publication, consider this piece of code:
public class Test {
public static void main(String args[]) {
ThreadB t = new ThreadB();
t.start();
t.Grab(new Bag("HI"));
}
}
class Bag {
private String item; // <-- no final here
public String Item() {
retu... |
Suppose a series of objects (presented here as tuples):
"a" | 1
"a" | 2
"b" | 3
"b" | 4
"a" | 5
There is no built in function (that I know of) to group by the first columns's sequence, that is, all the "a"'s in a row, then the "b"'s, then the one "a" alone. So that the groups become: {1,2},{3,4},{5} and not {1,2,5},{... |
I am using the following code to rename the uploaded files for any future name clashes. Please tell if my approach is right or I should follow some other approach or approach which is better.
[HttpPost]
public ActionResult Upload(HttpPostedFileBase fileData)
{
if (fileData != null && fileData.ContentLe... |
I have following relationship schema:
class Participation
belongs_to :toon
belongs_to :person
validates :role, :presence => true
end
class Toon
has_many :participations
has_many :people, :through => :participations
end
class Person
has_many :participations
has_many :toons, :through => :participations
e... |
This is a CRC function generated by pyCRC and changed by me:
static inline crc_t crc_update(crc_t crc,
char const * data,
long long data_len)
{
while (data_len--)
{
crc = (crc_table[(crc ^ *data) & 0xff] ^ (crc >> 8));
... |
I'm trying to build a superfish dropdown menu from a sql query. Working example is can be seen from here check the "emlak bul" category: http://www.bedavaemlaksitesi.com/mersinemlakrehberi210/sayfalar/HABERLER
function menu_emlak_kategori() {
$this->db->distinct();
$this->db->select('
kgsim_il... |
I've just implement direction enum
object Direction extends Enumeration {
type Direction = Value
val Up, Right, Down, Left = Value
val pairs = HashSet() ++ List((HashSet() ++ List(Up, Down)), (HashSet() ++ List(Right, Left)))
def isOpposite(one: Direction, other: Direction): Boolean = {
pairs.contains(Has... |
Now the program works, but is it correct? Sometimes it works in C anyway. Could I improve it somehow (not numerically, just C-wise)? I need to allocate the array as I do right? Since I am returning it and not just using it inside the function.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Approximates a ... |
I first saw this gigantic if and tried to refactor it. Could only end with a endless switch statement.
Old code -
# It is a Cause
if @causality == "C"
@relationship.cause_id = @issueid
@relationship.issue_id = @causality_id
@notice = 'New cause linked Successfully'
end
# It is an Inhi... |
Could I improve this somehow (not numerically, just C-wise)? Do I need to allocate the array since I am returning it and not just using it inside the function?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Approximates a solution to a differential equation on the form:
y'(t) + ay(t) = x(t)
y(0) =... |
I'm trying to build friendly URLs like /post/1/my-first-post. I started out with building my links like this:
@Html.ActionLink(Model.BlogPost.Title, "Index", "Post", new
{
id = Model.BlogPost.Id,
title = Model.FriendlyUrl
},
new { })
which were processed by this route:
routes.MapRoute(
"Post", // Route name... |
I think the below code is difficult to understand. I also feel it abuses Java's ternary operator.
String name = ((this.getAllNamesAsDelimitedString().contains(incomingName) ?
incomingName:
(CollectionsUtils.isEmptyCollection(this.getEntityOperationMap()) ?
null :
... |
Constructive criticism is required for the 2 methods below. I'm trying to develop better OO skills.
// Set up scanner to allow for searching of modules
public static String searchModule() {
Scanner scan;
System.out.print("Search module code: ");
scan = new Scanner(System.in);
String searchModule = sc... |
I wish to ask if the code written below has any holes (probably it will be useful for someone else). This code checks, by IP and by userid, if more than 5 attempts within the last 5 minutes were made to login. Every attempt to log in is stored in the history table (MySQL).
The history table is needed only for the purpo... |
I'm working on a Python script and I was searching for a method to redirect stdout and stderr of a subprocess to the logging module. The subprocess is created using the subprocess.call() method.
The difficulty I faced is that with subprocess I can redirect stdout and stderr only using a file descriptor. I did not find... |
I had an idea of checking if Entry ID already exists in database. If it doesn't there is no point of removing non existing entry.
So when user types then each time new character is added I am opening or closing connection to my database file. This is my concern.
But what if there might be hundredths of entries? Could t... |
The general idea is is a progress bar that updates the totals and percentage continually.
This just gets a bit choppy when I trigger a few of these independently on the same page. I'm doing a bit of math at every step, and wonder if there is a better way to accomplish this.
$bar.animate({width:percent+"%"}, {
durat... |
There's a Follow-up: Game Of Life rewritten into two classes, PetriDish and Cell
I wrote an implementation of the Game Of Life using the easiest approach, a bunch of loops and a boolean array. Yet I feel like I missed something very elemental.
The basic implementation is:
Check the old generation with loops
Check ea... |
I'm after a collection of opinions regarding cohesion and coupling with my application to improve OO programming.
Control Class - Populates test data and calls main menu
import java.util.HashSet;
import java.util.Set;
public class Control {
public void run() {
// Populate Test Data
Student jane = new Student... |
I am implementing a gap buffer and am trying to write a test for the insert method, the test currently looks something like this:
gapBuffer.insert('a')
assertEquals(gapBuffer.getText(), "a")
gapBuffer.insert('c')
assertEquals(gapBuffer.getText(), "ac")
gapBuffer.insert('d')
assertEquals(gapBuffer.getText(), "acd")
gapB... |
I have been working lately on an educational framework project to learn more about web development and problems that arise in more complex applications. Part of the framework's principles is to be as Object Oriented as possible. For example, most data returned from queries to a data source will be returned as a parti... |
package calc;
import com.sun.tools.corba.se.idl.constExpr.Equal; //imports .equals(variable)
import java.util.Scanner; //imports scanners
public class Calc {
public static void main(String[] args) {
boolean go = true; //sets up loop
while(go) //creates loop to top
{
... |
In my project, I am doing asynchronous processes in almost every classes. To explain my problem, I have created a sample:
public interface TestListener {
void onResponse(Response result);
void onError(Exception e);
}
public class AsyncTask {
TestListener testListener;
public AsyncTask(TestListener testListene... |
So I'm doing things the BDD way, writing features first, then moving on to writing specs to add more detail to the mix as I move down the layers.
One thing that bothered me, but isn't a big problem, is that when I got to the controller part of the stack, I have calls to the User and Todo model in my controller spec.
Is... |
This checks each row for a category. It stores ONE version of the category, ignore duplications. It then counts how many times a category appears.
There are a lot of for loops and a lot of table-checking. This takes time as the table is quite large. If it's possible, I would like to incorporate some of the loops to red... |
I've modified John Resig simple javascript inheritance framework, by adding set function with setter functionality. It seems that it works. Is it written correctly? Can you see some undesired behavior?
Framework:
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
t... |
I'm starting working with R, and found some tutorials and exercises online.
I want to divide one variable in two, bigger and equal 79 and smaller 79.
Perhaps because I'm used to python, my first approach was to do something like this:
z <- numeric(length(faithful$waiting))
n = 0
for (i in faithful$waiting) {
n = 1 + n
... |
I've recently helped fellow SOFer to answer his question here: Routing in my PHP MVC framework
Then I thought
Hey, why not improve this code and put in my snippets library.
This is what I came up with:
/**
* @author Gajus Kuizinas <g.kuizinas@anuary.com>
* @copyright Anuary Ltd, http://anuary.com
* @version 1.0.3... |
I have some static helper class:
public static class Helper
{
public static bool IsNull<T>(this T value) where T : class
{
return (value == null);
}
public static bool NotNull<T>(this T value) where T : class
{
return (!value.IsNull<T>());
}
public static bool IsNullOrEmpty... |
No one in my team knows how to write BDD tests, so I started writing some and it's quite working well. I think the time has come to improve the code quality.
This contains a lot of duplicated code and unused features:
<?php
require_once ('core/v3/engine.php');
require_once 'PHPUnit/Extensions/Story/TestCase.php';
clas... |
Okay so as I learn more about PHP and really strive to improve my code I have a few questions about a current setup of mine and how to approach it in the best way.
I think I have all the tools necessary to get this done the right way, but I am having trouble putting them together. I am also trying to separate my code b... |
I am writing a file writer/reader in JavaScript; I want it to work on local files.
It tries to use Firefox's XpConnect, falls back on IE activeX, falls back on Java LiveConnect, falls back on a Java class (not included here), falls back on HTML5 local filestorage. I also want to throw in there a GET driver, to communic... |
I've been trying to write a jQuery script where when someone clicks on the input the space clears and then if they don't type anything in, it reappears.
This is what I came up with. Is there a better way to do this? If so why is it better?
$(document).ready(function() {
// set all input.text default value ... |
I need to use some flags in my code. To make it a bit clearer, I am looking to set the flags in some structure, and I need to match the following needs:
The flag representation in the structureis hidden.
The following methods are provided (or the same idea at least): setFlag(structWithFlags *, ACTION_FLAGS ),
isFlagSe... |
I was asked how this code has a security risk. Does anyone have any ideas what it is? I am new on the security topic and don't know what to look for.
String DBdriver = "com.ora.jdbc.Driver";
String DataURL = "jdbc:db://localhost:5112/users";
String loginName = "stackoverflow";
String passwd = "codeReview";
Class.forNa... |
The problem is to find the longest words in a dictionary of legal words that can be constructed from a given list of letters.
For example:
$ ./scrabble dictionary.txt i g h l p r a
argil glair grail graph hilar laigh phial pilar ralph
More details here.
I've already solved this problem in Python (see this).
To brush... |
(this is a crosspost from StackOverflow, it was suggested I asked here)
Goal
I've got a DOM with about 70 elements on it (divs with some content) . I need to move and toggle the display of those divs quite a lot and also quite fast. The speed is one of the most important things. The trigger for moving and toggling thes... |
I have this code I used to to pull data from our IBM i into .NET into an object so it is easy to work with (avoiding DataTables).
How can I make it better?
How can I convert all/most of this into a generic reusable method?
Here is an example of a method I have written:
public Customer GetUtilityBillCustomer(int id)
{... |
I'm trying to work with some encryption/decryption of data. It was some hard work for me to get it working with some buffers and what not.
This is the code I came up with:
public static string Encrypt(string dataToEncrypt, byte[] publicKeyInfo)
{
//// Our bytearray to hold all of our data after the encryption
... |
Follow-up to: Game Of Life implemented with for-loops and a boolean-array
As proposed by palacsint I went on and rewrote my implementation of the Game Of Life and extracted everything into two classes:
PetriDish
The parent which holds the array of cells
Sets the array up and initializes each cell
Starts the evoluti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.