instruction stringlengths 71 95.1k |
|---|
I wrote a Python MP3 player for Linux using PyGame, with a curses GUI and a mouse-only interface.
It's purely for personal use.
It hasn't been polished yet, but for now I'd like to know what I've done inefficiently so I can fill in some ignorance-holes. I know a few things could be handled more directly.
import curse... |
Blackjack (twenty-one) is a casino game played with cards. The goal of
the game to draw cards that total as close to 21 points as possible
without going over. All face cards count as 10 points, aces count as 1
or 11, and all other cards count their numeric value.
The game is played against a dealer. The player t... |
I started working with R recently and need to do a simulation for 100 000 people that
divides them in exposition factor for a disease, gender and presence or absence of
disease.
My background info is that the probability of being exposed to this risk factor is 0.15 in this population. The probability of being a woman,... |
I have an iOS app that support all orientations. I sometime notices performance issues when I rotate the device, and sometimes it crashes, badly. And it's not as smooth as other apps. This is my first app, so I'm not a pro. I have quite a lot of custom UI elements so most of my views is done programatically. The issue ... |
Consider the following piece of code:
var result = List[Measurement]()
val dbResult = conn.createStatement.executeQuery(unsentMeasurements)
while(dbResult.next) {
result ::= Measurement(dbResult.getString("stuff"), dbResult.getString("morestuff"))
}
result.reverse
Versus this:
val dbResult = conn.createStatement.... |
I wanted to do the following:
Count the frequencies of words in a text (over 5 letters)
Invert the map of words to frequencies, but group together words that have the same frequency in the inversion.
Sort the inverted map by keys descending order and take the top 25.
Here is the code I came up with. Did I re-invent ... |
I personally want a small selector function that covers the three common cases
getElementById
getElementsByClassName
getElementsByTagName
It should support contexts and should not support querySelectorAll since <opinionated> QSA is slow as hell and should be avoided </opinionated>
I have an implementation of such a f... |
I was just playing around with N queen problems means accommodating N queens on N*N chees board such that no one can kill each other. I tried a simple algorithm which uses backtracking.The program is working fine till 29 queens but after 29 it is just going on and on..I am not able to decide is it due to some logic er... |
I'm trying to get a better grasp on generators in Python because I don't use them enough (I think generators are cool). To do so I wrote a generator for prime numbers:
def primes():
x = 2
while True:
for y in xrange(2, x/2 + 1):
if x % y == 0:
break
else:
... |
I have run this program for five hours and it has not yet completed. I wonder if we can make changes to reduce the computation time.
I use several for loop and this greatly increases the computation time. my goal is to compare the contents of the rows of a matrix (4435 × 2000) with 6 row vectors (1 × 2000). The compari... |
I am currently working on a Sudoku solver that should be able to solve a 25 x 25 grid. However, I am experiencing problems optimizing it to run quick enough to actually get a result with any grid bigger than 9 x 9. I was wondering if anyone could take a look at my code and give me some ideas on how to optimize it.
publ... |
This was actually asked in an interview. I have made it in the best possible way I could and would like to optimize it if there is any chance of doing it.
The input is:
a(b(cd)e(fg))
The output should be:
a
/ \
b e
... |
I wrote this to pull one column of data from a csv file, divide each of the results in 2, and then format it as JSON so I can do stuff with it in a web app. It works, but it feels wonky and weird. Is there a better way to do this?
$fname = "subjects.csv";
$half = array();
$otherkeys = array();
$records = array();
... |
I got my 1 dimensional program to work just fine so I figured I just need a few tweaks to get the 2D to work as well. It's not fully completed but it would helpful to know if I am on the right track or completely off base with where I am at.
import java.util.Scanner;
import java.util.Random;
public class MS2D
{
p... |
The code reads from the screen, compares a pixel in a previously provided sample image and, if the pixels match, it records timeback seconds of video leading up to it. The output is put into a folder 'tm'. Since I do not assume the pixel to be occurring all the time, the writing process is buffered with a thread, so as... |
I need to add a list of names and (optional) links to my ASP.net page.
I learnt (hopefully) to use a GridView to do this, mostly working from the example given by this blog entry: adding-dynamic-rows-in-gridview.
I've added a GridView to my frontend:
<asp:GridView
id="NameLinksGridView" runat="server"
A... |
I'm creating list of Tokens from input [Char] stream using Parsec v3. The definition of Token looks like this:
data Token = CharKeyword | OpeningBracket | Identifier String | Natural Int
As result of calling parse lexComb "" inputStream i have [Token]. Everything OK so far.
Now i want to parse this list of tokens usin... |
I'm trying to implement simple data streamer in Python with sockets. Consider one server and one or more clients. I just want to read data from server, process it and send it to the client. Here's how I do it now:
outputsocket = socket.socket()
outputsocket.bind((self.outputaddress, self.outputport))
... |
I have the following script and I think it's a bit inefficient. With a array from 1 to 3, this isn't a real problem, but this array can get way bigger. So how to boost it's performance/optimize this code?
<?php
$array = array(1, 2, 3);
foreach ($array as $tabid)
{
echo '<div id="tab'. $tabid. '" class="tab_co... |
Is there a way to reduce the computation time in this program that eliminates the columns of a matrix A if for a given column the element of line 4 is equal to the element in row 5:
k=1;
for i=1:4000
if A(4,i) ~= A(5,i)
B(:,k)=A(:,i);
k=k+1;
end
end
|
I have to clean up some Javascript and I am trying to figure out a more elegant way to write this code below. It's basically looping through 3 dictionaries with the same loop structure and appending some custom HTML onto a specific div. I wanted to see if there is a way to avoid this repetitive code:
if (dtInt in cale... |
The situation is that its not always possible to play with the web.config or have access to IIS, that being said I had to come up with a way to catch all 404s in a .NET application, for aspx page extensions its fairly easily and the web is full of ideas... but for non aspx extensions I did the following, looking for ad... |
I have 2 questions about functions inside object literals. I have included the workarounds I've been using, but they seem hackish. Is there a better way to do this?
ns = {
a: function (x, y) { return x+y; },
// Problem 1
// This does not work: Error: ns.b is not a function
b: this.a,
// Is this the corre... |
I need to limit method call to 80 times per second (for each connectionId).
My initial version:
private const int MAX_TRANSACTIONS_PER_PERIOD = 80;
private const int PERIOD_IN_MS = 1000;
private Queue<DateTime>[] times = new Queue<DateTime>[10]
{
new Queue<DateTime>(100),
new Queue<DateTime>(100),
new Queue... |
Here is the implementation I ended up with. Please post your feedback!
#include <cstdio>
#include <cstdlib>
#include <iostream>
inline void swap(int * const a, const int i, const int j) {
const int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
void printArray(int *a, int len) {
for(int i=0; i<len; i++)
... |
Is there any possibility of refactoring this code?
In class A:
public List<Item> GetItems() {
var result = new List<Item>();
foreach(var item in repo.GetItems1()) {
var x = repo.GetOtherItems1(item.Id, "param1", param2); // this part is different
if (x.Value > 5)
result.Add(x);
}
return result;... |
I have a database-intensive app, almost every activity requires access to the database, both reading and writing.
I had a lot of problems with separate threads and activities on the stack closing connections to the database when the current activity was using it, even if I opened and closed the database immediately bef... |
I was trying to solve this problem. I thought of any possible relation between the number of matches among subsequent substrings, but could not find one. So, the probably naive solution that I drafted was:
#include <iostream>
#include <cstring>
using namespace std;
int n;
char str[1000000];
int sim(int i, int len)
... |
I have a series of string manipulation, I realize this with the following code. I want it to be more elegant and readable such as str.sub_heading().sub_codeblock()..., how could I rewrite my code?
def sub_heading(str)
str.gsub!(/^(#+)\w+/) {|m| m.gsub("#", "=")}
str.gsub!(/^(=+)(.+)/, '\1 \2 \1')
end
def sub_code... |
and can I make it more efficient? It's to test the collision between a ray and a sphere.
float BoundingSphere::Intersects(Ray ray)
{
D3DXVECTOR3 direction = ray.Direction();
D3DXVECTOR3 vec = D3DXVECTOR3();
D3DXVECTOR3 cToO = ray.Origin() - centre;
float rSquared = radius * radius;
float vSquared = 0;
if(D3DXVec3Dot(&... |
I have the following script to reveal sections on a page if certain text in an is clicked. How do I collapse all other sections if any one of them is selected and make it scalable for 20 items?
The following solution looks like it needs refactoring, and also when clicking icn_1, for instance, all other sections might ... |
I am doing a refresher on algorithms.
I tried to solve the problem of determining if you have 2 trees (T1 and T2), one is a subtree of the other.
I came up with the following:
public boolean isSubtree(Node n1, Node n2){
if(n2 == null) //Empty Subtree is accepted
return true;
if(n1 == null)
... |
In a current project I needed to enable/disable autorotation of the UI to specific UIView's. I looked around and did not find a working solution that fitted my case and returning NO in
shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
method did not work as it seems to get overridden ... |
I am still getting the hang of Exception Handling in PHP; Here is the scenario where I am using the convention:
There are times where I have a SQL query that I need to turn into an object, so I wrote this utility class/method.
Class A {
public static function getThatOneInstance(){
$sql = "SELECT id FROM ta... |
For my homework assignment I have to create a class which converts an integer between 0 and 9999 into the written form. For example, 713 would be written as "seven hundred thirteen."
I wrote a few variations and I think I found the best approach. However, I was wondering if anyone had a moment to comment on my approach... |
function dashesToParentheses(str) {
var list = str.split('-');
return str.replace(/-/g, '(') + repeatString(')', list.length - 1);
}
function repeatString(str, times) {
if (times == 1)
return str;
return new Array(times + 1).join(str);
}
dashesToParentheses('a-b-c') // "a(b(c))"
dashesToParen... |
I'm trying to write a piece of code that will mimic ASCII keyboard output. It uses the keyboard library from pjrc, but the application I'm working on requires outputting string sequences rather than individual keys (the C++ interface exposes Keyboard.print, which does exactly what I want, except that I'm trying to stic... |
I really need some help removing some duplicated code. I've linked the methods causing me issues. http://pastebin.com/cZJihM4J
As you can see each method does similar things but retrieve different values. i.e one method to insert a string at a certain line. Another to get the the lines index and another to get the cont... |
I was wondering if someone could give some tips as to how improve long strings of if-else statements and redundant if statements. For example, how should I optimize this if statement so it would be more re-usable for maintenance purposes:
if (($game == 'DS' && $eventId == 185) || ($game == 'MT' && $eventId == 333) |... |
Looking for the best way to do this.
Currently in 4 different classes I have:
textArea = new JTextArea(10, 55) {
{
setOpaque(false);
}
@Override
protected void paintComponent(Graphics g) {
for (int i = 0; i < list.size(); i++) {
if(i == lineIndex)
g.setColo... |
I have a function that moves circles out of the way of an expanding circle. It moves them along a ray from the center of the expanding circle through the center of the circle to move. This allows all surrounding circles to move without overlapping.
Here's a diagram to better explain this:
I expand the size of the red ... |
As of now, I am using this code to open a file and read it into a list and parse that list into a string[]:
string CP4DataBase = "C:\\Program\\Line Balancer\\FUJI DB\\KTS\\KTS - CP4 - Part Data Base.txt";
CP4DataBaseRTB.LoadFile(CP4DataBase, RichTextBoxStreamType.PlainText);
string[] splitCP4DataBaseLines = CP4DataBase... |
I've not written many shell scripts and cobbled this together from examples. The 'if' condition should check if this is already running and quite if so. The 'wget' call should trigger the php page and write any output to a txt file. The script will be launched by cron. Is this a reasonable approach?
#!/bin/sh
if ps -ef... |
Having been through hundreds of often-conflicting posts on testing with RSpec, Capybara, FactoryGirl, Spork, Guard and Devise without Cucumber, this is the spec_helper which "seems to" work.
I'm bracing for it to blow up or not work like the previous attempts.
Here's my spec_helper.rb
Questions:
Is there something in ... |
Here is a small script I wrote to get the HNews ask section and display them without using a web browser. I'm just looking for feedback on how to improve my style/coding logic/overall code.
#!/usr/bin/python
'''This script gets the headlines from hacker news ask section'''
import urllib2
import HTMLParser
import re
... |
I have a piece of code that get errors from form and display to view:
$errors = $form->getMessages();
$msg = '';
foreach ($errors as $error)
{
foreach ($error as $err)
{
$msg .= $err . '<br/>';
}
}
$this->view->error_message = $msg;
It look so ugly, but now I don't have any ideas to improve it. Tha... |
This code will be used to map a set of unique keys to a container of objects that are unique to that key. I would like to be able to reuse this code in future projects hence the template, and not hard coding the types into the class. You can also access the code here.
main.cpp
#include <set>
#include <string>
#include... |
This is a follow-on from a previous question I posted here.
I've got code here that works for what I want, but the problem is the loop takes ages to perform. I was wondering if anyone could follow this and tidy it up a bit for me.
Sub Refresh_Data()
Application.CutCopyMode = False
'Turns screen updating off to... |
Because I needed to execute some actions one by one in seperate thread (not to block GUI) and I couldn't use Task.ContinueWith from .NET 4.0 I decided to write it by myself.
Here is how it evolved thanks to your suggestions.
public class ActionQueue
{
private Thread _thread;
private bool _isProcessed = false;
... |
Is there a cleaner way of checking a dataset for tables/rows before attempting to read them?
If ds.Tables.Count > 0 Then
If ds.Tables(0).Rows.Count > 0 Then
'do something with the the rows at this point
End If
End If
Edit to clarify - I am talking specifically about the two bool checks to see if the ... |
This is related to a question I posted on Stack Overflow. The consensus was to use JAXB, which is what I did.
One of the requirements was that it needed to work with legacy XML configuration files. The code needed to be able to start reading new configuration settings from XML files already used to configure pre-exist... |
I'm using the Amazon S3 Java SDK to fetch a list of files in a (simulated) sub-folder. This code is rather standard (AWSConfiguration is a class that contains a bunch of account specific values):
String prefix = "/images/cars/";
int prefix_size = prefix.length();
AmazonS3 s3 = new AmazonS3Client(new AWSConfiguration()... |
I didn't know this site existed before now... awesome!
I just made a thread here: https://stackoverflow.com/questions/8511620/c-palindrome-finder-optimization
#include <iostream>
#include <ostream>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
bool isPal(string);
int main()
{
ve... |
Magnus Lie Hetland in his Beginning python wrote a code to replicate the range() built-in.
def interval(start, stop=None, step=1):
if stop is None:
start, stop = 0, start
result = []
i = start
while i < stop:
result.append(i)
i += step
return result
I re-wrote it like... |
The script takes a string such as this: (15, 176) (65, 97) (72, 43) (102, 6) (191, 189) (90, 163) (44, 168) (39, 47) (123, 37) and breaks it into an array of arrays. It then computes the largest possible number of choices, with the guideline that each selected array has to have both numbers smaller than the previous se... |
I took the Python class at Google code today, and this is what I made for the problem about building a word counter.
Please take a look and suggest any improvements that can be done. Please do point out the bad practices if I have used any.
import sys
def make_dict(filename):
"""returns a word/count dictionary fo... |
I am writing some code to turn a multi level UL into an accordion:
$(document).ready(function () {
$('.s4-ql li ul').each(function (index) {
$(this).hide();
});
$('.s4-ql ul li ul').each(function (index) {
var length = 0;
length = $(this).children().length;
var CurrentItem = $(this).parent().find('a:f... |
How I can change this multi-loop to reduce the computation time?
A is a matrix (5 × 10000) where the fifth line contains values between 1 and 50 corresponding to different events of an experiment. My goal is to find the columns of the matrix which are the same for all possible combinations of 7 different events.
data =... |
I have a pan control that look like this:
Pretty standard Google Mapsish controls, IMO.
When the user clicks in the top 3rd of the control, it should pan up (deltaY = +1); right third means it should pan east (deltaX = -1); Down is deltaY = -1, and West is deltaX = +1. The control is 50px, square. I have working code,... |
Are there issues of any kind with this extension method?
using System;
using System.Web;
namespace AccountingBackupWeb.CacheExtensions
{
public static class Extensions
{
public static T Get<T>(this System.Web.Caching.Cache cache, string key, Func<T> f) where T : class
{
T results = ... |
Background information
I am building a web application that consumes 3 different WCF services that are hosted internally.
Each response object from the service inherits from a base class ResponseBase. This class contains properties int ErrorCode and string ErrorMessage.
When I am consuming these services in my web appl... |
I'm writing a custom JavaScript converter to deserialize some JSON. Here's a few lines I'm writing:
public override object Deserialize(IDictionary<string, object> dictionary, Type type,
JavaScriptSerializer serializer)
{
int NoteID;
NotesModel TheObject = new NotesModel();
if (dictionary.ContainsK... |
I'm working on a function that extracts information from an XML document and compares to what the user has typed in. Can you suggest any ways in which I can improve it? The variables in the XML file are compared against txtSearch.
function checkXML() {
var s = "";
var albumPages = [];
for (var i = 0; i < x... |
I am building a web app that needs to access various tables in a given MySQL db. To do that, I have created a generic class, see DAO_DBRecord.php below, and I create children classes for each table I want to access, e.g., DAO_User.php is used to access the users table. The only difference in the children classes is t... |
I am quite new to JavaScript and I wonder if you experts can see any obvious mistakes in this working code, and if any, suggest good improvements.
// add iframes to page
var normal_sortables = document.getElementById('normal-sortables');
normal_sortables.innerHTML = normal_sortables.innerHTML + '<div class="postbox"><i... |
I have tried using jQuery to create an alternative of marquee, and got no success. It flickers and does not stop on hover. I edited and edited again and it finally came out with a jQuery + JavaScript mess.
JavaScript:
$(document).ready(function(){
marquee();
var timeout=1;
function marquee(){
... |
I have this method for searching a DB based on filters I was wondering if anyone thought as I do that this code is excessive, and secondly if you have any suggestions to shorten the code.
private const string NO_FILTER = "No filter";
[DataObjectMethod(DataObjectMethodType.Select)]
public static List<Part> GetPartsSear... |
We're storing the xml communications with an external service in a text in the db and in a before_create I've got the following:
# filter opera password
def remove_password!
self.request.gsub! /UserPassword\>[^\<]*\<\//,
'UserPassword>[FILTERED]</'
end
Is there a better, safer way of... |
I have written some JavaScript code with jQuery to create collapsible webparts in SharePoint 2010.
Can someone suggest some improvements? As I think that the methods I am using for selectors are not ideal. The solution works perfectly as it is, I just want to ensure that I am being as efficient as possible.
Below is... |
I was hoping I might get some of the brains in Stack Overflow to take a look at my Python static blogger application. I've been using it a few years in a pretty hacked up form. Lately I decided to clean it up and put it up on Github. I'd love some smarter Python programmers to give me advice and wisdom into ways to imp... |
Which version of this code is better?
Ver 1.
a = 0
for i in xrange( 1000 ):
if i % 3 == 0 or i % 5 == 0:
a += i
print a
Ver 2.
from operator import add
print reduce( add,
( i for i in xrange( 1000 )
if i % 3 == 0 or i % 5 == 0 ) )
Things I like about version one is that it is... |
So today I jumbled together a script that would get data from a database, from different tables and such. I had wanted to just use simple ifs without the whiles, but I couldn't make it possible. The code I posted is useable but randomly times out when testing, and i'm afraid of how it would perform under stress. Is t... |
I have written the below code for quick sort in Java:
void quicksort (int[] a, int lo, int hi)
{
// lo is the lower index, hi is the upper index
// of the region of array a that is to be sorted
int i=lo, j=hi, h;
// comparison element x
int x=a[(lo+hi)/2];
// partition
do
{
while (a[i]<x) i++;... |
I need a way to build up a sort of stack of places to search for an item.
What I would like to do is to have each layer searched for an item, and if it is found at that level, then it should be loaded by each higher level (successively).
What I have so far is just a basic framework, but I was wondering if I was missin... |
I'm interested in implementing role based code in C++. I'm also interested in what side effects or barriers (from static strong typing perhaps?) have been added that I am unaware of and if there is a better way.
#include <cstdio>
#include <vector>
#include <string>
#include <numeric>
using namespace std;
// Interface... |
I have a requirement to capture a string in a specific format of * [Numeric Digits] *. This is how I have done right now but I think it would be faster with Regular Expressions. I don't have a lot of experience with RegEx, so please help me optimize this code using RegEx.
if (string.IsNullOrEmpty(BarcodeScan) && e.KeyC... |
Reading Jeff Atwood's "Why Can't Programmers.. Program?" led me to think that almost all of the solutions would not be something I would want in my own code-base. The Fizz Buzz program specification from Imran is here which says:
Write a program that prints the numbers from 1 to 100. But for
multiples of three prin... |
This code is still very naive. I am trying to convert an existing XSD to JSONSchema. Firstly, pardon the variable names (I know some are really just stupid but I will fix them once I get all the functionality to work.)
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System... |
This code works to copy named capture groups of a Regex to the same named properties of a strongly typed object. However, it's not pretty. Someone mentioned I should use polymorphism to at least remove the five if statements.
What should I consider when improving this code? Suggested reading?
// Copies named capture... |
Basically I just wrote this calculator as a sort of JavaScript test for myself. It's a simple calculator with addition, subtraction, and multiplication. I've made some improvements to it before posting this.
At this point I was hoping anyone could just point out some ways I could have cleaned this code up more, basic... |
I'm looking for a review of my current code. It is supposed to capture a paste in the browser window, regardless of the element with focus. This is not the final form as I will be converting it into a jQuery plugin but I'm looking for a review of the logic behind the code.
jfiddle: http://jsfiddle.net/JgU37/44/
$(docum... |
The code below is a good representation of my coding skills. I've been at it for about 6 months. What I am interested in is ways to make the following program faster. I currently have the urlrequests threaded to pull information for 500 stocks, but it is still too slow (around 30 seconds). What python techniques ca... |
Just wondering if this basic performance test between an untyped array of arrays and a vector (typed array) of arrays in Actionscript 3... is fair and balanced? It's simple, designed to test random access on the collections as well as pushing new items, etc. Here goes:
import flash.events.Event;
import flash.utils.getT... |
I'm coding a small web app with no real functionality. It's like a pilot program for something bigger. What I want is construct a program that works as a clock on/off for a restaurant. Actually I'm just trying to simulate one. What I'v done is working but I would like to know whether there is any java class that I can ... |
I use this piece of code to compute a short-time Fourier transform:
// Output pre-allocation
std::vector<std::vector<std::complex<T> > > y(nFft, std::vector<std::complex<T> >(nFrames, 0.0));
std::vector<T> xt;
std::vector<std::complex<T> > yt;
xt.reserve(nFft);
yt.reserve(nFft);
#pragma omp parallel for private(xt,yt... |
private static void OnSundayChangedCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
BinaryDataGrid c = sender as BinaryDataGrid;
if (c != null)
{
if (_shouldCallBack)
{
if (c.Sunday.Length == 4)
return;
... |
I have two very similar functions that exist mainly for syntactic sugar.
deactivate = (el, seek) -> el.find(seek).removeClass("active")
activate = (el, seek) -> el.find(seek).addClass("active")
This allows me to write, for example:
activate $("#something"), ".child"
Using the above purely as an example, ignoring any ... |
I am an eighth grader with a school project of creating and application in Java that returns the total permutations of two given numbers. It needs to be light and efficient, for later deployment on a website. I was wondering if there was any way I could improve the code so it would be more efficient.
class Factorials... |
I'm trying to learn Haskell and the mindset of programming functionally. I have started off by trying to understand the basics by writing code without any Monads in it.
So far, I think I'm getting used to the type system and how the basics works.
I thought to myself, why not try to get some feedback on what I have wr... |
The following code is very slow. I was wondering if you can help me speed it up.
private void filter(List<CheckBox> boxList)
{
// refLanguageTabs is a TabControl the Tabcount is 9
for (int i = 0; i < refLanguageTabs.TabCount; i++)
{
Control[] ctrls = refLangua... |
I'm generating all combinations of an array, so for instance, ["a", "b", "c", "d"] will generate:
[
"a", "b", "ab", "c", "ac",
"bc", "abc", "d", "ad", "bd",
"abd", "cd", "acd", "bcd", "abcd"
]
Here's the code I've written that does complete this task.
What I'd like to know is if there is ... |
public class BQueue<T> {
private Queue<T> q = new LinkedList<T>();
private int limit;
public BQueue(int limit) {
this.limit = limit;
}
public synchronized void put (T t) throws InterruptedException {
while (isFull()) {
wait();
}
boolean e = isEmpty();
... |
I have a xxs list:
xxs:: [(([Char], [Char]),([Char], [Char]),[(Double, [Char], [Char])])]
xxs = [(("a11","b11"),("a12","b12"), [(0,"a1","b1"),(1.2,"a2","b2"),(2.3,"a3","b3"),(4.2,"a4","b4")]), (("c11","d11"),("a12","b12"),[(1,"a5","b5"),(1.4,"a6","b6"),(1.9,"a7","b7"),(4.4,"a8","b8")])]
And I need something like:
foo ... |
I think I'm finished writing a multithreaded reader-writer implementation for my Operating Systems course. I would like to verify that my multithreading is correct and that I'm using good C++0x style.
PalindromeDatabase.h
class PalindromeDatabase : public Utility::Uncopyable
{
friend void *read(void *classHandle);
... |
I have been working on Custom TextBox control, which only allows alphanumeric characters. Note that I have not restricted characters from KeyPress, KeyUp event as I don't want to restrict copy/paste or any other operation that should be allowed generally. I have only trimmed non-alphanumeric character on paste operatio... |
Below is my code which I use to read data from a remote URL (which is GZipped), convert it to a Map, process the map (remove various unwanted fields, etc), the write it back to a file in JSON format.
Unfortunately, it's ugly. I'm doing multiple things in the same method, but can't think of a good way to break them apar... |
I have a data structure that looks like this:
a = {
'red': ['yellow', 'green', 'purple'],
'orange': ['fuschia']
}
This is the code I write to add new elements:
if a.has_key(color):
a[color].append(path)
else:
a[color] = [path]
Is there a shorter way to write this?
|
On my webform, there are two kinds of address-fields a user can give. But since it's a complex webform (Drupal) it's kind of hard to achieve. Every time a user adds an extra address, the form is regenerated and there will be a new item added to the $address_afl and $address_bev-array. Is it possible to compress this co... |
I often end up working with systems where the data is delivered with some Id property and possibly a parentId prop, but never do anyone tempt to actually give me a nice recursive object to play with.
Now, the code below is merely a suggestion in how to solve these kind of "problems", I've created the FlatObject to simu... |
First time I'm using stackexchange. I'm in 8th standard. I tried to implement Queue in Java. I wrote something like this> Right now I'm not able to test it because I don't have JVM in my machine. So I just wanted to know Is this correct implementation? Am I going in the right direction?
import java.lang.*;
import ja... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.