instruction stringlengths 71 95.1k |
|---|
I decided to try my hand at making an encryption utility, which I lovingly call "FileScrambler". FileScrambler allows the user to encrypt a file (a master-password list, personal diary, or whatever) using a password, and save the resulting jumbled mess to their computer (same folder as the executable is located). They ... |
I have a query below using CTE. I am wondering if there are some approach other than this. So I am collecting some advise to refactor it. Or does the query look good even though I am using this IN (SELECT InvariantLanguageCultureCode FROM y) statement many times in the query?
DECLARE @ReportingInstanceID INT
SET @Re... |
Having developed a page in HTML4 I'm looking to improve my page by developing it in HTML5 and specifically looking to use the header, nav, section, article, aside and footer elments.
I realise its a judgement call to apply the above elements and I've applied some of these HTML element plus I look forward to using more ... |
I have written a recursive method for a partition sort that sorts the array. However, when I use an array of more than 10-20 elements the program takes a really long time to complete. (On my computer a bubble sort of a 100,000 int array will take about 15-20 seconds, but with an array of only 30 ints my partition sort ... |
This question is related to another one that I have asked here.
I need to find ways to improve the runtime performance of the following piece of C-code.
I want to increase RANGE to around 1G, and still complete the execution within a reasonable time.
Auxiliary data structures:
#define RANGE 16000000
uint08 sieve[RANG... |
After years of fear and procrastination I decided to learn regular expressions. This is the result:
CoffeScript:
str = "<h2><a name=\"#{chapter._id}\">#{chapter.title}</a></h2>\n\n#{chapter.content}\n\n"
str.replace(/>([^>]+)</g, (r) ->
r.replace(/(>|\s)"/g, "$1“")
.replace(/"/g, "”")
.replace(/("|\s)'/g, "$1‘... |
The sum of the squares of the first ten natural numbers is:
\$1^2 + 2^2 + ... + 10^2 = 385\$
The square of the sum of the first ten natural numbers is:
\$(1 + 2 + ... + 10)^2 = 55^2 = 3025\$
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is \$3025 − 385... |
I came across this excellent post on delegates and event and tried to adapt it to C# 5.0L
namespace Bla
{
public delegate void WorkStarted();
public delegate void WorkProgressing();
public delegate Task<int> WorkCompleted();
public class Worker
{
public event WorkStarted Started;
pu... |
I've got a bit of code that I'm wanting to tidy up. The aim is to take a String that consists of multiple words connected by a separator (It's produced using Collectors.joining(SEPARATOR) as below, although the stream processing is not quite so trivial), and return a portion from the front of it.
This portion should ne... |
I have this method that returns true if attribute is already used and false otherwise:
public boolean alreadyUsed(Node node, int attribute)
{
if (node.parent == null)
{
return false;
}
if (node.children != null)
{
if (node.splitAttribute == attribute )
{
retur... |
I made my first program that I might actually use and I was wondering if anyone had some tips on how I could improve it.
My code is an auto-clicker that uses Python3 ctypes for the clicking and Tkinter for the GUI. I made this in 2 hours so there might be a lot of optimization I could do.
from tkinter import *
from tki... |
I have function that I need to run on window load as well as window resize and I was wondering
how can I make my code more efficient.
Here is my current code:
jQuery(window).resize(homeSliderAdjust);
var windowWidth = jQuery(window).width();
if (windowWidth < 750) {
var hmLeft = jQuery('.page-home #slides .lef... |
I wanted to store CMTimeRange structures inside managed objects, so I've worked out the following:
@interface Clip : NSManagedObject
@property (nonatomic, retain) NSData * primitiveRange;
@property CMTimeRange range;
@end
Within the data model editor I've set the type of primitiveRange to "Transformable".
The implem... |
I use this code in a GAS (Google Apps Script) to automate my project budgets.
Since every project has its own spreadsheet but all functions are in the same script file, being called as a library, I can't use them directly. I need to call libraryName.functionName, but it can't serve any arguments unless I do this:
func... |
Well, quite a biggie with all the foreach's. It works, it gets me 981 results, but there must be a way to shorten this code. Right?
<?php
$class = new FTPcleanup();
echo $class->index();
class FTPcleanup {
private $server = "1.1.1.1";
private $user = "ftpuser";
private $passwd = "ftppassword";
pri... |
This code is part of a data model used to create keyword records in a database.
if (_queue
.OrderByDescending(record=>record.Primary)
.GroupBy(record=>record.Term)
.Select(record=>record.First())
.Select(Create)
.Any(result=>result <= 0))
{
throw new ModelException("Failed to create keyword reco... |
I need to extract all numbers before a colon in a string, e.g.:
abc1234:blah -> 1234
5n63:124 -> 63
stringwithnocolon -> ""
stringwith:nonumber -> ""
Limitations:
no external dependency (looking forward to keep it simple)
no << operator allowed
not C++11
Here is the code I came up with:
const std::string DNAStorage... |
I am trying to implement a live chat for my websites visitors. I am currently using a PHP script that processes in background and that is called by AJAX. I am not familiar with sockets and node.js that also allow to create a live chat so I tried to make one longpolling-like code upon my possibilities. What I am hoping ... |
I was playing around with some code trying to implement a sorting algorithm in C++ that also works with singly linked lists. Since the merge routine of mergesort only scans forward, implementing a generic mergesort seemed like the way to go.
In C, I would have implemented it as follows:
typedef struct node {
int val... |
Can anyone help me optimise this query? I have the following table:
cdu_user_progress:
--------------------------------------------------------------
|id |uid |lesson_id |game_id |date |score |
--------------------------------------------------------------
For each user, I'm trying to obtain the di... |
I'm trying to pick Scala up. This is a simple heuristic that checks a similarity value between two sets. I've done this a million times in Java or Python. The function works, but I'm certain I am not doing this "the Scala way".
val a : List[Int] = List(1,1,2,2,3)
val b : List[Int] = List(1,2,3,4,5)
def calculateBags(a... |
The following code is designed to accept a string from the user that is at most 5 characters long. It will then find each possible substring of the string and print all possible permutations of each substring.
This is the first time I've done my utmost to prevent memory leaks by freeing every malloc. Even Valgrind see... |
I wrote some code a few weeks ago, to take a string similar to
seq[]=8&seq[]=7&seq[]=5&seq[]=1&seq[]=4&seq[]=3&seq[]=6&seq[]=0&seq[]=2
and put it into a gallery, to be ordered by jQuery UI's Sortable, which works all good, however, I'm concerned about the amount of times I .Replace the values in the string.
This code... |
I've read other solutions about solving the 10th problem for Project Euler (finding the sum of all prime numbers under 2,000,000) but I wanted to try it on my own using the Sieve of Eratosthenes method. It runs quickly and it seems to work for all of my test increments (under 10, first 1000 primes) but it doesn't seem ... |
In of my software engineering classes, I had to write a truth table calculator in the language of my choice. This is what I came up with, and I would like to know what I should do better next time:
import copy
import sys
print("This program reads boolean equations and outputs the truth table.")
print("You may use the... |
I am trying to implement a singleton builder that would be shared across
multiple builder threads for Coordinate objects.
Here is the simplified target class Coordinate with only two Integer fields.
public class Coordinate
{
private final Integer x;
private final Integer y;
private Coordinate(CoordinateBui... |
I've written code to check whether a domain resolves DNS or not like follows. It is working fine, but I doubt whether there is a simple way to check this by using `dns_get_record'
$url = 'http://www.example.com';
$get = get_headers($url); //Fetches all the headers sent by the server in response to a HTTP request
if (pr... |
I am working on a small and self-contained poll application, not unlike Straw Poll whereby one user can submit a poll and other users can vote (but only once).
I am building this little application in the open, using Angular for the front-end and Web Api for the back-end. I am using Fluent Validation to validate incom... |
I had been working on several projects that required Header Message Authentication Codes to be generated when brokering files with 3rd parties like Netflix.
Unfortunately on older systems like Windows Server 2003, Solaris and early versions of RHEL there was no easy way to generate HMACs which could be Base encoded.
So... |
I'm trying to implement a RawString class that conforms to C++11:
#include <iostream>
#include <string>
#include <memory>
class RawString
{
private:
char* buff_;
public:
RawString()
{
std::cout << "rawstring def ctor\n";
buff_ = nullptr;
}
~RawStr... |
In my company's code, they use double.tryParse() which is quite good but sets too much security for our needs. As we sometimes have to parse a few billion strings, I came up with this code which is a little bit faster (10%) but I have the feeling that it's not at its best... Unfortunately, this kind of stuff require mo... |
This is my code, for calculating a GPA for 7 subjects. It works, but is there a better way? Any hints on making it more flexible?
from __future__ import division
import string
print "This program will calculate a Semester GPA for a given set of courses. Enter 0 in all inputs, if you want to skip extra courses.\n"
... |
As @rolfl recently solved the N-Queens problem, I figured that it was time also for me to solve it.
My approach is significantly different from @rolfl's. I quickly realized that the N-Queens problem is just another Constraint Satisfaction Problem (CSP). Earlier, I have written a whole bunch of code for solving Mineswee... |
I am a Java beginner and have made a simple Compare Game. It has done well but I am not sure about my solution, especially about my thread. Can you give some advice on making it better?
public class CompareGame {
static short first=0;
static short second=0;
static JLabel lblFirst = new JLabel("First");
... |
Java 8 streams are my new golden hammer that I try to use as often as possible with often enormous gains in brevity and readability. Getting multiple return values, such as a maximum value and its associated element, is a bit cumbersome though (and requires an additional "pair" class).
Should I go back to "normal Java"... |
I have created a small script that:
Creates a lot of random points.
Runs a small brute force search to find a rect that has a low error, that is a good fit for the data.
Runs a linear regression on the rect generated with brute force to further reduce the error.
Prints out information and plots the data.
Down here yo... |
I have taken the following design from a tutorial done in 2006, and have decided to markup it up in HTML5. The design is as follows:
My markup is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Enlighten Designs - About</title>
<link rel="stylesheet" href="style.css">
</he... |
Here is my code for "Reverse Binary Numbers" in C.
Problem
Your task will be to write a program for reversing numbers in binary.
For instance, the binary representation of 13 is 1101, and reversing
it gives 1011, which corresponds to number 11.
Input
The input contains a single line with an integer \$N\$, (where
... |
The other day I was asked the following question during an interview:
Given a sorted array, how would you square each element of this array, while keeping it sorted?
I froze up and wrote a horribly inefficient solution I've included below. Basically, I iterate through the original array, squaring each element, and th... |
I have read some articles regarding the factory pattern and decided to write some code as an exercise. This is my first attempt and am not 100% if I did it right. I've omitted some implementations for the sake of focusing on the concept at hand.
class NumbersFactory {
public static function makeNumber( $type, $numb... |
Below is the code for stack along with one or two extra options. Kindly let me know if there are any concerns/critical issues. Below are the two link for previous versions.
Original
Version 1.1
//*************Version 1.2: Begineer's Implementation of Stack ***************//
#include <iostream>
#include <fstream>
tem... |
I just started learning Go. To start playing with it, I've implemented the fast power algorithm:
Any suggestions or criticisms regarding the coding style?
package main
import (
"errors"
"fmt"
"math"
)
func main() {
result, ok := fast_power(2, 4)
if ok != nil {
fmt.Println("Something went ... |
Here is my code for importing from a .csv to a neo4j graph using py2neo and cypher statements. I've noticed that it slows down significantly the bigger the graph gets. It takes several seconds just to parse ~10,000 lines. I'm curious to see if there are any glaring mistakes or improvements to be made.
Before doing any... |
I'm applying fallbacks to rem values only if required (you know, the whole progressive enhancement train), without conditional comments (because it's not just an IE issue) and without additional lines of CSS for fallbacks all over the place. I'm just checking for the edge cases (userAgent) and adding a stylesheet into ... |
I've written a web application that is a replica of the iPhone's notes app. It turned out quite well, you can do everything you can on the iPhone's app except for sharing and sending it via texts etc. I've been sitting here trying to figure out a way to DRY this up, so far I think I've done a pretty good job in doing s... |
This is code for a class that takes available ingredients and returns left over ingredients after making a dish.
Cesars: 2 carrot 4 ice burg 1 chicken 1 beans
Russian: 2 carrots 2 beans 2 chicken
If carrot is not there - 1 bean or 2 iceberg can replace if beans is not there - 1 iceberg can replace if chicken is not t... |
I'm working on simple code that is to read input where:
The first line is a number of cases to consider.
The next lines are integers separated by a space that will be tested lately.
Possible input:
2
3 4
4 5
Possible output (just some multiplication example):
12
20
Questions:
I would like to know if there are 'bet... |
Is there anything I can improve? The distance function is Pearson correlation.
import os
import pandas as pd
import numpy as np
from pandas import Series, DataFrame
def corrpairs(df1, df2):
"""
Pairwise correlation for columns of two data frames
:param df1:
:type df1:
:param df2:
:type df2:
... |
I was working on a suggestion for this question, but the method, I would've suggested the OP do something similar to, seems a bit convoluted.
It's supposed to take a String input and return an array of only the integers deliminated by spaces. It does this correctly, but It feels like I may be doing some unnecessary thi... |
This code checks a string called breakfastHours similar to
1567
which translates to Monday, Friday, Saturday, Sunday.
1 = Monday
2 = Tuesday
....
7 = Sunday
The user then checks the boxes for the days they visited the club, which is all handled within jQuery later on, with the chkB{0} tags.
#region BuildOpeningHou... |
I'm trying to solve the Oil Well problem on Hackerrank using dynamic programming and it works. However, it times out for some of the test cases. I wanted to know how this program can be improved so that it runs faster.
The challenge is, given a matrix \$M\$ of size \$r \times c\$ (at most \$50 \times 50\$), where each ... |
I wrote an AngularJS wrapper for p5.js called angular-p5:
angular.module('angular-p5', [])
.service('p5', ['$window', function($window) {
return $window.p5;
}])
.directive('p5', ['p5', function(p5) {
return {
restrict: 'EA',
scope: {
sketch: '='
},
link: function(scope, element, attrs) {
... |
I have created the following class to read Serializable object from file and write to a file.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
im... |
In my program, I display the compilation time which is calculated from the AssemblyVersion attribute. The attribute is set to automatically generate a version number (with asterisk).
As you know probably, the build is equal to the number of days since January 1, 2000 (local time), and revision is equal to the number of... |
I have two kendoGrid(s) named:
var sourcegrid = $('#usersGrid').data("kendoGrid"); //SOURCE GRID
var destinationgrid = $('#teamGrid').data('kendoGrid'); //DESTINATION GRID
In sourcegrid, I have 1000 records and in destinationgrid has no records.
I have a button that transfers data from sourcegrid to destinat... |
This has been written for network engineers to be able to create an Excel inventory of switch/router device info from a folder of 'Show version' .txt files. I've put it here to help me learn about Python and how I could potentially improve my coding, so please, feel free to rip into this and criticise!
#!/usr/bin/env ... |
I have a method that takes a model object, reads through its children and returns a hash of status counts. It should only return a count on a status if one exists.
This method works, but I was wondering if there are a cleaner, more Rubyish way to write it.
The batch_details table is getting very large, so if possible ... |
How is my usage of std::unique_ptr() and std::move()? How can I improve this code?
//I don't know what to return when key is not found, so throw std::runtime_error()
//this code does not have handwritten copy/move/destruct because I think unique_ptr already handled the node pointers
template<typename T>
using Ptr = std... |
I am using the code below that loops around thousands of time, I need this to be as fast as possible, however I am not an expert in Javascript and all I know is that this code is faster than doing it with the innerHTML method.
Can it be optimized? If so, how?
var a,b,c,d,e,
trEl, tdEl, imgEl
for (i = 0; i ... |
I'm trying to break up some procedural JavaScript code used for running an automation test.
The code is a series of steps that execute selenium webdriver commands within the neustar load testing framework. The framework is not too important for the purposes of this review, except to know this code is not run in a brow... |
I wrote a simple 8-Puzzle and solver and am interested in seeing how it might be improved. Please let me know if any style or design changes might enhance the readability/performance of my code.
import random
import itertools
import collections
class Node:
"""
A class representing an Solver node
- 'puzzle'... |
This is an attempt at the Factory Method Pattern
It emulates the logical model
and also the physical model
Resources:
http://en.wikipedia.org/wiki/Factory_method_pattern
http://msdn.microsoft.com/en-us/library/ee817667.aspx
http://www.oodesign.com/factory-pattern.html
Is this a correct implementation of the Factory ... |
I am wondering what is the best way to map array values to properties in a class. Consider the following sample array describing information for an airport:
[0] "6523" string
[1] "00A" string
[2] "heliport" string
[3] "Total Rf Heliport" string
[4] "40.07080078125" string
... |
This is an Observable class similar to java.util.Observable. The difference is that it uses generics to avoid casts. The question is: Is it really worth the effort? What are the problems with this code?
import java.util.ArrayList;
import java.util.Collection;
/**
* like java.util.Observable, But uses generics to avoi... |
Let me know if it seems right to you and if anything can be optimized.
/*
* Doubly Linked List
*
* Each node of the list contain two references (or links) – one to the previous node and other to the next node.
* The previous link of the first node and the next link of the last node points to NULL.
* In comparison... |
How can I make this code shorter?
function tblcheckboxes(){
var a= 0;
var b= 0;
var c= 0;
var d= 0;
var e= 0;
var f= 0;
var g= 0;
if ($('#tcbx1').is(":checked")) {
a = parseFloat($("#tcbx1").val(), 10);
}
if ($('#tcbx2').is(":checked")) {
b = parseFloat($("#tcb... |
A couple of months ago I posted a bash script to manage multiple Git identities as a solution on Stack Overflow but soon found the hook isn't flexible enough.
Thus I decided to rewrite the hook in Python. Basically it does what it should but I'd really like to have someone review the code in order to eliminate bad prac... |
I am interested in getting some feedback on the code for my TicTacToe game, implemented with AngularJS, particularly with respect to the AI logic, which is printed below. (The full code base is available on GitHub.)
I welcome any suggestions for improving the overall code quality, whether that's identifying places wher... |
Would appreciate a review on this. The program does work as it is intended to. However I am unsure if there is a more elegant or better way to execute this process with less code.
def main():
print ('This program takes two numbers and multiplies them.')
print ('the result is multiplied by a third number')
... |
I have read so many bed time stories and ins and outs of how delegates work and why events are to be replaced with delegates (surely not all the time) and just couldn't get my head around it.
I am trying to use delegates in a more functional way in my code rather than practice runs in the LinqPad with dummy examples a... |
I have a logging solution that writes down the hashes of messages. I consider some of these hashes to be safe and I want to skip logging those. I have implemented a whitelist that is a directory containing whitelisted hashes. There is a timer task that updates that list every 10 minutes.
I have tried testing it from mu... |
Here is piece of code with few if ... else, I appreciate if anyone can clean it.
def process_link(post_script_link_list,read_str):
links_list1 = ['Wq','Ws','Wi','Wd']
bad_list = ['How long','how long','How much','how much']
links_list2 = ['Qd']
result = ''
for item in bad_list:
if item in re... |
This 2-player tic-tac-toe game is the first thing I've really written from scratch in Ruby, without the guidance of a tutorial. I'm interested in knowing what could be improved upon to make the code better.
Please point out anything you see that deviates from common Ruby conventions, or that would improve the code in a... |
I've got the following PHP code, which is taking a search term, and checking if any of the search terms could be or could have a nickname.
$search = $_GET['search-term'];
$indiviudal_terms = explode(" ",$search);
foreach($indiviudal_terms as $term) {
foreach ($nicknames as $nameset) {//$nicknames is a multidimensio... |
I'd like to share my implementation to you to confirm if it's a correct way to solve my problem. I have a list of products which have an attributes table and a description table (both in html_encoded strings). Every product starts at a new print-page using page break. When the attributes and description tables don't fi... |
Challenge: 2520 is the smallest number divisible by 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by 1-20?
Solution:
public class Euler5 {
public static void main(String[] args) {
long startTime = System.nanoTime();
int result = 0;
for (int i =... |
I wanted to test the performance of concurrent http request in Go against node.js:
package main
import (
"fmt"
"time"
"strconv"
"net/http"
)
var responseCounter = 0
var requestCounter = 0
var count=0
var ch = make(chan int)
func sendRequest(){
go func() {
requestCounter++
url := "https://... |
I've written a solution for http://tour.golang.org/concurrency/8, which asks for a Walk() function to traverse a randomly generated binary tree, and a Same() function to check if two trees have the same values.
Is this solution is the most efficient? (I think that the Same function is not the most efficient solution, b... |
I tried to swap 2 integer numbers without using an additional variable as a traditional swap.
Is it legal in C++? My VC compiler doesn't complain nor gives any warning about it. If so, how can I improve this script?
#include <iostream>
int main()
{
int a = 20;
int b = 66;
// before swapping
std::cout ... |
I'm interested in whether there is a way to further improve a "fast" version of a function used in a homework assignment I received recently (I've already submitted the completed work).
from math import log
def func_fast(mass, density):
return sum(map((log(mass * density)).__truediv__, range(1,10001)))
def func_s... |
For the last few days I have been working on wave generation script. As there are a lot of calculations involved I was looking for possible optimizations to improve the performance of the code.
This specifically applies to the update function, as most of the calculations are done in here. As the full code is quite lar... |
Is it possible to shorten the Isnull checking?
It would be great to shorten this code and only have to put the datarow once.
This code imports data details (usually there would be more .x = IIF.... statements)
Public Class apPropertyFunctions
Public Function GetProperty(ByVal sUPRN As String) As apProperty
... |
I have a function fib2 which returning two values as Tuple but I want to print the product of tuples returned by function fib2. I am new to Haskell so please explain it to me in a simple way.
This problem is from SPOJ which I have already solved using C and again I am trying it in Haskell:
For each \$n\$, find \$G(n) ... |
Here is a zero pad function I have:
''' <summary>
''' Take a number string and zero pad it to the specified length.
''' </summary>
''' <param name="Number">The string representation of the value that will be zero-padded.</param>
''' <param name="ToLength">The length of the string that will result after the zero-padding... |
I'm a total newbie at parsing, so I figured I'd start by writing instances of Read for HList, which does not currently have them. I'd appreciate some feedback on the following:
{-# LANGUAGE
DataKinds
,KindSignatures
,FlexibleContexts
,FlexibleInstances
,TypeOperators
,GADTs
,ScopedTypeVariables
#-}
module MyH... |
I'm actually spending time on it, unlike the first time and going through, understanding and implementing the several suggestions I've landed on two different approaches.
Approach 1: Employing Java 8 Lambdas and stream functions made to be the equivalent of David Zheng's answer in Python.
import java.util.ArrayList;
p... |
Here is the link to the problem: Aladin on Kattis.com
Problem
Aladin was walking down the path one day when he found the strangest
thing: N empty boxes right next to a weird alien machine. After a bit
of fumbling around he got the machine to do something. The machine now
accepts 4 integers \$L\$, \$R\$, \$A\$ an... |
Let me know if it seems right to you and if anything can be optimized. My concern is that I'm unsure if circular linked lists are supposed to have a tail. I've implemented it just using a head. Is that wrong? If so, how would you change it to make it proper?
/*
* Circular Linked List
*
*/
#include <stdio.h>
#inclu... |
I am trying to write a script that will traverse through my directory and sub directory and list the number of files in a specific size.
For example, 0kb-1kb: 3, 1kb-4kb:4, 4-16KB: 4, 16kb-64-kb:11. This goes on in multiples of 4.
I am able to get the list of file numbers, the size in human readable format and find the... |
I'm new to JavaScript, and decided to learn the language by running through as many of the Project Euler problems as I have time to do. I just finished the first one, and am looking for some feedback, specifically on language specific features I could use to do this faster, and faster performance overall (it seems to r... |
This is the follow-up question from here.
This is an Observable class similar to java.util.Observable. The difference is that it uses generics to avoid casts.
There are two questions:
Is it really worth the effort? or it's just making things more complex than needed?
Should this class be declared final, or is it ok to... |
I wrote the script below to load data obtained from the twitter JSON archive on archive.org into a PostgreSQL database.
I'm looking for optimizations in the code. It currently runs at ~1.7 seconds per file (of 50,000 files), or loads 3 million rows in an hour.
Would I be looking at multithreading? The first run took ap... |
Is this the best way to remove URL parameters from a string containing an URL?
$url = "http://www.test.com/test.html?parameter=hey¶meter2=ho";
if (strstr($url, "?")) {
$url = strstr($url, "?", true);
}
Is there a better one-line solution? It seems so bad to run the same function twice.
|
The below script is one I made to check the disk space on mounted partitions under Debian Wheezy. I tried adding a -d switch to force printing out the used data, but its main purpose is to run as a cron job, and email the administrator if any disks are below a certain threshold.
What I'm looking for is to make sure it'... |
I've spent a few days working on the animations for my Bejeweled clone and I am pretty happy with the results so I am posting the code for review. This is the most advanced animation code that I have written so far, so there are probably problems with it. Here is a gif of the animation running :
I encountered two maj... |
I am a beginner in C# coding, and I was trying to compare two int variables:
void CompareNumber() {
int oneNumber;
int secondNumber;
if (oneNumber > secondNumber)
{
DoSomething();
}
else if (oneNumber < secondnumber)
{
DoSomethingElse();
}
else if ... |
I think the snippet is too nested having too many blocks. It needs to be refactored to make the logic more readable.
The try exception is the first level block
Timeout::timeout is the next level block
Some loop-like blocks inside it
How can I make it more readable?
def https_request(server_url, header, content)
... |
An interview question I received:
You are given two unsorted lists of positive doubles
x contains the results from experiment 1
y which contains the results from experiment 2.
All results from the second experiment y are improvements over x
by i percent, where i is an integer. That is to say that given a
result... |
I am playing around with CSS/HTML/PHP and created a password generator:
<?php
$lowercase_characters = "abcdefghijklmnopqrstuvwxyz";
$uppercase_characters = strtoupper($lowercase_characters);
$numbers = "0123456789";
$symbols = ".-+=_,!@$#*%<>[]{}";
$chars = "";
$password ="";
function generatePassword($length, $chars... |
I have two loops on my page - each with their own category. It works, but I don't know if this is the best practice as I'm pretty new to this stuff.
<?php $my_query = new WP_Query( 'category_name=news&posts_per_page=3' );
while ( $my_query->have_posts() ) : $my_query->the_post();
$do_not_duplica... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.