instruction stringlengths 71 71.9k |
|---|
I wanted a template for a service script that is versatile and easily configurable.
Along with producing similar outputs to the SSH and Samba daemons, I request the code to be as clean, simple and self explanatory as possible. Hence I removed all the comments.
Sample usage:
$ service mydaemon restart
mydaemon stop/wai... |
My getExtend() function, which will be included via require.js, has two inputs and one output:
HTML file content
config object which determine how to update the HTML, for example to create new script (as the first object in the array
extendedHtmlObject ) or update existing script content such as
attributes values... |
I made a function about random backgrounds
And those images will unique as possible. (Shuffle again after all gone)
My steps is :
Setup the array
Shuffle it
Do function (check if isset() so run on)
PHP :
$rand_image_ids = [1048,1049,1061,1064,983,972,964];
shuffle($rand_image_ids);
$rand_images_i = 0;
function rand_... |
This is a small socket library I made to avoid complicated C boilerplate code and several #includes for connecting sockets, bind, listening etc.
Please note that socket_create() does not support bind to specific IP addresses and that the IP parameter is ignored.
The only C++11 feature I am using is constexpr. Even thou... |
I have recently built a plain old Ruby program using TDD with RSpec to model this. I wanted to get feedback.
Repo
For the company whose application we’re looking at, order processing
looks something like:
If we accept an order over the web, then we have to wait for payment
to arrive, unless it’s a credit-card orde... |
I've been working on this pong game for the last 10 days, and I'd like to know of your opinions about it, what could I change to make my code better?
#include <stdio.h>
#include <allegro5/allegro.h>
#include "allegro5/allegro.h"
#include "allegro5/allegro_image.h"
#include <allegro5/allegro_native_dialog.h>
#include <... |
I'm currently writting piece of logic which copies entities from one user account to another. My current strategy in doing this is like that:
Consider the following code:
public class MobileOrderSettings:ICloneable
{
public long Id { get; set; }
public bool allowCash { get; set; }
public int deliveryPrice ... |
Recently I started playing a bit with Slim and what is making me confused is a necessity of container and middlewares hard coding. As because I am a staunch supporter of a dynamic loading I decided to write a piece of code for middlewares that suits my preferences. Considering my programing skills limitations - I am ... |
So I have some code which I created from the top of my head. But in all honesty I know it can't be the most efficient way of doing it.
I have some data in a file all positioned 5 values per line separated by commas (one line will be a specific object) dependent on the name of the item.
I know this can't be the best way... |
I'm fairly new to F# and have written a program to parse PLY files - this is however done in an imperative way with mutable values and as far as I know that should be avoided in functional languages.
The program works, but is the performance weakened by this imperative way of doing things? How is the coding style?
modu... |
Description:
Since the input array is sorted, we can take the middle element of the array to be parent and recursively do the same on the left and right halves to create left and right sub trees of the parent.
class Node{
int data;
Node left;
Node right;
Node(int x)
{
... |
Looking for some constructive feedback on Parsing an Address without using Regular Expression in C# for performance purposes.
My aim is to clean the data and to separate it into its respective fields: HouseNumber, Directional, StreetName, StreetType, Zip, City, State, Apartment
Example Input: 123 Main Street
Example ... |
open Core.Std;;
let print aofa =
let s1 = ( Array.length aofa ) - 1 in
for i = 0 to s1 do
for j = 0 to (Array.length aofa.(i)) - 1 do
printf "%d " aofa.(i).(j);
done;
printf "\n";
done;
;;
let rec fact i =
if i <= 1 then 1 else i * fact (i - 1)
;;
let rec permuta... |
I've recently started to check out Angular 2 and TypeScript that comes with it, and I guess I'm kinda into it. However I'm not too sure about the whole "TypeScript way" of doing things, specifically the typing of variables and such.
I wrote this simple modal component which displays a modal when the ModalApiService has... |
I want to clone a collection with the following method and I want to know if it can be optimized:
public T CloneCollection<T>(IEmployees employees) where T : IEmployees, new()
{
T collection = new T();
foreach (IEmployee employee in employees)
{
collection.Add(employee);
}
return collection;... |
I'm working on a language called grond (see it on GitHub); the compiler is so small it is included in this post.
My gut tells me that this code is awful, but it works. I am hesitant to change things to make the code better because generally, I have found that bad things happen when I "fix" something that isn't necessar... |
I have answered to a question on Stackoverflow where Andy struggled to cancel a Stream copy to file operation using the Universal .NET Framework:
Apparently, cancelling the cts CancelOperation token had not the expected behavior.
await httpResponseContent.Content.WriteToStreamAsync(streamToWrite.AsOutputStream()).AsTas... |
Given a string of length n, print all permutation of the given string.
The code bellow generates all permutations (with repetitions) for the given string and stores them in object res. Could you suggest ways to make the code faster (or a completely different algorithm written in R)? (For the "ABRACADABRA" word it tak... |
Just an idea I had for a Java exercise. Cracking a password like "testing" takes at least 15 minutes, so obviously it's not as efficient as it can be. What are your thoughts? I also never worked with multithreading, so I can imagine I could be doing things better there.
public class AlgoTester implements Runnable {
... |
I rarely see this kind of navigating on the web. But basically I load all the content in the background and then flip pages as needed while loading user specific data via ajax.
Are there any problems with this and in general?
/********************************************************************************************... |
I need to find the length of elements within a string and return it to the user.
What is the best way of simplifying this code to make the amount of string lengths equate to user input? Also, how can I replace string1 with the user input, such as "The length of string 'Dog' is 3"?
num_of_items = int(input("How many ite... |
I was just wondering how secure my code looked and if I'm overlooking any serious mistakes. Any suggestions/critiques are welcome.
This is my relevant login script.
login.php
<?php
if (!isset($_POST['remember']) && isset($_POST['user'])) {
if (isset($_COOKIE['remember_me'])) {
$past = time() - 100;
... |
The problem can be found here and is essentially asking us to generate J many numbers containing N many digits, where these digits have to be either 0 or 1. The catch is that the these numbers that we generate have to be composite when interpreted as being written in base i, where i ranges from 2 to 10, inclusive. Furt... |
After A ton of work I finally have a working Tic Tac Toe game that I am very proud of, and it works great. I would like some feedback on anything that can be improved/ needs to be changed.
I had a problem implementing my header guards. After I finished everything, my IDE automatically sets up #pragma once. After frustr... |
I have a search function in my class which checks various class property values for null or certain values and queries the database based on those properties. This how my function looks like now:
public object searchCustomerList()
{
object partner = null;
try
{
using (var rep = ... |
I recently joined the tex community and had quite a fun week texing. (I migrated this question to codereview, as it seems to be the better place for code-review samples). The result is some layout/format I would like to use for future theses/small-books. I did host the the whole thing here, and as others might like to ... |
How can I make the saving to the dictionaries more efficient as well as making my overall code more efficient?
import random
import sys
import shelve
def get_input_or_quit(prompt, quit="Q"):
prompt += " (Press '{}' to exit) : ".format(quit)
val = input(prompt).strip()
if val.upper() == quit:
sys.ex... |
I wrote this algorithm to rotate elements in an array. It's not very efficient, but it works. It has another disadvantage that it doesn't rotate right (it would be nice to pass it negative steps, for example).
def rotate_left!(array, steps = 1)
for i in 0...steps
first = array[0]
for j in 1...array.size
... |
I have an ArrayList which contains Strings with a size of 1000. I am looping through that ArrayList and finding words and trying to form a square from them. For example as follows:
C A R D
A R E A
R E A R
D A R T
The square must match left to right and top to bottom. So first left to right word (card) must match firs... |
My application needs to implement authenticated encryption using C#. There is a .NET class called encryptAndAuthenticate, but it is only supported on windows 8 or later, and I need the code to also work on windows 7. I created a class for internal use in my app that uses the encrypt-then-authenticate model. I use AES ... |
Here is my code:
def winnerchecker():
def player1win():
print '\n' * 5, name, "YOU HAVE WON! GG TO", xplayer
time.sleep(3)
raise SystemExit()
try:
if "1,1" in turn1l and "1,2" in turn1l and "1,3"in turn1l:
player1win()
elif "1,1" in turn1l and "2,1" in turn1l... |
Series post - I am reading through Introduction to Algorithms, 3rd Edition implementing each algorithm as I read them.
Pretty basic insertion sort. Only considering numbers initially - how could I make this better and/or have better tests?
def insertion_sort(numbs):
for cur_index in range(1, len(numbs)):
c... |
After seeing Tic Tac Toe in MVC, I attempted to create something similar. My program uses the Swing library and it's relatively simple. When I run the game, it's just a 3x3 grid with no extra features.
Can anyone give me tips on how to improve my overall MVC design / code? I did a lot of reading, but I sure I don't ful... |
I have a function that pulls data from a file or string literal in my case and returns them in either a list or a dict.
My concerns
I'm not sure if a function should have two different return types.
I feel like I'm repeating myself a lot.
If it is ok to return two different datatypes, how do you document that in the d... |
This is my first ever program in my first language, Python. I wanted to know how I could improve my writing style.
#USER: TCG
#Noughts & Crosses
#Header
header = '''
------------------------------------------
| |
| KNOTS & CROSSES |
| ... |
I am writing a triple for loop in Python. Since the data set is larger, it takes more than 1.5 hours to finish. Is there any fast way to avoid the loop?
idx = []
for key, value in bid_img.iteritems():
for v in value:
loc = 0
for pid in pid_lst:
loc += 1
if v == pid:
... |
Within a method, this code is calling a SPROC that is doing a 'select *' from 9 different views. This method then goes on to access the returned DataTableCollection array by the index specified here (0-9). If the order of the stored procedure select statements ever changed, this would also need changing round here.
Thi... |
Given an array:
arr = [2,3,1,4]
I could write a count inversion array such that counting all numbers n2 after a certain number n1 in arr such that n1 > n2 and write it like this
[1 1 0 0]
Similarly, the inversion array of:
[2, 1, 4, 3]
would be:
[1, 0, 1, 0]
For:
[20]
[1, 2, 3, 4, 5, 6]
[87, 78, 16, 94]
Output wo... |
#
# Guess the presents someone will get
# We compare a `wishlist` with many criteria to the `presents` and return an array with the names of the matching products.
#
def guess_gifts(wishlist, presents)
wishlist.map do |w|
w[:name] if presents.include? w.reject { |key| key == :name }
end.compact.uniq
end
gue... |
Problem statement
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be \$\mathcal{O}(\log (m+n))\$.
Implementation
def median(A, B):
m, n = len(A), len(B)
if m > n:
A, B, m, n = B, A, n, m
if n ... |
I have written my first code of object oriented Python. Prior to this I have spent a week on learning the concepts and understanding the technique. I would appreciate it somebody reviews this and give suggestion on where I can improve.
I am working through codewars Kata and this code is for the problem. I am copying t... |
I have the following gulpfile which I use for development. It used to be a simple gulpfile with just jade compiling, sass, jekyll-rebuild, etc. but then I decided to add HTML Optimization my gulpfile became a little bit complicated.
The Gulpfile works okay but it has some bugs, for example when I save a jade file, I h... |
I have a file named feedback.js that I would like to improve.
function feedback(feedbackform) {
// collect the feedbackform data while iterating over the inputs
var data = {};
for (var i = 0; i < feedbackform.length; i++) {
var input = feedbackform[i];
if (input.name && input.value) {
... |
Starting to write an article about Socket Programing.
So I need a simple C version of a client/server app.
So here it is for review (Also on github)
A linked question is the C++ version
MakeFile
all: client server
.PHONY: all
.INTERMEDIATE: %.o
CFLAGS += -Wall -Wextra -Werror -pedantic
client: client.... |
Starting to write an article about Socket Programing.
So I need a simple C++ version of a client/server app.
So here it is for review (Also on github)
A linked question is the C version
Makefile
all: client server
.PHONY: all
.INTERMEDIATE: %.o
CC = $(CXX)
CXXFLAGS += -Wall -Wextra -Werror -p... |
I have a class that encapsulates a PowerShell Runspace object which, among many other things, has methods for getting and setting variables in the session state. There is no apparent mechanism for enumerating the variables, only get/set.
To simplify access to the variables from my code I've been using a specific index... |
I'm currently working on a thing I needed this feature for. Essentially, these are two methods to convert DateTime objects to and from the Unix epoch time (two methods for each action).
There is a non-nullable, and a nullable version for each conversion.
/// <summary>
/// Converts a DateTime to the long representation ... |
This is my new version of my Tic Tac Toe game written in C++. I tried to follow community advice by separating I/O from the game logic and view (MCV). The code works great, and I am looking to see if I followed the model control view design pattern correctly.
TicTacToe.h
#ifndef TICTACTOE
#define TICTACTOE
#include<st... |
Please tell me ways I can improve this code to be more efficient.
#Moving Character in 2D Plane
'''
Made by a beginner
'''
arena = [] # This is a map file
def make_board(place): #Generates map terrain
for i in range(5):
place.append(["O"] * 5)
def list_to_string(alist): #Makes map easier to read
for i... |
The problem:
We have a set of mobile mechanics who are assigned specific zip codes. Each zip code has its own hourly rate. We want to increase and decrease these rates when the number of idle mechanics within a zip code falls or goes above specific thresholds. This way we can proactively set the going rate for each mec... |
I have attempted to make conways game of life in Python, and then save the output into a picture.
Is there any way to make this more efficient?
Is there anything wrong with the logic? (Most of the pictures don't look quite correct)
Other?
import PIL.Image, random
WIDTH = 1366
HEIGHT = 768
ROUNDS = 10
DEAD = (0, 0, 0... |
The idea of my application is to have the user provides text which is pasted (or written) inside the textbook and further provides a search word.
The application then shows the overall count of words in the text, how many times the search word appears in the text, and the rate overall words to count of search word.
Any... |
My goal is to write a reasonably robust c++ linked list class. The current code represents the latest phase in this attempt. My future goal is to implement a doubly linked list along with more member functions. Before I continue further, I would like some input on my overall design thus far. Also, any input on improvin... |
I've written an ActiveAdmin mixin, such that you can include it and call simple_menu_for Foo, to reduce duplicate code when working with simple models. Here is the main part, which will connect all others. It works, but code looks little bit ugly. Maybe there is an alternative to using the class_variable_set method?
... |
I have code here which will change a sprite depending on the variables called gunUpgrade and moveUpgrade. Any way to make the code simpler or shorter? I'm using Unity 3D.
if (gunUpgrade > 0 && moveUpgrade > 0)
{
if (gunUpgrade == 1)
{
// For every moveupgrade, set the sprite to array num... |
The aim of this program is to say which position a word is in a list. This is just a basic version of it. I made to see if I could shorten it more than what it is currently.
position, word, word_list = 0, 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'
word_list = word_list.split("... |
I am new to AngularJS. Here is my basic code for implementing Tabs with Pane. Eventually, each tab-pane will have a form and a ui-grid that will display data from the DB.
Can I use separate controllers to initialize each tab to load the pane?
Is it good to give separate controllers for implementing a pane? I have DB... |
I'm solving the "Balanced Parenthesis" problem in Ruby, and I came up with this solution.
def balanced?(string)
return false if string.length.odd?
pairs = { '{' => '}', '[' => ']', '(' => ')' }
string.chars.each_with_object([]) do |bracket, stack|
if pairs.keys.include?(bracket)
stack << bracket
e... |
I have a method in Scala that checks if a game board is full or not. To speed this method up, I return inside the nested for loop to break out of both of them and stop execution. How would I achieve this in Scala in an idiomatic way?
def isFull: Boolean = {
for (x <- getGrid.indices) {
for (y <- getGrid(x).indice... |
I'm currently writing a binary reader that reads a value from a BinaryReader at a given position. For that I have to store the current position of the MemoryStream so I can restore it afterwards.
public byte GetByte(int position)
{
long oldPosition = this.memoryStream.Position;
this.memoryStream.Position = positi... |
Part of a project I'm getting started on requires access to the Stack Exchange API for certain data, as a result I built a .NET implementation to interact with it.
The implementation is pretty simple, in my opinion. You can also find it on GitHub.
It features a main Configuration class, in which you put a lot of the A... |
I wanted to write a function paths that returns the possible routes between two nodes in a graph.
For example:
const graph = [
['a', 'b'], // i.e. directed edge a => b
['a', 'c'], // i.e. directed edge a => c
['b', 'a'], // i.e. directed edge b => a
['b', 'c'], // ...and so on
['c', 'a'],
... |
Given any string with a series of numbers find out which one of the numbers differs from the others in evenness and return its position.
Examples:
"2 4 6 7 8 10" returns 4
"3 5 7 9 10" returns 5
I found 2 different ways to do so, but I'm wondering what is the best approach in matter of time complexity.
Solution 1
d... |
I'm a beginner-intermediate programmer who's mostly used Java. I taught myself Python and made this engine for playing Reversi. Tips on Pythonic ways to accomplish tasks and/or general advice appreciated!
from ast import literal_eval as eval
board_size = 8
BLACK = '\u26AB'
WHITE = '\u26AA'
EMPTY = '\u2B1c'
offsets = (... |
I have a function where I am comparing an error string returned from a web service to several lists of known strings, and then based on which list the error is a member of, returning from the function a more 'user-friendly' error to display.
I am hoping someone could offer some tips on making it shorter and more effici... |
I'd like some feedback.
from random import randint
turns = 1
computer_guess = randint(1, 10)
while True:
user_guess = raw_input("Guess Number: ")
print 4-turns, "Turns left"
if turns == 4:
print "You lost!, LOOSER!"
exit()
else:
if int(user_guess) == int(computer_guess):
... |
I needed to rotate a non-square matrix in my program to transpose some spreadsheet data and decided to make a function to rotate 90, 180, or 270 degrees.
It doesn't rotate the matrix in place, but instead generates a copy and returns that. I want to go for processing efficiency, let me know what I can do better:
//Rota... |
I have written a simple implementation of the game Tic-Tac-Toe designed to allow "pluggable" player control, meaning I can easily swap out the controlling logic for players without modifying the game itself.
I have a few issues with my existing code:
I don't like the while loop for processing, however I find making mo... |
General objective: Find the date (day of the month) of the nearest specified day of the week and output.
More specifically: Focusing on events which take place every Fri & Sat, want the page to automatically update dates to next events. HOWEVER for clarity the page should never display Fridays and Saturdays which are N... |
I tried to implement a linked list that can do pop(), push(), append(), printall(), and so on, and also I tried to handle the wraparound features, and de-wrap it when check if the list is cyclic to avoid endless loop, but I am sure this wrap and de-wrap features can be implemented better...
#include <iostream>
struct ... |
Here is an async Tcp server using async/await I have written. I would be very appreciate if anyone can help to improve my code. Thank you!
public class TcpServer
{
private int DefaultPort = 6340;
public TcpListener TcpListener { get; set; }
public TcpServer()
{
var ip = NetworkHelper.GetLocalIP... |
Algorithm which returns a number which is divisible by all the numbers from \$1\$ to \$n\$ without remainders.
public static void smallestMultiple(long l){
int count = 1;
boolean flag = true;
while(true){
flag = true;
for(int i=1; i<=l; i++){
if( count % i != 0){
... |
ActiveWindow is like the main container and below the subviews. Router trigger activewindow.render(options) then the switch operates. Is it fine to do that Or how bad is it?
define('activewindowView', [
'backbone',
'text!views/activewindowView/activewindowTemplate.html',
'ghostviewHunter',
'menuView',
... |
Let \$I = \{ i_1, i_2, \dots, i_d \}\$ be the set of all possible items, and \$T = \{ t_1, t_2, \dots, t_N \}\$ be the (multi)set of all given transactions, where \$t_i \subseteq I\$ for all \$i \in \{ 1, 2, \dots, N \}\$. We call any such \$t_i\$ an itemset. Given an itemset \$X \subseteq I\$, its support count is
$$
... |
So I made a version for the 0/1 knapsack problem myself (using matrix dynamic programming algorithm). Given a list of items with name, value, and weight, my function computes correctly the optimal value with total weight <= allowed weight.
I don't know if my code is clean and pythonic enough, I would greatly appreciate... |
This is a silly Redis implementation that handles only three commands: INFO, ECHO, PING.
The implementation is based on streams:
var _ = require('lodash')
var expect = require('chai').expect;
var assert = require('chai').assert;
var redis = require('redis')
var split = require('split')
var net = require('net');
var ut... |
A long long time ago I asked this question which has since garnered about one thousand views. Now for something new.
The demo for what I have is located here. I am generally happy with what I have built (although I did not implement all of the visuals (yet) of the original).
I want to know if there is some improvements... |
Is there a better, more efficient or nicer way to do this?
public static String sortString(String s){
String[] strArray= s.split("\\s+");
Arrays.sort(strArray);
StringBuilder sb = new StringBuilder();
for (int i=0; i<strArray.length; i++){
sb.append(strArray[i]);
sb.append(" ");
}
... |
Already many days I'm documenting about the SQL Injection. I was wondering if the code I wrote is vulnerable in some of its parts.
<?php
if($_POST['nameone'] AND $_POST['nametwo'])
{
$conn = new PDO("mysql:host=localhost;dbname=dbname;charset=utf8", 'dbuser', 'dbpass');
mysql_query('SET NAMES utf8');
$conn->se... |
This code works just fine as I get the correct output. However I want to make my code more simple. I want to avoid using the setPrev(Node n) method and would rather set the reference to the previous node in the Node(String s) constructor directly somehow. I mainly want to know if this is the 'right' way to implement a ... |
I am almost finished with my queries which are running inside transactions so it's everything or nothing... Could you please take a look if I am missing something or if everything is where it belongs?
I am bit worried about my conn.Open() call, and about security in general. Can you help me out to tune it up and make i... |
So this is my full script that I've been working on. My plan is to Create New, Folder, Create AD Group FS-TESTSHARE-R, Create AD Group FS-TESTSHARE-RW, Apply Both groups to the new share folder, Set Full Read permissions to FS-TESTSHARE-R, Set Full Read/Rights permissions to FS-TESTSHARE-RW, and Set full access permiss... |
(See the next iteration.)
I have this funky class method for computing standard deviation from an array of Number objects using the Stream API:
StandardDeviation.java:
package net.coderodde.util;
import java.util.Arrays;
public class StandardDeviation {
public static double computeStandardDeviation(Number... col... |
I'm new to programming, Stack Overflow and Code Review. I was encouraged to post this method here based on a question I posted on StackOverflow here. Let me know if you have tips for improving this post, and I will try to implement them asap.
I'm hoping for a general review of my code. I realize the formatting is go... |
I already solved this one from CodingBat, but I'm unsatisfied with my solution and I feel I could have made it much shorter. Most of the other recursion tasks could be solved by a one line conditional for the base case and a one line return statement usually using ternary operator. So, could I have made this any shorte... |
I create a constant class by looking at some of the best practices described here in stackoverflow. Many of those have a single Constant class with variables. Some of the answers suggested creating separate Contant Classes. The way I create a constant class is by naming it Parameters and creating classes i.e. Variables... |
This 5 classes: CBoard, CInput, CPlayer, Console, Graphics, and the main file, Test, which is actually main.cpp (but I named it poorly). Specifically, I use a switch to update the board, which is a 2D char array.
Is there a better way to update the board besides a large switch case? I have yet to think of a way to hold... |
I am wondering whether the following inheritance pattern is a good idea.
I noticed that Sales Orders, Sales Quotes and Sales Invoices all follow a similar Master/ Detail pattern ( i.e a Header with Lines ) so I wanted to be able to inherit from base classes that encapsulated their common properties.
I will start with m... |
A followup to this question, thanks to @mdfst13 and @janos for the feedback.
I have made some changes to my code, mainly the following:
Replaced the next method with a loop and run method, as suggested by @mdfst13. Also removed redundant "null" checks.
Added a Cell enum as suggested by @janos, replacing the 2D array ... |
This is my first stab at a game AI, and I've been working on multiple game mode difficulties, so I decided to start with a simple game. :) I'm most concerned about efficiency of the AI algorithms, and any possible way of reducing the duplicate code. I know I can't change the int values by reference, so would it be more... |
I need to speed up this code so it can handle inputs in the thousands. It adds triangular numbers to a list based on input n, then it loops through to find if any two consecutive numbers squared in that list add up to n. The test cases I've been using are n = 45, which would be true and n = 6, which would be false.
He... |
I'm trying to code this decision tree using R. I was wondering if there was a better way to go about this rather than using a ton of conditionals?
# ops
rm(list=ls(all=TRUE))
options(warn=-1)
saveFiles = FALSE
setwd("~/Documents/Education/UCLA/Spring 2016/MGMT271B/proj/")
# data vars
n = 10
T = c("X", seq(0,4), "is") ... |
My code fetches telegrams from a server periodically in the background. The server API is documented here. What do you think of the way I do multithreading by handling my _updatesList?
public class AutoUpdate
{
public bool IsStarted { get; private set; }
private readonly Timer _timer;
private readonly List... |
I just wrote a small Ruby class to solve the first of the challenges in the G CodeJam. I am not strong at this sort thing so very sure it can be simplified massively! The program is correct for both the small and large inputs.
Challenge
Problem
Bleatrix Trotter the sheep has devised a strategy that helps her fall
as... |
I created a method that takes a string value with a fixed length of 9 characters and extracts three values, house (4 characters), level (2), door (3). If the input value has another length than 9 then the method should return nil.
I found several ways to implement the method, but which implementation should I prefer an... |
I'm a beginner at C#. I just want to know what is the C# way to do this by its convention and a better algorithm as well.
using System;
using System.Collections.Generic;
public class Program
{
static public void Main()
{
bool prime = false;
List<int> non_primes = new List<int>();
while... |
I have an object of arbitrary depth, and a string (or array) containing the keys which have to be traversed to get to the value.
As far as I know, there's no method to get to the value directly:
var object = {
user: {name: 'bob'},
'user.name': 'error'
};
object['user.name']; // contains 'error'
And the usua... |
I am trying to count the rows of two tables generated by SQL connections in Excel VBA. My plan was to use ListObject.DataBodyRange.Rows.Count however, this errors when a table is empty, which one often is. I found it completely impossible to use On Error GoTo ... twice within one sub so I pulled out the counts as funct... |
We have the following validation function:
var result = scope.CurrentUser.Surname.length > 0;
var d = $q.defer();
if (result) {
apiService.UniqueEmailCheck(scope.CurrentUser.PersonId, scope.CurrentUser.Email)
.success(function (response) {
if (response) {
... |
The code is working fine however, I would like to fix code after unless and can I store thread ID in the database too? Is there a way to improve performance?
require 'csv'
class CsvDb
class << self
def convert_save(model_name, csv_data, field_name=nil)
target_model = model_name.classify.cons... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.