instruction stringlengths 71 71.9k |
|---|
I recently dived into Ruby, so I want to improve this code. Is this good enough?
def ranksystem
logfile = IO.readlines("some_logfile.log")
logfile.each do |value|
value.gsub!(/[\n]+/, "")
end
logfile.delete("")
logcount = Hash.new(0)
logfile.each do |v|
logcount[v] += 1
end
... |
Here are 3 methods which handle my ajax calls.
I loop until pass b.c. I've had problems with the Ajax Object working as expected. This is noted here
/**
* Ajax
*/
var Ajax = ( function ()
{
var Ajax = function (element)
{
this.object = this.create();
};
Ajax.prototype.create = functio... |
I am about to start a very large project in Ruby. To get myself in the Ruby mindset I have been doing all of my homework and other side work in Ruby. I am hoping that some of you who know Ruby very well can look at this small program I have written and point out areas that aren't written in a Ruby-like fashion. Any and... |
I'm having a hard time creating a design (due to my lack of experience). I need a little of help to create the Model.
It's a mathematics system. I've created an IProblem interface with a function IsCorrect, this function helps me to know if the result is correct or not (by parameter). It also has a function CreateAnswe... |
The Javascript libraries have pretty complicated functions to calculate an element's offset on the page. I wrote the following function that works in all the places I need it, and I've tested a few edge cases as well. It adds the element's offsetTop to its parent's offsetTop all the way up the DOM to the document. Can ... |
I am currently developing a new breed of 3D engine for my upcoming thesis and I really liked the C# properties, but now I am on C++11 for obvious reasons. Since I couldn't find it elsewhere, I tried to write my own property mechanism that shall nicely integrate with C++.
I'd appreciate expert feedback on my class (or ... |
When invoking a Web Service from C# (where the external service might be WCF, ASMX, Java, etc. - you just don't know), it is common practice to point your modern development tool of choice (Visual Studio in my case) at the service's WSDL to generate a proxy class for calling the service. You can also create a proxy "by... |
This code allows me to save some settings from my small app to the text file which later I can retrieve by using substring and delimiter.
I wonder if there's any better way of doing this. If not, how could I make my code better or more efficient?
This is my code:
using System;
using System.IO;
namespace NameSpace
{
... |
This is a small web application that I have created using the Flask framework.
I am looking for best practices feedback, as well as design pointers. I am not confident that my design choices have been very good, or rather that they were the best they could have been, but I would like some feedback regardless on where ... |
I just started Python a few days ago, and I haven't programmed much before. I know my code is terrible; however, I would like someone to look it over. What I'm trying to do is create a photo "loop" that changes my Windows 7 login screen. I had a batch file doing it, but even though my code is crappy it does the job way... |
<?php
/**
* Module : Control
* Name : ControlSigin
* Input : Text Array
* Output : Pass or Fail(w/responseText)
* Notes :
* Call :
$instanceControlSignIn = new ControlSignIn();
$instanceContro... |
I wrote a little C++ program for playing Chess:
Now I check the valid moves by filling an 8x8 board with different flags called cBoard.
fNONE = none type
canPASS = the piece can go there
cannotPASS = the piece is blocked
canEAT = the piece can go there and will eat a piece
The Piece has 2 properties:
id = ROOK,PAW... |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
/**
* Solution for Quora Classifier question from CodeSprint 2012 This class
* implements a logistic regression classifier trained with Stochastic Gradient
* Descent. No reg... |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
... |
My task was to write a function in C where a string such as {2210090,34566,87234,564676} would be given as input and the function had to find out the count of numbers separated by comma whose average of single digits is greater than or equal to 5.
In the below example, the average of 2210090 is 2, the average of 34566 ... |
I'm using django and I wrote this decorator to take away some of the repetitive code I found for ajax views and I want to know your opinion (too basic, bad design, try this instead, etc).
def ajax_only(func):
def _ajax_only(request,*args,**kwargs):
if not request.is_ajax():
return HttpResponse('... |
HtmlAgilityPack is being really slow pulling back results. I have seen similar tools that get results a lot faster, but it's taking over a minute just to get the viewcounts on YouTube, and that's just with the first page of results.
Ideally I want to loop through multiple elements, but a nested loop wouldn't work for t... |
I'm interested in the idea of not having my BLL dependent on ASP.NET MVC. This means that I would like to have model binding occur within my service layer. But I want to take advantage of ASP.MVC's model validation as well. So I'm considering returning a custom validation dictionary from my BLL service methods like so
... |
Reading the article in Wikipedia about cycle detection I came across a relatively small code snipped of Floyd's cycle-finding algorithm. I'll put it here to keep everything in one place:
def floyd(f, x0):
# The main phase of the algorithm, finding a repetition x_mu = x_2mu
# The hare moves twice as quickly as t... |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
namespace ReactiveExtensions
{
class Program
{
static void Main(string[] args)
{
var sta... |
I am endeavoring to build my first non-trivial web application and so I'd like to confirm a couple of design decisions.
I have three tiers as follows:
UI (my MVC project)
Business Logic (separate project)
Data Access Logic (a simple .dbml that is part of project #2)
Is this a reasonable approach to separating concern... |
I am doing my homework and i have done this? Is there any other better way to do this?
def write_log(name, total):
# change user input with shape names
name = name.replace('1', 'triangle')
name = name.replace('2', 'square')
name = name.replace('3', 'rectangle')
name = name.replace('4', 'pentagon')... |
I tried to implement the dispose-finalize pattern on this WCF wrapper.
Do you have any comments about this? Something I missed?
namespace System.ServiceModel
{
public class WCFClientWrapper<TProxy> : IDisposable where TProxy : class
{
private string _endpointAddress;
public TProxy Service { get;... |
I'm a beginner, currently taking the Stanford's free CS106A course which teaches Java. The second assignment has you build Breakout from scratch using the ACM programs and graphics packages.
Since it's an online course and I don't have anyone who can review my code, I thought I might ask you what newbie mistakes I'm m... |
I have the following .net-page. I hope it is ok that it is only an example, describing my problem(s) pretty well.
<form id="form1" runat="server">
<div>
<asp:TextBox runat="server" ID="textBox1"></asp:TextBox>
<asp:TextBox runat="server" ID="textBox2"></asp:TextBox>
<asp:Calendar runat="server" ID="cal... |
Can someone take a look over my bootstrap file and see if you believe it's doing too much or the logic could be better.
<?php
/*
* ------------------------------------
* Autoloader for classes/files
* ------------------------------------
*/
function __autoload($class) {
if(file_exists(... |
As my parallel mergesort implementation was very memory dependent, I wanted to write a parallel quicksort one. Here it comes:
template<class In>
In partition(In b, In e) {
// create uniform distribuiton for random engine
std::uniform_int_distribution<int> rand_distribution(0, std::distance(b, e - 1));
// c... |
I'm looking for some assistance with a PHP script I'm writing. It creates a table that is then exported to an Excel file for download.
The issues as I see them are as follows:
$students contains 559 items and the $classes has 22 items and $attributes has 6 items:
<tbody>
<?php foreach($students as $student){
$p... |
I am trying to get my dictionary to iterate seven times after the dateTime is found. I want to iterate through the next week of objects in my dictionary pagesInRange. I figured out how to do it, but I am sure this is not good code. I am wondering if someone could point me in the direction of what I can do to improve th... |
I have about 6 of these, but I'm only posting two. Essentially I have a bunch of options with a "yes" or "no" radio button. If "no" is selected, I want a form to popup.
$('#Option1').live('change', function() {
if ($('input[name=Option1]:checked').val() == "False") {
$('#formDiv').show();
} else {
... |
So i got the grip on the basic MVC patterns in java using Observer / Observable method. Now in interest of keeping it clean and readable i would like some pointers before i move on regarding how to well organize my View as this is where my Classes get most filled up. We been told in school to keep file size per class b... |
This is a question I have in regards to my implementation of the MVC design paradigm that I came up with. The MVC type I am using is where everything must go through the controller. No communication happens between the model and the View. This is what I saw apple doing when I played with some iPhone stuff so I wanted t... |
I have just 'wrote' a linked list implementation of Disjoint Sets. This is the changed version of Bob Tian's implememnation. Can you take a look and tell me if there is something missing ? For instance memory leaks while destroying nodes. And please judge it also in performance matter.
I would like to change the long N... |
I have the following code that checks for three different properties. Unfortunately each call can throw up to four exceptions that I all have to catch. Can I some how make the code more readable by reducing the amount of try/catch?
public void retrieveSourceCode() {
try {
fileName = RestServices.get... |
I use the DefaultCodeFormatter of the core Java package to prettify my code. Unfortunately I want to look my code very different from the default settings. That why, I have to explicitly define a lot of values:
public static String makeSourceCodeLookingMoreSexy(String source) {
Map<String, String> options = Def... |
I am relatively new to C and would like some feedback on a function that I have written, if it adheres to C standards or if there are some other things which I could have done better/differently.
/* Function to find DB matches and store them in a glycopeptide structure */
/* Written by Bas Jansen, 18-01-2012, Leiden Un... |
I created a function that compares two hashes and returns a report on whether the subtraction of their values is negative or not.
The problem comes down to having a cost hash for a building and a current resources hash like:
cost = {:wood => 300, :stone => 200, :gold => 100}
reqs = {:wood => 200, :stone => 220, :gold =... |
I have a collection (Child Collection) on which I am performing some operation to make another collection (Parent Collection). But that I do in a dirty foreach loop. I want to do it in an elegant way.
GroupInfo grpInfo;
List<GroupInfo> lstGroupInfo = new List<GroupInfo>();
foreach (AddressInfo addressInfo in subDetails... |
I'm building some code with an inheritance heirarchy, and I want to validate the resulting instances. At present I have a method in the base class can override to return a list of the problems (see the code).
My problem here is that this works, provided the inheriting classes remember to get the base results first, bef... |
I'm starting to look at Python and its facilities. I've just tried to make one simple program using some base libraries.
I would like to hear some comments about anything you've noticed - style, readability, safety, etc.
#!/usr/bin/python2.6 -u
import urllib2
import simplejson
import zlib
from optparse import OptionP... |
I've been getting into plugin development for jQuery and my first creation is a tooltip plugin. I've been reading a lot about plugin development especially with the use of JavaScript prototyping. I'm just looking for any tips to further improve my plugin development (only 144 lines of code).
Two questions in particul... |
I'm writing a program to convert integers to Roman numerals (naively -- it doesn't know how to do the subtraction trick yet). What I have is functional, but it is not "Good Ruby".
VALUES = [
["M", 1000],
["D", 500],
["C", 100],
["L", 50],
["X", 10],
["V", 5],
["I", 1],
]
def romanize n
roman = ... |
I've updated the previous version to be more object oriented as suggested.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
/**
* A class containing a single record. Each record contains the Quora... |
This is a solution from the CodeSprint 2012 coding competition. Any suggestions on ways to improve the object orientation or general style would be much appreciated. The code takes several text documents, encodes them into feature vectors using TF-IDF, and then applies k-means clustering to group documents with similar... |
I have the follow function:
Download.prototype.fundamentals = function(exchanges, cb){
if (!(exchange = exchanges.pop())) return
var that = this;
this.login(function(err){
if (err) return cb(true, exchange.code)
var path = util.format(that.eoddata.fundamentals['path'], that.token, excha... |
I have a package called pkg_crypto.
My select looks like this:
SELECT "SEQ", pkg_crypto.decrypt("NAME", 'secret') name, pkg_crypto.decrypt("TEL", 'secret') tel
FROM MYTABLE
ORDER BY "SEQ" DESC
This takes about 3 seconds for a few thousand records. (Average of 10 runs is 3.032s.)
Now, if I change it to either of the fo... |
In a custom Ant task, I have the following constants:
private static final String _REVISION = ".revision";
private static final String _CODEBASE_INFO = ".codebase";
private static final String _DIFF = ".diff";
private static final String _TYPE_GIT = "git";
private static final String _TYPE_SVN = "svn";
private static f... |
I'm newish to obj-c and I have some code that works, but I'm thinking I may be leaking memory as I have two retain statements and no release statements.
In both cases if I remove the retain I get a bad access error on [btPairedDevices count]
Am I doing this right or is there a better way?
//============================... |
Given:
k = {'MASTER_HOST': '10.178.226.196', 'MASTER_PORT': 9999}
I want to flatten into the string:
"MASTER_HOST='10.178.226.196', MASTER_PORT=9999"
This is the ugly way that I'm achieving this right now:
result = []
for i,j in k.iteritems():
if isinstance(j, int):
result.append('%s=%d' % (i,j))
else... |
Is this a good way to design a class so I can prevent values being changed/ the state must remain as it was when it was intantiated...
This code would be normally instantiated after a call from the database.
public class InstructionWorkflow : IStageWorkflow
{
private readonly int _companyID;
public InstructionW... |
I need a bit of help on if I have coded this class correctly.
I want to handle the setting of client cookie/client store.
public class UserSession : IUserSession
{
private readonly IReadOnlySession _repo;
public UserSession(IReadOnlySession repo)
{
_repo = repo;
}
private string _loginId;
... |
I'm writing some code to perform some simple form validation and I would like to display error messages inside the actual relevant textarea by means of a text fadeout/fadein effect.
To achieve this I am using jQquery UI to do the following:
Step 1: Animate the color to match the background colour
Step 2: Modify the te... |
I have inherited the Java function below, and it works the way it should, but you have to look at it for a minute to figure out exactly what is going on. Is there a more succinct or elegant way to encode this logic?
private Float applyFactors(Float originalValue, Float localFactor, Float globalFactor){
if (globalFa... |
I was wondering if this was a decent way of handling this function. Please take a look.
// Use Less Mixins from Theme Options to adjust Stylesheets before Parsing Less to CSS
add_filter( 'less_vars', 'wellies_less_vars', 10, 2 );
function wellies_less_vars( $vars, $handle ) {
//Necessary for UpTheme Framework
... |
I have several lists of objects which are stored in different locations, based on what they are and who needs them - the system, or the user, for example. There are times where I am only given an ID and need to find the name, type, or description, but I would like a very succinct, efficient way to do so. Since I'm also... |
I have a method that ascends an inheritance tree and returns the element at the root, progressively yielding the elements if appropriate:
# Finds the root of the hierarchy.
def root
element = self
until element.root?
yield element if block_given?
element = element.parent
end
yield element if block_given... |
I am pretty new to JavaScript and learning the intricacies of this language. I wanted a unique collection which will overwrite while adding if an item already exists else add. Rest of the behavior should be just like any other collection. I had written the type and its as below. Instead of using an array internally, I ... |
I've been working on this elevator program for quite some time now and finally finished it and made it work and I'm pretty proud of myself, but I'd like to see ways how to optimize my code so I can learn for the future. By optimizing, I mean making the code look better, maybe by using fewer lines of code.
import java.a... |
I have the following code with switch case statement:
public string IrregularCouponLabel
{
get
{
switch ((ctrl.IrregularCouponFirst ? 10 : 0) + (ctrl.IrregularCouponLast ? 1 : 0))
{
case 11: return LocalString.Evaluate("label.Both");
case 10: return LocalString.Evaluate("... |
A previous developer had an array of strings like so:
public static const PAGE_ONE:String = 'PageOne';
public static const PAGE_TWO:String = 'PageTwo';
public static const PAGE_THREE:String = 'PageThree';
public static const PAGE_FOUR:String = 'PageFour';
public static const PAGE_FIVE:String = 'PageFive... |
I am implementing Unix sort in Clojure. This is my first program, and I would like some feedback regarding any non-idiomatic, harmful code and any other best practices I can include in future versions. I tried my best to follow the coding standards, but went with camelCase instead of hyphen-case for variable and functi... |
I have a workflow; within the workflow I can have many stages. I want to open and close a stage based on some business rules. E.g., stage 7 cannot be opened, because stage 5 + 6 need to be closed first; or, check whether key data x is filled out: if so, you can close stage 4.
How can I optimize or improve my code, belo... |
I have a routine that can be potentially reduced.
internal ArrayBufferObject GetAccessorArray()
{
ColladaDocument colladaDocument = GetColladaDocument();
ColladaArray colladaArray = colladaDocument.GetSpecialElement<ColladaArray>(Source);
ArrayBufferObject bufferObject;
if (IsSimpleParamsConfiguration(... |
My goal was to make a list dynamically list itself into two columns, no matter the length of the list. I know this is possible by just floating the li nodes, but I wanted to keep the li nodes in the same vertical order. I would really like to hear from people who know more about JavaScript and jQuery than I do if this ... |
I am very new to functional programming. I wrote this program where the user can enter an integer and it will print the factorial. If the user enters a negative integer or not an integer at all, it'll give the user a second chance.
This doesn't feel very functional to me. How can I make this code more functional (esp. ... |
This is a scraper written in CoffeeScript for NodeJS. It is run in an interval (set to 5 seconds here to dramtically show the leak). Somewhere this code leaks memory. I already tried nulling a few things for manually deleting references. Where is the reference kept that produces the leak?
request = require 'request'
js... |
I'm creating a factory design for math problems. The idea which I have is:
When the factory initializes, creates in a list some problems (20 initially)
If the program wants more than 20, the list should grow until reach the requested quantity.
For example, if I require 30 problems of the X problem, will generate two ... |
I've been looking at ways to use asserts in programs that must do some kind of cleanup on fatal errors, and have arrived at the following pattern (PROJECT being replaced by the name of the project):
#include <boost/exception/all.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <string>
#include <iost... |
I have this method which sends binary data to server. The code works fine, but still, it's structure is kinda stupid: output and input connections are opened like thousands times (depends on data size), closed only once.
I cannot move the code that opens connection outside of the loop because I'm getting strange errors... |
There is HTML that triggers the code below I want to disallow executing the script more than once per 24 hours. I wanted this script to store the last visit time in a table against the user ID in a database, then do a time calculation and back them out until the 24 hour expiry time.
<?php
//Input correct values into th... |
I'm learning functional programming and their concept of Monads. I've found nothing more effective in learning than writing an implementation in a programming language I have experience with.
I came up with the following implementation in Java. Could someone please suggest improvements?
So, I have an interface, Bindabl... |
I've wrote this class in PHP for my future projects:
<?php
/**
* Auth
* This class is used to securely authenticate and register users on a given website.
* This class uses the crypt() function, and PDO database engine.
*
* @package Class Library
* @author Truth
* @copyright 201... |
I have a small library for utility functions for ES5 mainly aimed at OO code organization.
Are there any recommendations for the API or for the code quality / organization?
github page
styleGuide it complies to
Note the library has a few tricks in it for aggressive minification.
Code inlined
/*
pd(obj) -> proper... |
I use this Matlab code:
load ~/emailAnalysis/results.txt
results=results(size(results,1)-400:size(results,1),:)
temp = results(:,3)-1238370000;
h=plot(temp,smooth(results(:,1)),':b')
set(h,'LineWidth',1)
ylim([0 80])
xlim([max(temp)-(86400*7),max(temp)-1])
set(gca,'XGrid','on')
ylabel('Emails')
hold on
i=plot(temp,smoo... |
I'm trying to devise a way to calculate the mean differences (the absolute average differences between any two values in a set), of sub-arrays (starting from arbitrary indices) in an int array. I'll be placing the bounds of each subarray in to "buckets" of differing mean difference magnitudes.
The problem is, I can't f... |
I find it a bit odd in ASP.NET MVC that the Html helper extensions, like Html.EditorFor, take a Func<T1, TResult> where the T1 argument is just the already in scope Model variable, e.g.:
@Html.EditorFor(x => x.Name)
If I really wanted Model renamed, I would just assign it once to a variable in the top of the razor vie... |
I've got this humanoid_shuffle I wrote in Python. I've been wanting to learn C so as an exercise I ported it to C. As this is my first venture into C and even the ideas of memory management and the like, what are some ways to make this better from a code quality and efficiency perspective?
A couple of quick thoughts fr... |
I am looking for feedback on my doubly linked list implementation that I have written in Java. I am looking for specific feedback on the efficiency of my code, as well as my usage of generics. I am pretty new to using generics in Java, and I'm not quite sure that I am using them correctly yet.
My node class is pretty ... |
I have a form that I need to resubmit to the action if a checkbox is TRUE. This is to facilitate chained select boxes with javascript turned off.
Ideally I would instanciate the form object at the end only, just before sending it to the view, but as you can see I need it beforehand.
The form takes parameters (an arra... |
So say I have a method that does a bunch of stuff, and I want to refactor this method to take a different type of parameter:
public object A(MyObject a)
{
// does a bunch of crap with a
// then calls another method
this.B(a);
}
Now even method B() does a lot of crap with that same Object a. What if I want... |
I'd like to refactor the following code:
case @request.path
when '/'
Rack::Response.new do |response|
do_stuff
end
when '/env' then Rack::Response.new(@env.to_html)
end
And extract Rack::Response.new, something like the following:
Rack::Response.new case @request.path
when '/' then Proc.new {|response| do_s... |
Recently I was asked to write algorithm to rearrange elements in two-dimensional array in spiral order.
Input array: Output array:
[ 1, 2, 3, 4] [ 1, 2, 3, 4 ]
[ 5, 6, 7, 8] = > [ 8, 12, 11, 10 ]
[ 9, 10, 11, 12] [ 9, 5, 6, 7 ]
I came up with the following... |
This snippets works, but I think it can be optimized:
/* highlight input, if it is empty */
$(function() {
var highlight_if_no_val=function () {
$(this).toggleClass('highlight-input', !$(this).val());
}
$('#id_index-EditForm-gpnr').keyup(highlight_if_no_val).each(highlight_if_no_val);
}
);
Is there... |
I recently started cleaning up my projects and decided that I want to create a personal repository of useful bits of code. I found this bitmap code between them and heavily edited it and I'd appreciate if someone could review it, because I'm not that used to bitwise operations and such. Is the code portable enough, or ... |
I'm trying to create URL parse class., so i can check URL Segment / part,
Example:
http://localhost/myproject/class/method/arg/other (localhost)
http://www.myproject.com/class/method/arg/other (live site)
http://www.myproject.com/class/method/arg/other?param=value (with get param)
In urls above:
$url->segment(1)... |
This code is for continuing the execution after an exception, and this is ugly:
int step=0;
do{
try{
switch(step)
{
case 0:
step=1;
methodAAAAACanThrowException();
break;
case 1... |
I want to be able to convert a list of objects into a string csv format. I've written this extension method below but have a feeling I'm missing something as this seems like potentially a common thing to want to do.
private static readonly char[] csvChars = new[] { ',', '"', ' ', '\n', '\r' };
public static string To... |
I'd like some feedback on my implementation to get all the permutations of a set.
Eg:
@Test
public void test()
{
def data = [["A","B"],["A","B","C","D"],["D","E","F"]]
def expected = toResultSet("ABD,ABE,ABF,ACD,ACE,ACF,ADE,ADF,BAD,BAE,BAF,BCD,BCE,BCF,BDE,BDF");
def result = SetPermutations.getSetPermutatio... |
I have following code that is used of one time skipping some functionality(actually do something only one time until SkipSomeStuff is true):
private bool _skipSomeStuff;
public bool SkipSomeStuff
{
set
{
_skipSomeStuff = value;
}
get
{
if (_skipSomeStuff)
{
_skipSomeStuff = false;
... |
I'm attempting to create a linked list of length n using Python. I have the simple list implemented, a working concatenation function, and a working create_list function; however, I just want to know if there is a more efficient method at making the linked list than using my concatenate function (made for testing).
Sim... |
I have a code which was not refactored at all. I refactored it to some extent, but stuck at a point where I cannot think of anything further.
Tractor.java:
package com.farm;
public class Tractor implements MethodsInterface {
private int[] position;
private int[] field;
private String orientation;
p... |
I have the following code to do remember-me style login:
<?php
session_start();
if(!isset($_SESSION['login'])) $_SESSION['login'] = 0;
if(isset($_COOKIE['web_login_cookie']) && $_SESSION['login'] == 0) {
$sql = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($sql)) {
$pass = sha1($row... |
How expensive is this query?
Lets say for example if I don't have a field called total_comments in my blog table. All I want to know is the blog has comments or not.
SELECT EXISTS (SELECT true FROM comments WHERE blog_id = b.id) as has_comments FROM blogs b
How else could this be achieved?
|
I looked at the pypi classifiers and some guide to help me write the following script, and here's me wondering if it can be improved:
import xmlrpc.client
# pypi language version classifiers
PY3 = ["Programming Language :: Python :: 3"]
PY2 = ["Programming Language :: Python :: 2"]
PY27 = ["Programming Language :: P... |
I've been working on this class for a while now and would appreciate some feedback, even if it's just nitpicking. I've added basic instructions on how to use the class below along with some questions.
<?php
/**
* @category Security
* @version 1.0
* @author First Last <email@mail.com>
* */
class SessionH... |
I am using this code for a fast JSON API without routes.
Does this code contain any useless parts? Is the class loader efficient enough? Are there any better options? Is ReflectionMethod slow if used once?
<?php
/*
* Init stuff
*/
session_start();
define('ROOT', realpath( dirname(__FILE__) ) . '/');
set_include_p... |
I'm a complete beginner in Python and programming in general. I made a program for Spotify's Best Before puzzle. It was accepted. I have looked a litle around on internet and looked at other solutions to the problem, and everyone I have seen have importet several modules, inclusive the Calendar module. I understand thi... |
In our software we enable certain features based on the existence of a flag. The Flags class is a static class used to determine the existence of such a flag.
I came across one piece of logic that I wrote that I feel could benefit from refactoring. The boolean logic works, but I think it's difficult to understand or ... |
I've probably done some pretty horrendous things here, but I'm throwing it out for people to give me some feedback that I can start using to immediately improve my Clojure coding style.
Additional suggestions would be performance enhancements as well as areas where I could use transients if it is advisable.
So far I've... |
I ran into an issue where I was doing this:
dictionary1 = {}
dictionary2 = {}
foo = dictionary1.get('foo', dictionary1.get('bar', dictionary2.get('baz')))
I.e. if the value isn't supplied in one dict, it would fall back on the next and then on the next. In this case dictionary1 has a key that is deprecated that I'm ge... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.