instruction stringlengths 71 71.9k |
|---|
This is my first attempt at putting the conceptual knowledge I've gained about graphs into code. When searching for examples they all seem overly complicated, and searching for a tutorial or introduction leads to conceptual information. So here I am trying to code a very simple graph and this is what I have. The vertic... |
I am trying to add parallelism. The following function works. For testing purposes, calculating chunckLength is fine. However, when I allocate more cores, it seems to slow down significantly which seems due to massive overhead. The visualisation shows the average core utilisation during execution. Each run, the functi... |
I'm reading monadic parser combinators. On the page 23, they leave an exercise for defining a Gofer block comment parser, and I try to implement it in Haskell.
My code is here:
import Control.Monad
import Data.Char
import Data.Maybe
newtype Parser a = Parser
{ runParser :: String -> [(a,String)]
}
-- return `... |
I'm currently implementing an interner in the style of Guava's Interner, where:
an intern pool is maintained for an immutable class
whenever a new instance of that class is created, it's checked to see if it's equal to an existing instance in the intern pool
if such an existing instance is found, it's returned, otherw... |
The users get permissions to do specific things for a specific group of employees. These employee groups have a self reference. So an employee group (C) can be a child of group (B), and group (B) is child of (A). The user is granted permission to employee group (A), so if I want to check if the permission is granted fo... |
I went with what I know and can use well, not what I know and can't figure the syntax out to make it look good.
So please enjoy the code and prepare to school me (probably in the basics) in C#
public static void Main (string[] args)
{
/* Here are your rules:
"Scissors cuts paper,
paper covers rock,
r... |
I am somewhat new to Java. I want to know if this is the proper way to share text with other Android applications, and if I am properly determining if the text is selected. Is there a better way to share the selected text? Is my decision statement proper? The app works just fine.
package com.kylelk.sharedemo;
impo... |
Say I have the following SQL:
SELECT
amount,
amount*.1,
(amount*1)+3,
((amount*1)+3)/2,
(((amount*1)+3)/2)+37
FROM table
Instead of repeating that identical code every time, I really want to be able to do something like this:
SELECT
amount,
amount*.1 AS A,
A+3 AS B,
B/2 AS C,
C... |
I need some opinion if my code below is proper for an async process. This code only reformats text. Please let me know if this implementation is not proper or needs some improvement.
static void Main(string[] args)
{
Task.Factory.StartNew(() => ReadCharacter("File 1.txt"));
Task.Factory.StartNew(() => ReadChara... |
Review this code regarding optimization, cleanup, and best practices.
final class EdgePrims<T> {
private final T source, target;
private final int distance;
public EdgePrims(T node1, T node2, int distance) {
this.source = node1;
this.target = node2;
this.distance = distance;
}
... |
In my code's package, I have a flag such as:
public static final boolean LOGS_VERBOSE = false;
And in worker classes (multi threaded Runnable jobs), I have code like:
if(XYConstants.LOGS_VERBOSE){
logger.debug("some state info var 1:" + var1 + ", var 2:" + var2);
Is this a good idea? Is there any performance gain... |
The next bit of code does exactly what i want it to do, but it is 'rather' unelegant and unpythonic, so the question is quite simple: how can this code be changed into something more elegant
import numpy
from scipy.stats import nanmean
A = [[1, numpy.nan, 2],[2,3,4], [2,3,4], [numpy.nan, 5, 5]]
A1 = numpy.array(A)
pri... |
I was given a task:
Given any integer - write a program, which:
finds all digits of the integer
writes odd and even digits from the integer
finds the biggest even and smallest odd digit
writes the biggest possible number that can be formed by rearranging the odd digits
writes the smallest possible number that can be ... |
I would like your opinion on the following subject.
I have to provide icons in different sizes and states. The sizes will be 16*16, 24*24 and 32*32.
The states bright, dark, disabled and link.
Because of browser support we decided for .png instead of .svg.
Do you feel this is the best CSS approach for this case?
Would... |
There doesn't seem to be anything really wrong with this method. But it has a little smell to me. Does the name make sense (do what you think it would do). Is there some logic I could use to make the enabler a bit more elegant?
private void tryEnableCRUD(bool tryEnable = true)
{
bool enable = false;
if (_securi... |
I initially thought that this was just an architecture issue so I placed it on programmers as Thoughts on refactoring a generic DAO. Then I asked on codereview meta here and decided to put up the code here.
Here's a github link if someone wants to see there.
There are four DAOs - DAODelete, DAOUpdate, DAORead, DAOIns... |
open System
type Date = System.DateTime
type SafeDate =
| WorkingDate of Date
| InvalidDate of Exception
let dateAttempt (x: int, y:int, z:int) =
try
let returnDate = Date(z,y,x)
WorkingDate returnDate
with
ex -> InvalidDate ex
let rnd = System.Random(4)
let randomBirthYear... |
I have been writing the application. I meant to implement a repository pattern with Unit of Work. Is it correctly done? Can you make a code review? I use SQLite wrapper sqlite-net.
IFeedRepository:
internal interface IFeedRepository<T> : IDisposable where T : IBaseFeed
{
int Count { get; }
void Add(T feed);
... |
Is this a valid and safe use of .NET's System.Threading.SpinLock?
Why am I doing this?
Random's public methods are not thread-safe. I could be calling from
any thread which I do not know until run-time; they are from the
Thread Pool, and it could be called fairly frequently (up to a hundred
times a second), so I... |
I have an array where each element is either one less or one greater than the preceding element \$\{x_i = x_{i-1} \pm 1\}\$. I wish to find an element in it in less than \$O(n)\$ time. I've implemented it like this:
public int searchArray(int[] arr, int i, int elem) {
if (i > arr.length - 1 || i < 0) {
ret... |
Continuation of this question: Unit of Work with Generic Repository Pattern MVVM
I have made some modifications:
Interfaces aren't forced to implement IDisposable
Removed the finalizers
Rebuilt UoW
FeedRepository:
internal class FeedRepository<T> : IFeedRepository<T>, IDisposable
where T: IBaseFeed, new()
{
... |
I have been building a site using php and would like advice to improve the structure of my site and the best way to lay out my code for SEO. I'm also a little concerned about echoing large chunks of HTML and how SEO will work with my structure.
Ok here's my structure...
My site contains many pages with only the body co... |
I've made a Regex to find any URL on site, which uses PHP:
Reg = new System.Text.RegularExpressions.Regex("((http|https)://([a-zA-Z0-9-]{1,}[/]?))?[/]?([a-zA-Z0-9-]{1,}[.](php|html))((/[a-zA-Z0-9-]{1,}){1,}[/]?){0,}([?]([a-zA-Z0-9]{1,}=[a-zA-Z0-9\"><();/.,]{1,}&?){1,})?");
Is this code optimal, or is there a better so... |
I have a method that checks to see if a hash of given items should have discounts applied and if so, determines and returns the discount:
def get_discounts
@items.each do |name, attr|
@specials.each do |special|
while name == special.sale_item && attr[:quantity] >= special.quantity
@discounts << spe... |
The current code solves the issue I had when trying to use property injection.
Problem: Every module must use constructor injection because of a circular reference that occurs when not using constructor injection with my factories and trying to use property injection
Reason: A module requires a client and each client m... |
This looks pretty messy (need to reduce nesting I feel). I need a check an input for a seat, but I can't guarantee it has a value (one may not be chosen for example). If the seats aren't in a certain color it goes to seat basic (1), otherwise seat premium (2).
var seat = $("input[id*=" + seatPrefix + "]");
if (se... |
There is a user login, and the requirements are the following:
The login must start with a Latin letter.
The login must finish with either a Latin letter or a digit.
There may also be digits, dots, and minus signs in the login.
Min. login length is 1.
Max. login length is 20.
Here is my Java code.
boolean checkLogi... |
I'm rather new to jQuery but managed to get some social links to open in a new controlled window instead of new tab. I have a few functions that do the same thing, and this works, but there is always a better method.
I did review the question and answer here and couldn't figure out which would apply to this case.
jQuer... |
I just learned the quicksort algorithm and tried to implement it, but it feels dirty:
#include <iostream>
void quicksort(int list[], int low, int high)
{
if(low >= high)
return;
else
{
int pivot = low, i = low, j = high;
while(i < j)
{
while(list[i] <= list[p... |
I'm looking for any and all feedback on quality, style and efficacy of the code. If there's a simple way to get the header put in, I'd love to hear that.
The code is used to take zip codes from a csv file and and spit back out the city and state where available.
import sys
import os
import csv
from bs4 import Beautiful... |
I've just created a winform that exports a datagrid to Excel. Originally the file was never shown, but I was asked to give the option. So I put in a checkbox and modified the code.
Is my if/else statement at the end enough or should I go about it a different way?
private void buttonExport_Click(object sender, EventArgs... |
I've written a code snippet that will get a (max.) 14 character string from the user input, and while the user is typing, simultaneously echo it out to the screen.
It seems a bit long and ugly, so I was wondering if any of you would happen to have ideas on how to shorten, and generally optimize this.
for(int i = 0; i <... |
This is probably horribly sloppy, but here it is! This is a section from a large (imo) GUI program I am making. The below code is what triggers when a specific button is pressed.
def calc_platenumber(self):
customer_firstname = str(self.customer2_entry.get())
customer_lastname = str(self.customer3_entry.get()... |
One of my colleagues told me that you can use streambuffer for std::string, and instead of using string id in the for loop, you can declare it outside.
I am not sure whether this will make any difference or not.
void getRecord(uint64_t currentTime, const std::vector<uint32_t> &shards) {
try {
currentTime ... |
I am developing a WPF application that requires me to get an Access Token from Facebook using oAuth. After much searching online, I came to the following conclusions:
OAuth must be done in a browser
I need to watch the URL posts in that browser, therefore it would have to be inside a WebBrowser WPF control
I decided ... |
I would like to develop a kind of template or canonical implementation for a concurrent subclass of NSOperation.
Edit: there is a related request which implements the NSOperation subclass in Swift.
Requirements:
Thread safe API.
start shall only start the task once, otherwise it has no effect.
The NSOperation object s... |
How can I shorten and optimize this code which displays then hides a DIV?
setTimeout(function () {
$('.updateNotification').show().addClass('heightener');
callback();
},2000)
function callback() {
setTimeout(function() {
$( '.updateNotification' ).fadeOut();
}, 10000 );
};
My first thought was to comb... |
Enter risk!
This program will roll dice for the game of Risk. The initial input is two numbers separated by a space and if the attackers wish to do a blitz they can add one more space and an "!" to get a positive attack modifier but are committed for an all or nothing fight.
package riskdieroll;
import java.awt.Compone... |
I'm trying out a new approach to SASS stylesheets, which I'm hoping will make them more organizined, maintainable, and readable.
I often feel like there is a thin line between code that is well structured and code that is entirely convoluted. I would appreciate any thoughts as to which side of the line this code falls... |
Though I have heard about the magic method __autload, I still prefer to use this code:
function autoload($array)
{
foreach ($array as $value)
{
switch ($value)
{
case 'database' :
include ROOT_DIR.'/core/database.php';
break ;
case 'user'... |
You have to find a path through which the rat move from the starting
position (0,0) to the final position where cheese is (n,n). List the
total no of possible paths which the rat can take to reach the cheese.
Sample Input:
7
0 0 1 0 0 1 0
1 0 1 1 0 0 0
0 0 0 0 1 0 1
1 0 1 0 0 0 0
1 0 1 1 0 1 0
1 0 0 0 0 1 0... |
I have the input image in, and the mask image lev (which label each pixel as a number from 1 to nlevels, nlevels=4). I need to get image out, which from each region in==lev will be replaced by its average value.
Here is my brute force approach. I'm wondering if there is any better way of doing it.
Mat ACA::global_aver... |
I have previous revisions of my deck of cards project, but I may not need to link them here since the emphasis is on the use of templates.
I've never used them before until now, and I like how intuitive my implementation has become. However, I'm also aware that there are many pitfalls in C++ templates. Although I don... |
Seeking code correctness and best practices.
I would like to re-allocate various amounts of memory (0 or more) such that on systems that may return NULL for an allocation of 0 does not falsely imply a memory allocation error.
Given:
void * (with a valid value or NULL already)
size_t (new desired size)
Receive:
voi... |
var romanArray = [];
var toRoman = {
analyze: function(number){
romanArray = [];
if (number >= 1000) {
return this.thousands(number);
}else if (number >= 100){
return this.hundreds(number);
}else if (number >= 10) {
return this.tens(number);
... |
I've been learning Haskell for a few weeks after coming from a C# background. I've written a function to return a number of unique Ints from a specified range:
module MrKWatkins.Random (
uniqueRandomInts
) where
import System.Random
import qualified Data.IntSet as I
uniqueRandomInts :: RandomGen g => (Int, Int) -... |
I've been playing around with Clojure for a while now, and one of the tasks I occasionally find awkward is parsing input. For example, I took part in the facebook hacker cup recently, where part of the challenge was to read input like this:
5
4
..##
..##
....
....
4
..##
..##
#...
....
4
####
#..#
#..#
####
5
#####
##... |
I'm not a dedicated cryptographer, so I'm looking for someone to look over these functions I wrote and let me know if there are any implementation errors leading to security vulnerabilities or just anything I should improve. Any other comments about improving performance, etc. would be great too.
This is used in a PHP... |
I have a number of text files (they are reports from a financial system) stored in a directory. Each report has a particular piece of text to search for (eg Report Total) and then a range of characters to extract for the value (e.g. position 78 for 10 characters).
There are a number of these reports - but no more than ... |
Other people will be looking at this jquery code and i'm not an expert with jQuery so im asking. How can i make this jQuery code shorter, more efficient, and easier to read?
/*
HEADER NAVIGATION
*/
/* navigation tabs click highlight */
$(".header-main-tabs").click(function() {
$(".header-main-tabs").removeClass("hea... |
What can be improved in my code:
using (var oracleConnection = new OracleConnection(ConnectionString))
{
using (var oracleCommand = oracleConnection.CreateCommand())
{
oracleConnection.Open();
oracleCommand.CommandText =
"SELECT *... |
I have a program I am writing that calculates Algebra 2 functions and equations. The interface is all CLI, and I even made commands that are similar to shell commands. That's not the part I want review on, so in the interest of space I'm going to consolidate as much as possible. If you want to check out the full progr... |
Below is a code snippet of how I have been laying out my WPF control XAML. I do it mainly because I get intellisense in the editor and I can change the implementation of the viewmodel and push the layout into a resource file.
However, I am not sure whether you gurus have a better insight into why I should not do this?
... |
I'm new to ASP.Net and up until now my code has worked but has been a mish mash all over the place with no real structure. I'm trying to teach myself how to keep the presentation/BLL/DAL separate so I have built a simple page to try and work with.
Page has 3 text boxes: clock number, first name and last name. On input... |
I have a folder called uploads in this folder is a folder for the year the file was uploaded(2013,2014,2015 etc...), inside the year folder are usernames(rick, dan, edward etc...), inside the usernames folder are folders 1-12 for the month that the file was uploaded.
I want to search through the folders and if there is... |
I am working on using monad transformers in C#. I would like to know if the following code I present, shows that I have understood this. I am fairly new to this so any feedback / comments are really welcome. This example is just for wrapping a maybe monad in a validation monad.
using System;
using NUnit.Framework;
nam... |
I wrote this code in Java without using any methods, just by using simple for loop and if statements.
When we input a number, it checks whether it's a prime or not. If it's a prime, then it prints "It's a prime". And if it's not a prime number, it says "It's not a prime" and prints the first number which divides it.
Fo... |
I have some code below that takes different detected users recognized by the Kinect and assigns them a specific random id range based on the player they are. I use this to grab the x,y coordinates of their left or right hand. I was trying to have the Kinect get at least 6 peoples coordinates with the code. Am I taking ... |
I wrote the following Fizz Buzz program. How can I improve it or make it more efficient?
public class FizzBuzz
{
public static void main(String[] args)
{
System.out.println("--------Fizz Buzz program-------------");
for(int num=1;num<=100;num++)
{
if(num%3==0)
{
if(num%5==... |
The aim is to enumerate all possible sets of whole numbers whose sum is a given integer.
class partition
{
public static void main(String[] ar)
{
part(66);
}
public static void part(int n)
{
part(n,1,"");
}
public static void part(int n, int st, String prefix)
{
... |
I would like the have a second opinion on my code I've written to calculate e
e is an integer that you wherefore the following counts gcd(φ(n),e) = 1 with 1 < e < φ(n)
public int calce()
{
do
{
e = priemgen.newKey(1, euler);
} while (GCD(euler, e) != 1);
return e;
}
private int GCD(int value... |
The game will be combination of text adventure (navigate through buttons), RPG, sandbox, strategy and turn-based game where the main task of player is to explore the game's world and survive (since I cannot classify my game with one genre just yet, I'm still experimenting).
The interaction between player and game, as I... |
I've never done a FizzBuzz before, so I decided I would. Please let me know what I could have done better. This is ran via a .bat file in Windows.
@echo off
set loopStart=1
set loopEnd=100
set /a i=%loopStart% - 1
:LoopStart
if %i% == %loopEnd% goto :LoopEnd
set /a i=%i% + 1
set /a fizzbuzz=%i%%%15
... |
I created a quiz using the module pattern. My code is as follows:
; (function ($) {
"use strict";
var s,
QuizDefaults = {
modalOverlay: $(".modal-overlay"),
modalWrap: $(".js-modal-container"),
timer: null, // setInterval var for timer
totalSeconds: 10, // Amount ... |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Car Rental Calculator</title>
<... |
I have project where I need to use C# and Entity Framework.
After my question here, I have decided to use Unit of Work and Repository patterns.
This is the first time when I'm using this. Can anyone tell me if I'm doing this right or I have to redesign something?
BTW: why do I have to set student.Group = null in Servi... |
I'm creating a simple syslog server in Delphi XE2 using Indy's TIdSyslogServer. I've decided to make it dump into a TClientDataSet and display in a TDBGrid, but I'm skeptical about how well it would handle if the log got quite big, and what I should expect when it grows to millions of records. This application is for i... |
I have code that checks the range of a value and sets a variable accordingly.
if ( 169 <= angle && angle < 191 ) {currentOrientation = "1";}
if ( 191 <= angle && angle < 214 ) {currentOrientation = "2";}
if ( 214 <= angle && angle < 236 ) {currentOrientation = "3";}
if ( 236 <= angle && angle < 259 ) {currentOrientati... |
Some recent discussions on this site involved the Fizz-Buzz game - I have never actually implemented this, but for the record this is what I put together:
public class FizzBuzzConverter
{
private readonly int _fizz;
private readonly int _buzz;
public FizzBuzzConverter(int fizz, int buzz)
{
_fiz... |
I've been reading about WeakPointer and WeakPointer<T> today, and it looks very useful. Rather than just using it as-is though, I decided to write a wrapper around it that covers a common usage case for me.
Code as follows:
public class Temporary<T> where T : class
{
Func<T> generator = null;
WeakReference<T> ... |
Disclaimer: The code already was graded - so I don't ask for a homework here -just for a code review. :)
For a university course my colleagues and I had to implement a list without using any Arrays or any utilities from java collections. Only interfaces were allowed.
We received a small feedback complaining that the ou... |
I wrote the following Caml light code to find prime factors of a number (part of an early Project Euler question).
Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
let rec find_factors target check =
if (check > (int_of_float (sqrt (floa... |
I have written this code for cookie parsing. Can anyone tell me what optimizations we can do in this or what can we do to make it more concise?
function parseCookies(cookies) {
var cookie,
cookieParts,
parsedCookies = [];
if (!cookies || !cookies.length) {
return null;
}
// Remove domain from eac... |
Which of these two alternatives is more readable?
token = map.get(token_str)
if not token:
token = Course(token_str)
return token
or
token = map.get(token_str)
token if token else Course(token_str)
|
I made a small text adventure. I'm not trying to make it appealing to anyone, but rather just to practice my Python skills. I am fairly new to Python and this was my next step after making a console calculator and BMI calculator. I would like someone to tell me how this code could be better optimised, less work, etc.
... |
I must read and extract some values from string. These values are coded like this:
k="11,3,1" v="140.3"
I have defined the codes and created struct with all field as well as a temp one where I store k and v. In fillFields proc I transfer values from temp struct to the right one (with the valid types). It works but I ... |
Here are a couple of examples of one-liners that go way beyond 80 characters:
scope = DepartmentRepository.includes(:location).by_account(@request.account_id).find(approved_department_ids)
departments = ActiveModel::ArraySerializer.new(scope, each_serializer: DepartmentWithLocationSerializer).as_json
I usually simply ... |
I have a Google Maps Geocoder and I am looking to refactor it. The user enters address details into a form where at the bottom there is the option to show on map.
First the map is hidden
The user clicks show_map checkbox
Map-area is shown
Map is initialized
The codeAddress() function is used if the user edits the a... |
I was asked to write a permutation algorithm to find the permutations of {a,b,c}. Since this is a famous question to which an answer is readily available online, I wanted to do it a little differently, so that it won't look like I copied off the Internet. It was evaluated as OK for the algorithm being correct, but said... |
I just wrote this simple code, but I have a problem. I get the factorial for small numbers, but if I enter number like 45 or above, I get 0 as the factorial. Why is that? Check and let me know what you think:
import java.util.*;
public class Testing1 {
public static void main (String args[]){
Scanner sc=new Scanne... |
I'm curious about Object.defineProperty. It seems awfully verbose for not doing much more than what you can already do in the constructor. What's the point of it? Would it be 'bad code' to not use it? I know you have more control over read/write and enumerability with defineProperty, is that enough to use this verb... |
I am building an web application that is going to work in a similar way like photoshop or illustrator regarding layers. Here are my code that is searching the ".case" div for images, and then put these images id's to an array. When that is done we are looping the array to find out if the received image is the same as t... |
We have a binary tree, suppose like this:
8
/ \
6 10
/ \ / \
4 7 9 12
/ \
3 5
We have to print this binary tree in top-down manner - column wise. Note that, 8, 7 & 9 would be considered in same column. So the required output should be:
3
4
6 5
8 7 9
10
12
Currently I've implement... |
I'm just starting to get along with threads in Java and I need some code review,
about interfaces, classes, managing threads, correct writing, secure threads, exposed objects etc.
Horse-Race Implementation:
package HorseRace;
public interface FinishingLine {
public void arrive(Horse h);
}
package HorseRace;
im... |
Please review my code based off of a responsive Initializr template. It's functional and visually correct, but I know there's better ways to write the code. Let me know if I can layout the HTML5 better and/or best practices I'm not using for CSS selectors because I feel my stylesheet is all over the place.
HTML
<!D... |
I haven't had much experience with postgresql (none) and I am wondering/hoping that there is a better way for me to do this query.
SELECT * FROM member_copy WHERE id = 17579 OR id = 17580 OR id = 17582 ect.
There are about 800 where clauses in total so this will take a while and I need to run it on a fairly regular ba... |
I tried implementing Integer Partition (enumerating all possible sets of whole numbers whose sum is a given integer).
Looking at @rolfl's answer, I reasoned that with a stack data structure, we shouldn't need to use recursion, since recursion implicitly stores state in the call stack. I also tried to address @JeffVanz... |
I would like to execute a certain method at a given interval. The reason why I can't use a timer + its event handler right away is because I want to add an offset to each tick (100ms in my example below).
It seems to be working just as intented. The reason why I'm starting it manually is because if the _action(); takes... |
I have not tried decorators yet or functions within functions, but this current un-pythonic method seems a little convoluted. I don't like how I need to repeat myself when I check the return_type 3 times.
Any suggestions are welcome, especially if the repetion can be dealt with in an elegant way. Please note that I am ... |
I'm trying to port the following C loop to Python:
for (int32_t i = 32; --i >= 0;) {
v0 += ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + k[sum & 3]);
sum -= delta;
v1 += ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + k[sum >> 11 & 3]);
}
The problem is that the these integers are 32-bit unsigned and the code above relies on in... |
This code finds all the divisors of a given number. Can it be shortened?
import java.util.Scanner;
public class PrimeNum2{
public static void main(String args[]){
Scanner x=new Scanner(System.in);
System.out.print("Enter the number : ");
long y=x.nextInt(),i;
System.out.print("Div... |
This week's review challenge is a poker hand evaluator. I started by enumerating the possible hands:
public enum PokerHands
{
Pair,
TwoPair,
ThreeOfKind,
Straight,
Flush,
FullHouse,
FourOfKind,
StraightFlush,
RoyalFlush
}
Then I thought I was going to need cards... and cards have a ... |
I came across an interview question, which is like this:
You have an array of integers, such that each integer is present an odd number of time, except 3 of them. Find the three numbers.
I tried implementing it using a HashMap<Integer, Integer>, by mapping each integer element to a number that would identify if that ... |
In my first attempt, I have tried to load images from disk and load it to a QTableView using QAbstractTableModel. I'd like a general code review of this code.
import sys
import os
from PyQt4 import QtGui, QtCore
class MyListModel(QtCore.QAbstractTableModel):
def __init__(self, datain, col, thumbRes, parent=None... |
I am having a structure of 3 tables
Table mintemp consist of matcode,min_qty,jo_no,mr_no
Table min_out_body consist of matcode,out_qty,jo_no,mr_no
Table eu_min_out_body consist of matcode,out_qty,jo_no,mr_no
And data as follow:
[mintemp]
matcode min_qty jo_no mr_no
xxx 100 ... |
I have a nested array that returns objects which are then traversed to retrirve the ids, which are then used to retrieve another array, which is traversed and the values returned are echoed out.
The problem is this seems to take ages in the browser to work across. How do I go about speeding this up?
This is the first ... |
I have a bit of code that converts a Sql Like expression to a regex expression for the purposes of a Linq to objects Like extension method. For some time I have been using this conversion.
This conversion replaces all "%" with ".*?" which works for contains patterns but is over matching for starts with or ends with pat... |
I have the following code that reads a .csv file that than outputs the result in the form of a HTML table:
$fhdrop = fopen("ac.csv", "r");
while (!feof($fhdrop) ) {
$at[] = fgetcsv($fhdrop, 1024);
}
$fhdrop2 = fopen("rc.csv", "r");
while (!feof($fhdrop2) ) {
$at2[] = fgetcsv($fhdrop2, 1024);
}
?>
<table border=1... |
I wrote this script as a proof of concept of reading a file from disk as variable-length quantities (ints encoded using 7 bits from as many bytes as required). I'm mostly making use of the file system ReadStream, for reading byte buffers from files and the varint package for decoding variable length values.
This is is ... |
This is following up on my previous attempt, which was admittedly done fast and not-so-well. This code attempts to allow comparing two poker hands to determine a winner, not only evaluating a given set of cards. (this was actually edited - see original take 2 here).
I'm abstracting the dirt away into an interface... an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.