instruction stringlengths 71 71.9k |
|---|
I'm trying to read data from an array. I manage to get the information I want but my code is extremely inefficiently written.
My array looks like this:
var arTab:Array = new Array();
arTab[0] = new Array(2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012);
var promilleTab:Array = new Array();
promilleTab[... |
I have a multidimensional array of house properties:
$array = array(
array('apn' => 345345353, 'sqft' => 1121, 'address' => '12 Lincoln Ave.'),
array('apn' => 345345351, 'sqft' => 1643, 'address' => '13 Lincoln Ave.'),
array('apn' => 345345352, 'sqft' => 1222, 'address' => '14 Lincoln Ave.')
array('apn'... |
This is the first time I tried to solve a problem and wrote code for it, rather than learning some code and trying out to see what I might be able to do with it. As such, it's not much, but I'd like any tips and help about how I wrote this. Basically, I tried to write a program to find the biggest number in a list of n... |
data =
[ { 'name' => 'category1',
'subCategory' => [ {'name' => 'subCategory1',
'product' => [ {'name' => 'prodcutName1',
'desc' => 'desc1'},
{'name' => 'prodcutName2',
'des... |
I'm trying to make sure I understand how to write clean and robust idiomatic Scala, so I wrote a custom generic implementation sequence of type A[B[C]] => B[A[C]] (instead of TraversableOnce[Future[A]] => Future[TraversableOnce[A]] -- I know something like this exists in scalaz).
Is the following code a reasonable and ... |
I'm working on some precompilation operations for a world compiler. Currently to identify flags placed by the level designer I need recognize when a specific entity exists at specific coordinates from the flag's origin. I need to generate a list of offset coordinates from the origin(and include the origin) in string fo... |
I want to understand how to properly unit test a function such as this. The function doesn't return anything, but it does call other functions that themselves have already been unit tested. My understanding is that in order to properly unit test this method I will have to shim the dependant methods - otherwise this is ... |
How does it look? Comments, code correctness, etc.
//Function Prototypes
void buildArray(int anArray[]);
void printArray(int anArray[], int start, int end);
void sortArray(int start, int end, int masterArray[], int tempArray[]);
void mergeArray(int start, int split, int end, int masterArray[], int tempArray[]);
void... |
I have some .csv files compressed in .bz2 format. I need to take a subset of the records (and data) and switch to .gz.
I am not happy with the performance. Is there a more efficient way to do it?
//For each file in a folder:
try (BufferedReader br = new BufferedReader(new InputStreamReader(
new BZip2CompressorI... |
This little function can make object creation much easier.
Sometimes you need to switch between representing your data as objects vs. having the members in separate containers.
Example:
class Foo {
public:
Foo(int a_, double b_): a(a_), b(b_){}
int a;
double b;
};
And then:
std::vector<int> as = {1,2,3,4,... |
I want to compare the values in two arrays. The order of the values doesn't matter. Basically they are two Sets. This function returns true if the values are the same in both arrays, or false otherwise.
function compareSets(a1, a2) {
if (a1.length !== a2.length) {
return false;
}
var len = a1.lengt... |
I am starting an angular app and I was wondering if I am on the right track with this. I worked on my last angular app when I was just a youngun who didn't understand the important of designing the code properly. I failed so hard at keeping the code clean and maintainable, mostly due to not understanding directives or ... |
(define (tridiagonal n)
(build-list n
(lambda (x)
(build-list n
(lambda (x)
(cond
[(= x n) 2]
[(or (= x (- n 1))
(= x (+ n 1))) 1... |
This is not "real life" code. I'm trying to expand upon the well known Sakila sample database for MySQL to make it more complex. Step 7 (or 6) is running surprisingly slow.
PS: Note these are all separate queries executed against the same database in the order specified.
Add columns to sakila.customer table:
USE sak... |
I wrote a function to convert a hexadecimal string representation (like 0x00) of some binary data to the data itself.
How can I improve this code?
QByteArray restoreData(const QByteArray &data, const QString prepender = "x")
{
QByteArray restoredData = data;
return QByteArray::fromHex(restoredData.replace(prep... |
I'm try to create array of strings from a text file. I need a review from experienced programmers about my program. (MinGW gcc, Win7)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main()
{
FILE *file;
char *fname = "lines.txt";
file = fopen(fname, "r");
if(file == NULL)
printf("Can't read %s", fname... |
Can someone check my Merge Sort implementation on Java? Is it good/bad and can it be improved further?
public class MyMergeSort {
private int [] data;
public MyMergeSort(int[] data){
this.data = data;
}
public int[] sort(int[] data){
if (data.length < 2){
return data;
... |
I'm using Express 4 to provide routes to HTML/Jade files, and as well to provide an API.
I want to separate routes from server file, and go even further- separate API from WWW. My code now looks like this:
server.js
//================== ROUTES ======================================
require('./routes/api')(app, express... |
I've created a Views Counter in Python, Gevent and MongoDB (Flask is also included in the full stack as you can see from the context issue in the code).
My gut still tells me that it can be still somehow improved though.
What the code does is initializing a dict "buffer" (just a shelve persisted in memory [no writeback... |
Here's part of code in Java for battleships game I'm working on:
lblGrid2 = new JLabel(new ImageIcon(myPicture));
lblGrid2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
for (int i = 0; i < shipList.size(); i++)
if (shipList.... |
I defined a function that multiplies its argument by 3:
coffee> foo = (x) -> x * 3
[Function]
We can call it with an input of 1:
coffee> foo(1)
3
However, when I tried with a non-Number type:
coffee> foo("3")
9
This behavior appears wrong to me since a String cannot be multiplied by a Number.
To fix it, I'd add some... |
In Kernighan and Ritchie (the C programming language):
Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
I wrote the following code. Do you have advice to improve it?
#include <stdio.h>
/* copy input to output, replacing each
string of one or more blank... |
There's a new version of this as v2 - Adding a duplicate entry randomly into a list in haskell using random monad
I wrote this trying to set up a Haskell testcase. The aim is to take a list and add a single duplicate from any place in the list to anywhere else in the list.
I'm trying to learn to use the Random Monad p... |
I have 3 tables, 1 where voters information is stored, 2 where their address is stored and 3 where voter ids are matched with address ids. I thought this approach was best as several voters can occupy the same address.
Now I have Query that selects all the voters on a given street / road. Although it works, I'm not su... |
This problem:
The Shallow Alto city council has organized a special committee to review the traffic situation in the city. Despite the fact that there is nothing whatsoever to do in the city, citizens still write complaints about the amount of time it takes them to get from one unexciting location to the next. The com... |
I'm taking user input from a file in form (1, 2, 3) to create a color, and I just wanted to know if I was taking most cases into account, and if there is any way I could improve this method in terms of being robust and readable.
private Color getColorFromString(String rgb) throws MalformedColorException{
rgb = rgb... |
I am working on a bookmarker project for replacing storage of bookmarks in a web browser. It will be storing bookmarks as per categories in a database. I have written some jQuery for the WIP search page.
A bit about functionality
There is a search box for categories with autocomplete which is done by my app
On clicki... |
I've just started to play around with Python and I've decided to create a little script that post tweets every hour (cronjob on Ubuntu) telling what time it is.
I'm not sure if I follow best practices or if I can make the code even shorter/cleaner/nicer? I'm a C# developer so I miss a few things in Python, like string.... |
I'm wondering what the best approach might be.
One approach is to chain cachedPromise and "regular", thus, if cachedPromise fails, we call a regular one (and caching results).
The second is to have a wrapper function, something like a decorator in python, and being able to wrap any promise-returning function when neede... |
I was given an assignment, it was as follows:
Give a JS code snippet which writes to the console from:
"0" to "ZZZZZ" all the combination of the characters of a-z, 0-9 and A-Z.
Is my solution correct?
I am sure there are better ways to achieve the same, can anybody show some?
My code is:
function createCharSet(){
... |
I have a very basic OpenGL instanced rendering setup, which is compiling and running, however it is super slow, and even though I spent days of asking and reading how to fix it, I still have no clue, what causes the problem..
What does slow mean? At the moment as you can see, it draws
16 000 instances (48 000 vertices... |
Please critique this CoffeeScript code. Is it idiomatic?
MoneyAccount = (balance = 0) ->
obj = {
withdraw: (x) ->
if balance < x
throw new Error("not enough funds in account")
else
balance -= x
console.log "withdrew funds."
x
deposit: (x) ->
if (typeof x isnt ... |
I am to use VBA code to simply retrieve certain data from all Excel files in certain folder and paste it in working spreadsheet. I am not sure that this is the most efficient (which matters as I would like to learn how to write the most possible efficient codes).
I am using simple copy/paste actions but maybe there are... |
I was recently working on a project where I had the following setup:
from stargaze.sg import SGObject
from stargaze.constants import NegInf, Infinite, PATH_CLAMPED, PATH_REVERSIBLE, PATH_ACCELERATABLE
from stargaze.utils import clamp
__all__ = [
'PathIdentifier', '_basePath', '_clampedPath', '_reversiblePath',
... |
I have both the regular for each loop and its equivalent paralleled version. The loop simply iterates through a collection, looking for the rate key in a local db instance and then updating the topic code.
using (var db = new SomeEntities())
{
foreach (var measure in measures)
{
var keytofind= measure.... |
I ran into a problem recently where I had to decide whether a set of sum types was homogeneous (all the same). In itself, this is a pretty simple problem. However, there were a few complicating factors:
There exists a type within the types (call it Id) that is ignored in the comparisons.
There exists a type (call it M... |
I need a lock-free queue which is implemented by doubly linked list.
Is my code correct? Are there any errors? Are there any improvements to be made?
linkedlist.h
/*
* linkedlist.h
*
* Created on: 2014. 5. 10.
* Author: dlaru_000
*/
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
/*
* circular doubly linked... |
I've been designing UIChessboardView in the likeness of UITableView using protocols and delegates.
UIChessboardView.h
@interface UIChessboardView : UIView
@property (retain) id chessdelegate;
-(void) selectChesstileWithID:(NSInteger) tileID;
-(void) deselectChesstileWithID:(NSInteger) tileID;
@end
@protocol Chessb... |
I was attempting to write my own simple version of the Piano Tiles game app in Java just as a fun exercise.
GameLogic.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class GameLogic extends JPanel
{
Tile[][] tileArray = new Tile[4][10];
int lowestIndex;
i... |
I understand that using goto in C++ code is strictly unadvised, but sometimes, it really reduces the number of lines of code like in the following case.
This is my code for SPOJ. I know this does not reduce too many lines of code, but in a big project, it potentially could.
#include<iostream>
#include<cstring>
#include... |
The following is my solution to Java vs C++. I think the way I have used the re library is inefficient, and possible erroneous as I am getting tle.
import sys
import re
cpp = re.compile("^[a-z]([a-z_]*[a-z])*$")
java= re.compile("^[a-z][a-zA-Z]*$")
r = re.compile("[A-Z][a-z]*")
lines = [line for line in sys.stdin.read... |
I wrote a program for downloading files in concurrent / parallel (GOMAXPROCS > 1) manner.
This is my 2nd (non-toy) program written in Go. Please point out areas for improvement:
package main
import (
"errors"
"fmt"
"github.com/kennygrant/sanitize"
"github.com/nu7hatch/gouuid"
"... |
I'm designing a simple GUI using tabs to separate each 'window' of the application. There are 3 main tabs, each with 2 sub-tabs.
In one class I create the entire hierarchy of panes and panels:
mainPane = new JTabbedPane();
mainPane.setBounds(0, 0, WIDTH, HEIGHT);
//instantiate main tabs, get panes added to them
create... |
I know using global variables in JavaScript is bad practice. Here I am using config, host and port as global variables as I have added a watch function to watch for the changes in the config.json file. Is the use of global variables in this example a bad practice or is it ok to use them?
config.json file
{
"host"... |
#include <stdio.h>
#define MAXLINE 1000 /* Maximum length of a line */
#define TABSTOP 4 /* Length of tabstop */
int getLine(char line[], int limit);
int lookAhead(char line[], int start, int end);
/*
* Exercise 1-21
* Write a program entab that replaces strings of blanks
* by the minimum... |
In the Python library, sklearn is implemented the algorithm for SparsePCA.
I have written the code for a another version of this algorithm that is much faster in some situations. I have not enough experience with Python and sklearn in order to write code that could be loaded in the sklearn repositories.
It would be n... |
Background
I was writing a promises/a+ implementation, just for fun. About halfway through I decided it wasn't that fun after all, so I decided to do something a little different.
Thinking of promises as a pattern (and not a contract), I figured they basically amount to the following (if I'm missing the point, please c... |
I'm using passport to setup login in an express site. The site is just a playground for me to learn. The code inside login was exhibiting the arrow anti pattern so I decided it was time to learn to use promises.
But I don't know if what I've arrived at is good, bad, idiomatic, or idiotic. Any and all feedback appreciat... |
I am trying to print a board exactly like this with the multidimensional array.
char score[10][10] = {' '};
a b c d e f g h i j
+-------------------+
0| |
1| |
2| |
3| |
4| |
5| |
6| ... |
This is the first time I've actually made my own jQuery script from scratch, because I couldn't find exactly what I was looking for. My code works how I want it to, although I don't know if I did it correctly. Just something about it is screaming to me, and although it works, I didn't do it properly. So I figured I ... |
I feel like there is too much repetitive code going on here. All I am doing is doing a basic regex match for a string in the URL.
If a match is found, I find a li with a class (.index, .grid or .type) and add the active class. This is just for my main nav in an attempt to make it somewhat dynamic.
However, I feel like ... |
Please let me know if you see any performance improvements, bugs, or anything you'd change and why.
public static bool TrySpeculativeUpdate(ref int field, out int result,
Func<int, int> update, Func<int, bool> shouldAbort)
{
SpinWait spinWait = new SpinWait();
while (true)
{
... |
I have this JavaScript excerpt, and I was wondering if this (primarily the usage of switch case) would be considered good practice. One item of note is that I have it separated into two similar parts to not evaluate the same boolean check over and over again when it is static the whole time.
if (strict) {
for (var i ... |
Please help in code reviews for readability, optimizing it, functionality etc.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
public class Merge {
static BigInteger cntInv = new Bi... |
I wrote a simple class that substitutes all file inputs in an HTML for a more complex template and set some actions on it. The code is rather small, but I'm not used to write JavaScript.
I wonder if there is a design pattern or extensively used way to set the callbacks? Of course, overall improvements are welcome as w... |
I have a WPF MVVM Application. I have a Customer Model which is generated by an entity framework (Database first approach) and one CustomerViewModel where I created an instance of a Customer Model and used Model members inside the ViewModel property get and set.
Here is my Customer Model:
public partial class TblCusto... |
The backend supplies an attribute called content which clashes with the controller content, so I'm remapping it:
App.Webinar = DS.Model.extend({
body: DS.attr('string')
});
/**
* Remap content -> body so it doesn't clash with the controller.
*/
App.EventSerializer = DS.DjangoRESTSerializer.extend({
normalize: fu... |
I am trying to learn the clean architecture by Uncle Bob. I wanted some basics and following this good post I tried to implement it in python with some minor differences.
class ValidationError(Exception):
pass
class Repository(object):
repositories = {}
@classmethod
def register(cls, type_, repo):
... |
I've been working with jQuery for a few days now and starting to get the hang of it (it does the thing that I want to do).
I've made an accordion, and the header of each accordion item has an arrow that points up (for being open) or down (for being closed). This code works fine, does what it has to do. When I wrote it,... |
By any means, if any can tell me if this code can be more optimized than it already is, please say so. It's a select statement to my PDO class. When I glare over my code, I'm certain there is a lot of easy improvements.
public function select($table, $where = array(), $Innerjoin = array(), $group = array(), $select... |
The SPOJ problem:
Given a 40 character string representing outcomes of 40 coin tosses,
find the frequency destribution of all the possible outcome triplets.
So, for string like : HHHH....40 Hs ,the result is HHH : 38 and the
rest 0. The exact input output format is given in the link.
My approach, as is clear fr... |
I have a script used for installing few rpms depending on operating system type. Here in this example, the script will install packages on two system "centos" and "suse". The system names are listed in nodes.txt and read as an input while executing the script.
For example:
~]# cat systems.txt
centos
suse
~]# ./myscr... |
I am a big fan of one-liners using sed awk perl and other tools. But there are that are things hard to do in one-liner, such as when you working with a CSV file and there are commas between quotes, or when you want to print a centralized field with printf.
A few months ago I wrote ftable more for fun than anything else... |
I'm just looking for some review for my code. This is a script that checks for outbound links in posts in vBulletin forums, and if it is an external link it will redirect to a template which will load the external site in an iFrame that I also coded, inspired by themeforest and stumbleupon's way of showing external li... |
This is my first real web project and I have never touched JavaScript (barely touched CSS), so I just skipped that and went to dart for fun. Here's a live demo
The code for the dart file is down below. If you could help me improve the code in any way, that would be nice.
Sudoku.dart
import 'dart:html';
TableElement ... |
I have some lines that form triangles. I'd like to challenge the fastest way to find all triangles.
In particular the code should take an ArrayList of Line2D object and return an ArrayList of Triangle2D. The only constrain is to use p1.distanceToSquared(p2) < 1) as equal function.
Note:
My code does not work because i... |
I have created a PHP to change the user's login password:
<?php require_once('Connections/conexion.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gp... |
I'm new to CSS and HTML and while I've achieved a centering of the logo and navigation links, it feels wrong. I'm developing a site for a small non-profit for a side project. I have a logo next to a few navigation links. I put the logo and navigation links in a list.
Could someone take a look at this and tell me if ... |
I implemented std::stack from the STL for deeper understanding of the language and memory since I still am only a beginner. I implemented the stack using a singly linked list.
Header file:
/* Header file for abstract data type "STACK" implemented using a linked list */
#ifndef STACK_H
#define STACK_H
template <class... |
I have the following code that splits a combination of names on either the word and or the & ampersand:
var name = 'Ron & Peggy Sue'; //or 'Ron and Peggy Sue';
if ( name.indexOf('&') > -1 ){
names = name.split(/ & /g);
}
if ( name.toLowerCase().indexOf(' and ') > -1 ) {
names = name.sp... |
This is a follow-up to this post.
In this project (C# Win forms) I'm supposed to calculate wages of employees.
These are the steps:
Calculate earnings from Attendance data. Here all regular earnings like BasicSalary, OverTimeAmount etc will be calculated.
Then these earning details will be shown in a grid where user c... |
The problem statement can be found here. In short, here's what the problem is about:
You're given a set of numbers and you need to find whether the the numbers are ordinary or psycho. For a number to be psycho, its number of prime factors that occur even times should be greater than the number of prime factors that oc... |
Here is the piece of my controller action that takes a session[:auth] hash and then assigns the values to the ActiveRecord object represented by @user whilst the key names happen to be the same.
def new
@user = User.new
if session[:auth].present?
@user.first_name = session[:auth].extra.raw_info.first_name
... |
In a wage processing system which employees MVP pattern We have Model classes WageInfo, EarningInfo, DeductionInfo and AdvanceInfo and entity class Advance. (With several other classes)
EarningInfo and DeductionInfo has a composition relationship with WageInfo (contained in WageInfo) and also since Advance amount is a... |
This isn't urgent, it is more along the lines of trivia or a challenge. The solution works fine as it is, but I suspect it could be better.
What follows is a method I came up with a while back in a rather ugly situation where I need to make a "best effort" to try casting an object of an unrestricted unknown type TO an... |
It might be a bit redundant, and I'm not experienced enough to wrap it all into one function. But,
I'm aiming for unicode email adresses and a quick loose but secure validation. How can I improve this?
note: I'm using PDO, so I'm mainly focusing on preventing HTML injection. Is this an issue ether way if I'm outputting... |
I wrote this code for reversing a doubly linked list containing words in each node, which works perfectly fine. My teacher says the algorithm is difficult to understand and the code as a whole could be made more efficient(reducing overhead and memory consumption).
What changes can i make to the code/the reversing algo... |
I am hoping someone can help me tidy up my code (for a practical for university). The practical is to use the random number generator to produce 100 integers (all between 1 and 10) and store them in an array. We then need to scan the array and print out how often each number appears. Following this, we needed to create... |
I am using the Python module urllib3. It occurs to me that there is a better way to design a good class when I rebuild my last site crawler.
class Global:
host = 'http://xxx.org/'
proxy=True
proxyHost='http://127.0.0.1:8087/'
opts=AttrDict(
method='GET',
headers={'Host':'xxxx.org',
... |
How could I improve this code to make it shorter and more functional?
#!usr/bin/python
import time
integer = 0
print("The current integer is set at " + str(integer) + ".")
print("\n")
time.sleep(2)
prompt = raw_input("Would you like to change the integer? (Y/N) ")
print("\n")
if prompt == 'y':
integer = int(raw_inp... |
I would like to get some general comments on style and use of STL in particular. This is some code I wrote to do machine learning classification (logistic regression). Any suggestions would be very appreciated!
A record containing an individual training example:
/*
* A class representing a single record to be used for... |
In this program, I have been asked to read an existing textfile (1324passlist) containing a list of passwords, then create a dictionary file with both the password and MD5 hash of the password on the same line. It should also have the user input a password hash, search the created dictionary file and print the correspo... |
Can someone improve this code? I need to eliminate the for loop.
public bool CheckMobileSim(List<Mobile_Range> numberRange, string MobileNumber)
{
bool SimType = new bool();
string NineDigits = MobileNumber.Substring(0, 9).ToString();
long Number = Convert.ToInt64(NineDigits);
if (numberRange != null)
... |
I am developing a BlackJack game using Java, and it came to a point that I am using instanceof operator to determine if it is a type of some subclass.
Here's an example:
public void checkForBlackJack(Player player) {
Hand fHand = player.getHands().get(0);
if (fHand.getCardScore() == 21) {
fH... |
I have a Value class that may represent many different types:
private BigInteger fNum;
private BigDecimal fReal;
private ArrayList<StaticValue> fArrayValues;
private int fArrayOffset;
private HashMapArray<String, StaticValue> fRecordValues;
private boolean fIsCharLiteral;
private int fEnumOrd;
private char fCharLiteral... |
I've successfully solved the Alien Languages problem for Google Code Jam in Haskell:
The algorithm is trivial - turn the patterns into regular expressions and see how many of the known words match these expressions.
But - this has taken me far longer than I expected it to, and most of the time I was battling with getti... |
Can anyone review my addMatrix() method to see if I am following the instructions correctly?
These are the instructions:
This is a public method (I'm calling it addMatrix()) that has only one parameter for a DoubleMatrix to add this doubMatrix (not changing this doubMatrix) and the parameter's doubMatrix and return a ... |
Im using Struts2 running in google app engine.
User can use their google and facebook account to login to the site. When a user login, i have:
session.put("email", email);
When a user log-out, I have
session.remove("email");
In Struts2 Action, I have the following:
public class ChapterAction extends ActionSupport imp... |
Can you help me optimize the speed and security of my homepage?
(Link now dead - 2014/04/10 - http://www.pixel-klicker.de)
var aktiv=0;
var red ;
var enable = [];
var count = 1;
var number = 0;
var Jetzt = 0;
var Start = 0;
var codes = [];
var xmlHttp;
function createXMLHttpRequestObject()
{
if(window.ActiveX... |
I posted the following code on here a few days ago:
public class Practical4_Assessed
{
public static void main(String[] args)
{
Random numberGenerator = new Random();
int[] arrayOfGenerator = new int[100];
int[] countOfArray = new int[10];
int count;
for (int countOfGen... |
explain:
from start day till now I've got 7.7 mb size, how long it will be to make it 10 gb size
open System
let dd = (DateTime.Now - DateTime.Parse("12/09/2012")).Days
let oneday = 7.7 / Convert.ToDouble(dd)
let in10gb = Convert.ToInt32( Math.Round (10.0 * 1024.0 / oneday) )
let years = Convert.ToInt32( Math.Round (... |
public bool CheckPlace(string State, string City)
{
TestDataContext data = new TestDataContext();
bool IsKochi = new bool();
if (!string.IsNullOrEmpty(State) && !string.IsNullOrEmpty(City))
{
var Place = (from a in data.Places where a.State == State || a.City == City select a.Place).ToList();
... |
The basic idea here is that I want to measure the number of seconds between two python datetime objects. However, I only want to count hours between 8:00 and 17:00, as well as skipping weekends (saturday and sunday). This works, but I wondered if anyone had clever ideas to make it cleaner.
START_HOUR = 8
STOP_HOUR = 17... |
Guava has a feature request which is asking to provide the ability to forget memoized value on a given supplier.
On top on that I needed another functionality where if during the calculation of expensive value another thread would invalidate the data, the memoisation should retry (guava LoadableCache doesn't provide th... |
When I look at this style of code I feel like there has to be a better way to write this:
<div id="by_cx">
<!-- free text input for name -->
<label>Name:<input type="text" id="cxByNameInput" name="cxByNameInput"/></label>
<!-- cx state drop down -->
<label for="cxState">State:</label>
<select id="cx... |
public static class ThreadStatic<T> where T : new()
{
[ThreadStatic]
private static T instance;
public static T Instance
{
get { return instance ?? (instance = new T()); }
}
}
Used like this:
var probability = ThreadStatic<Random>.Instance.NextDouble();
Can this be broken? (Like, am I mi... |
So I created this custom application and ported it into a few websites. It uses the Twitch API and pulls in active streams and the viewer count. The problem I run into is when the list gets so big it seems to become too much to do though ajax. I think this because sometimes it will show a stream online when it has been... |
As part of an assignment in Cryptography I've been asked to write code that involves calculating modular exponentiation. The BigInteger modPow is not allowed in this case, we have to implement it ourselves.
I have the assignment working, but I think my modular exponentiation function is not the greatest in terms of ru... |
How can I design this class and its implementation so that it looks like it was developed by a seasoned senior level PHP developer that follows all of the best practices? I'm trying to design this class so that it can be reused in other applications. I also have some other questions that are located inside of the code.... |
This function was hard to write as a Clojure newbie, and I don't like the result.
Can you help me find a better (more readable) way to do it?
(defn split-seq
"Splits a seq into blocks defined by start-fn and stop-fn.
Returns a lazy seq of seqs"
[start-fn stop-fn lines]
(let [step (fn [c state]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.