instruction stringlengths 71 71.9k |
|---|
I haven't done too many nested statements in MySQL and I was hoping to have the below SQL looked at and let me know if there is a better/more efficient way of doing what I am trying to accomplish.
Through all of my tests it appears that everything is working properly, I just want to make sure I am meeting best practice... |
I wonder
Is it appropriate to hide imported classes (collections and UserDict in this case) from Python IDE (e.g. IPython)?
Is there a more efficient algorithm/implementation?
Please feel free to comment on how you would improve this class.
import collections as _collections
import UserDict as _UserDict
class _IdDi... |
I'd like to be able to define Angular constants in terms of other constants.
It's not possible to inject dependencies into Angular constant services. When I want one of my constants to depend on another of my constants, I use a provider service. This allows my constants to have dependencies (on other constants), but ... |
Given a shape, get all triangles that can be possible by connecting the points.
Example: given 3 points, only 1 triangle is possible, but given a pentagon, 10 are possible.
Also the combination formula is \$\dfrac{n!}{r!(n-r)!}\$. Does it mean \$O(n!)\$ is the complexity?
Looking for:
Code review optimization and ... |
At the time I try to write some code to handle an IRController, I got this following classes:
public class UsbDataInputListener implements UsbPipeListener {
@Override
public void errorEventOccurred(UsbPipeErrorEvent upee) {
throw new UnsupportedOperationException("Not supported yet."); //To change body... |
I'm trying to make a loop where it returns whether or not a rectangle collides and then to which coords the rectangle should move to.
I'm calling my function like this:
rectangles2[i].rect = rectangleupdated(i, rectangles2);
And this is inside my function:
private Rectangle rectangleupdated(int i, List<rectList> recta... |
This Python main is what greets the user to a thrice nested super duper barebones OS. The entire rest of my code isn't bug free but this section is, and it feels dirty anyway. I'd like to know how to make it better, by adhering to conventions, or by removal of fatty code.
NOTE: I am not looking to use classes with an... |
I have a Python script which parses a complicated CSV generated on election nights. Each row of the CSV represents a race. As I loop through the races, I store the candidates for each race into a list called cnds. The other variable to note is called num_win, and it holds the number of people who will be elected for th... |
I'm fairly new to Objective-C. The app I'm trying to make, is using the foursquare API to list up places that is close by. I've re-written this app more times than I care to admit, because I feel the implementation get messier the bigger the app gets. I take that as a sign that my basic code structure is in need of som... |
I have written a partition function in Python (my_partition_adv). I have written this one after reading a similar function from a website. The version of the partition function from the website is also given below (parititon_inplace).
As I am a beginner in Python, I want to know the following things:
My version look... |
I was needed a SET-like data structure written in pure C for some university class, so I've implemented a simple one - the Treap (or cartesian tree).
Please check if everything is okay (actually, I'm not sure that there isn't a memory leak there).
cartesian_tree.h
#ifndef _CARTESIAN_TREE_H_
#define _CARTESIAN_TREE_H_
... |
I'm in the process of creating a program that can model points, vectors, lines and segments. I have the classes built and confirmed to be working correctly. The classes are built to handle multiple dimensions, so as an example, the same point class is used for R1, R2, R3, ... Rn.
The issue that I am dealing with is how... |
I am learning how to implement a basic undirected graph and perform a depth first traversal.
Please critique my code for correctness, best practices, security, and any other comments that may be helpful.
Graph.h:
#include <vector>
/************************************************************************
/*************... |
Learn You a Haskell shows the lines function:
It takes a string and returns every line of that string in a separate list.
Example:
>lines' "HELLO\nWORLD\nHOWAREYOU"
["HELLO","WORLD","HOWAREYOU"]
Here's my implementation:
lines' :: String -> [String]
lines' [] = []
lines' xs = lines'' xs []
where lines... |
So I've been working on AI for a Tower Building simulation game for quite a few days, and I think the code would really benefit from review. I'm a hobbyist programmer, but I really care about doing things properly so don't be afraid to be harsh. I want to learn.
The basic idea of the job management system is as foll... |
Question: To find the maximum number of consecutive zeros in a given
array.
Example:
Input: \${1, 2, 0, 0, 2, 4, 0, 2, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 7, 0}\$
Output: "Maximum number of consecutive zeros : 6"
Here is what I've come up with:
public class ZeroSeriesLength {
public static void main(String[] args) {... |
For a school project, I am creating a text-based adventure game in C++. I have shown my code to my teacher and he is stating my code is not entirely logical in sequence and that I should make my if statements inside functions because there are so many. I need help as to know how to make these changes.
Note that this i... |
I developed this tickets booking system recently to showcase HTML5 features. I would like you to review it from the UI/UX perspective. Also if there is something more that I can add.
Is it good enough?
JS/HTML5/CSS3:
$(document).ready(function(){
// first check the movies already booked
check... |
I am currently learning angular.js.
The following is an example I came up with. The goal:
An editor for a dict, the dict format is: {key: [type, data]}
A view of the same data
The "type" should be validated. I use two types: "string" (can be anything) and "greeting" (a string that starts with hello)
Don't care for min... |
I use the jQuery Calendar with an underscore template and I wanted to put <li> tags around each week. This does the trick, but it's awful.
<% _.each(days, function(day, index) { %>
<% if ( index % 7 == 0 && index != 0) { %></li><% } %>
<% if ( index % 7 == 0) { %><li><% } %>
<div class="<%= day.classes %>"... |
The following code is ran when the user presses a button to generate a log file based on the date selected. The DatePicker has a restrictive selected date range of the last 2 weeks including that same day. If the user leaves the page open for more than one day (very common), they will however be able to generate a log ... |
For context, I have a SourceControlSystem factory class that detects if a user is using Git, SVN, or another source control system and returns an object to interact with that source control system. The implementation is here, but I don't think it's very relevant.
So, at the start of my library, I have this single line:... |
I have a MVC framework, and I am struggling with the following dynamic menu code.
A menu is pretty much HTML, so technically it should reside in the View, but the dynamic part is driven by PHP and a config class that holds all the menu items.
Where would I place this class? (model layer, view, library, or helper folde... |
I'm writing a function which gets two strings and a number k as an input, and outputs a string with length k which is present in both strings. I want to do this using the function hash_sequence().
I need my code to be as efficient as possible because my inputs are very large strings.
def hash_sequence(string, k):
... |
I was wondering what I can do to increase the performance of this program. The algorithm is pretty slow right now but I was wondering what I can do to increase the efficiency of this program. I used lists instead of strings to avoid immutable string concatenation.
This program should compress strings by the number of ... |
I have a RequestsExtensions class with two functions for sending GET/POST requests.
using System;
using System.Net;
using System.Text;
public static class RequestsExtensions
{
/// <summary>
/// Sending POST request.
/// </summary>
/// <param name="Url">Request Url.</param>
... |
Here's a (hopefully) better shared pointer than the previous one. The improvement is that now it should also accept function and lambda objects. Should work fine with threads.
#pragma once
#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP
#include <cassert>
#include <atomic>
#include <memory>
#include <utility>
#include ... |
My website is poorly coded.
The structure is pretty simple:
A RewriteRule redirects /.... to /index.php?page=$1
mypages/page.php contains the page content and actions (model controller and view glued together...)
index.php wrap the demanded page into a theme (basically include header and footer around it)
The site is... |
This is a complete rewrite of the code posted for review in this question. The question is identical.
def render(digits):
'''This function converts its input, a string of decimal digits, into a
barcode, using the interleaved 2 of 5 format. The input string must not
contain an odd number of digits. The outp... |
I have to work with C-style functions which return ERROR_SUCCESS when successful or an error code when not. I want my code to be nice and neat and easy to read but I am not sure I like what I have.
Option one:
int Foo()
{
int result = Init();
if (result == ERROR_SUCCESS)
{
result = SetTemperature( ... |
Learn You a Haskell demonstrates the break function:
breaks it when the predicate is first true.
Example:
-- ghci> break (==4) [1,2,3,4,5,6,7]
-- ([1,2,3],[4,5,6,7])
Here's my code:
break' :: (a -> Bool) -> [a] -> ([a], [a])
break' _ [] = ([], [])
break' f ys = break'' f ys []
where break'' _ [] a... |
I'm attempting this simple HackerRank counting sort problem but testcase #3, which has 100,000 test cases, is timing out.
Is there something particularly inefficient about this code?
input = []
$stdin.each do |line|
input << line
end
input.shift
arr = input.map { |line| line.split(' ')[0].to_i }
answer = (0..99).... |
Learn You a Haskell shows the words function.
words and unwords are for splitting a line of text into words or
joining a list of words into a text
Example:
ghci> words "hey these are the words in this sentence"
["hey","these","are","the","words","in","this","sentence"]
ghci> words "hey these are the w... |
Learn You a Haskell explains the unwords function.
$unwords ["hey","there","mate"]
"hey there mate"
Here's my implementation.
unwords' :: [String] -> String
unwords' [] = []
unwords' (x:xs)
| null xs = x
| otherwise = x ++ " " ++ unwords' xs
Is there a possible implementation with fold? I tried the followi... |
Please review code quality and give me shortcuts or optimization tips as well as corrections.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Clean HTML Code</title>
</head>
<body>
<p><textarea id="code" cols="80" rows="15" autofocus></textarea></p>
<p><input id="comments" type="checkbox" checked> <label fo... |
Here are all the threads write the log file. I want to know if the below script is fine, if it needs any modifications, and whether I am utilising threads properly to execute this code quickly.
open(LOG,"+>","log.txt")or die "cant open the file";
my $file_total= scalar @listOfFiles;
my $div = $file_total/$threa... |
I am a tyro with OOCSS and think I bit off more than I can chew in creating a dropdown bubble for a menu item.
I removed as much element specific code as I could, but still think I don't quite have it down.
I know my class names are all messed up, but I'm really just messing around right now.
For example: should the d... |
I have changed a lot from my original code that I posted about a week ago, you can see that here:
Guild Wars: Knights & Dragons
Now what I need to know is if I improve this code further. Any help is greatly appreciated.
EDIT: Should I add <title> tags to my page to make it more accessible? And also <meta> keywords? I ... |
I would like to know if my java db class is enough protected against hackers. (I'm currently developing an Android application). I protect it with a infos.properties file which contains every information that I need.
final class DB {
static final String DRIVER;
static final String URL;
static final String USER;
stati... |
I've been working on what is essentially my first proper attempt at making a useful PHP wrapper class for the Wordpress Settings API. It works great so far and I plan to add more methods as I go so that I eventually build up a class that can be used in pretty much any situation.
As this is my first proper PHP class, I'... |
I am creating a function for sanitising user inputs and user inputted data outputs.
Please offer advise on any improvements which could be made:
function cleanse($input) {
$search = array(
'@<script[^>]*?>.*?</script>@si', // Strip out javascript
'@<[\/\!]*?[^<>]*?>@si', // Strip out H... |
data = ['HTTP/1.1 200 OK', 'CACHE-CONTROL: max-age=1810', 'DATE: Wed, 14 May 2014 12:15:19 GMT', 'EXT:', 'LOCATION: http://192.168.94.57:9000/DeviceDescription.xml', 'SERVER: Windows NT/5.0, UPnP/1.0, pvConnect UPnP SDK/1.0', 'ST: uuid:7076436f-6e65-1063-8074-78542e239ff5', 'USN: uuid:7076436f-6e65-1063-8074-78542e239f... |
This is code written for use inside a 3rd party application to pull information from an XML and insert into a word document, I don't know all the mechanics of the fun process of inserting the information into the word document (inside the 3rd party application) so some questions you might have for me are going to be a... |
I have to clone some Entity, then I wrote this piece of code.
public override object Clone()
{
var CloneUser = base.Clone() as FMSUser;
CloneUser.Username = this.Username;
CloneUser.IsEnabled = this.IsEnabled;
CloneUser.IsNeedPasswordReset = this.IsNeedPasswordReset;
CloneUser.LastName = this.LastName;
Clo... |
Task from CodingBat:
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.
My original answer to the problem:
def sum13(nums):
sum = 0
for idx,val in enumerate(nums):
... |
I am trying to implement a HTTP Server in Java, I want the server to use a persistent connection per thread for request and response. After some research on Google, this is how my program looks like. It runs fine without any exceptions but I am unable to tell if it is doing what I want it to do, that is connection per ... |
I want to build a function which finds the longest substring that is common between two large strings. I want to do this using the first two functions.
I'm running it on very large strings (containing more than million characters) and it's taking a lot of time. How can I optimize the function findlongest?
def hash_sequ... |
Following is the code I wrote to download the information of different items in a page.
I have one main website which has links to different items. I parse this main page to get the list. This is handled by the Items class.
I also parse these each of the links in the list using the Item class.
I have implemented a Han... |
I have an implementation of an optimization algorithm called the Covariance Matrix Adaptation Evolutionary Strategy (CMA-ES). I am using this algorithm to optimize the position of wind turbines inside a wind farm, but if I place more than a certain number of turbines (equivalent to a high value of N at the beginning of... |
I've built a simple chat server/client on Node.js and socket.io that I would like reviewed. My main concern is making the chat.js (client) running as cleanly as possible (OO) and streamlining data back and forth so I can add client monitoring (updated list of connected users) features down the line without issue.
Aside... |
This is a follow up question to the one I asked a couple of days ago.
I reviewed the suggestions & did some research (specifically, read relevant info on CLRS). The new version is 3 times faster (210ms vs 71ms on 100,000 numbers) & looks cleaner.
One thing I still feel weird about is not using iterators except than to... |
I have the following diagram (did this only to ask here, it's obviously missing details):
From the diagram you can see I have to check if all sensors in an environment are respecting the established conditions, but I'm not comfortable with the way I'm implementing this...
class Environ:
def __init__(self):
... |
It is not always possible to simplify program design by strictly managing the lifetimes of objects. If two objects have unpredictable lifetimes, but one of them needs to refer to the other, a simple pointer or reference is a segmentation fault waiting to happen.
The approach that I tried first was to have both objects ... |
I am using JUnit, Hibernate and Spring Framework. I wrote a simple test to test whether entity was updated correctly or not.
Is this correct way to test if entity was updated? Could it be done better?
@Test
public void testUpdated(){
ConfirmationEntity confirmationEntity = confirmationDao.find(1L);
confirmation... |
Though I can achieve most ends via a series of conditionals and arithmetic, especially when iterating over or comparing arrays I frequently hear of much more efficient implementations.
Hailing from PHP, I am accustomed to having array_merge() accessible; this JS function is different in that key that don't match the fi... |
I'm learning MATLAB (still trying to "think in vectors") and have the following piece of code:
stats = regionprops(bwconncomp(mask), 'all');
% find the object nearest our nucleus
smallest_dist = flintmax;
location = [cell_x, cell_y];
for j = 1:numel(stats)
stat = stats(j);
dist = pdist([location;[stat.Centroid... |
This my implementation of the Merge Sorting Algorithm:
def merge(series1, series2):
output = []
while series1 != [] or series2 != []:
if series1 == []:
output.append(series2[0])
series2.pop(0)
continue
if series2 == []:
output.append(series1[0])
... |
Implement an iterator (generic) which skips an element if it is equal to the previous element. e.g: AAABBCCCCD, produces ABCD.
Please suggest improvements.
import java.util.Iterator;
public class DeDupIterator implements Iterator {
E next = null;
Iterator<E> itr;
public DeDupIterator(Iterator<E> iter) {
itr = ... |
Learn You a Haskell shows the delete function.
delete: deletes first occurrence of item
ghci> delete 'h' "hey there ghang!"
"ey there ghang!"
Please critique my implementation.
delete' :: (Eq a) => a -> [a] -> [a]
delete' y xs = delete'' y xs []
where delete'' _ [] _ = []
de... |
This is supposed to be an evolutionary algorithmic program, and I'm not sure if it does what it's supposed to do.
It is supposed to take a random list of numbers (containing at least one 5), and over many generations, increase the probability of 5's reproducing, thus having the 5's eventually taking over the output.
Is... |
I have not yet seen an implementation of the observer pattern in Python which satisfies the following criteria:
A thing which is observed should not keep its observers alive if all other references to those observers disappear.
Adding and removing observers should be pythonic. For example, if I have an object foo with... |
Learn You a Haskell presents the \\ function.
\\ is the list difference function. It acts like a set difference,
basically. For every element in the right-hand list, it removes a
matching element in the left one.
Example:
ghci> [1..10] \\ [2,5,9]
[1,3,4,6,7,8,10]
Please critique my implementation.
setDiffere... |
Learn You a Haskell shows the union function:
union also acts like a function on sets. It returns the union of two
lists. It pretty much goes over every element in the second list and
appends it to the first one if it isn't already in yet. Watch out
though, duplicates are removed from the second list!
Example:
... |
This is a Python module I made to search the Rotten Tomatoes movie API. It caches the search results in a SQLite database.
What improvements can I make to the cache system? Is there a better way to store the results of the API search?
Is there a better way to communicate with the API?
import urllib2
import json
impo... |
I am trying to implement a Doctor/patient scheduling system. It would be great if someone can review my code and suggest how I can improve it further. I would like to know how to have a date-based calendar for this. I also want some idea on how to protect a patient record data from one doctor to another.
One more feat... |
Learn You a Haskell shows the insert function.
insert takes an element and a list of elements that can be sorted and
inserts it into the last position where it's still less than or equal
to the next element. In other words, insert will start at the
beginning of the list and then keep going until it finds an elem... |
I have a number of JSON files to combine and output as a single CSV (to load into R), with each JSON file at about 1.5GB. While doing a trial on 4-5 JSON files at 250MB each, the code works when I only use 2-3 files but chokes when the total file sizes get larger.
I'm running Python version 2.7.6 (default, Nov 10 2013... |
Can anyone help make this perform faster?
import numpy as np
from scipy import signal
d0 = np.random.random_integers(10, 12, (5,5))
d1 = np.random.random_integers(1, 3, (5,5))
d2 = np.random.random_integers(4, 6, (5,5))
d3 = np.random.random_integers(7, 9, (5,5))
d4 = np.random.random_integers(1, 3, (5,5))
d5 = np.ran... |
I recently implemented the RDP polygon approximation algorithm in Python and I'm skeptical of whether or not I implemented it correctly of with the greatest efficiency. The algorithm runs in around 0.0003 seconds for a polygon with 30 points on my computer (an Intel Core i5 with 3.8 GHz of RAM), so I'm worried about ho... |
Tetromino class:
class Tetromino(object):
def __init__(self, board, matrix, type, color, x=0, y=None, updateinterval=FRAMERATE, queue=0):
self.matrix = matrix
self.type = type
self.board = board
self.color = color
self.updateinterval = updateinterval
self.time_until_u... |
I have been given a change to rewrite an old framework we use, and to implement the repository and unit of work patterns, but in an attempt to not rewriting all queries I have ended up with a weird combination of Linq queries and Linq lambdas.
I was hoping someone could explain to me a better way of doing this, or advi... |
I just implemented code to add two ints together as strings and I'm sure my method is inferior. I've looked up other methods too but I'd appreciate criticisms specific to my code. I really want to make sure I don't develop bad habits in C++ and I think leveraging the knowledge of brighter individuals than myself on thi... |
I am using Hibernate 4 and Spring Framework 4. I wrote a simple test to check whether object was persisted or not.
All set values in confirmationEntity are required.
In this test I relly on that, that after a new object is persisted, then it is given a new id automatically.
Is this correct way how to determine if the o... |
This is what I have which is mostly based on code I've found on Stack Overflow. How good is it? Can you suggest better implementation?
#pragma once
#include <mutex>
#include <condition_variable>
#include <deque>
template <typename T>
class BlockingQueue
{
private:
std::mutex d_mutex;
std::conditi... |
Follow up to This Question
I took some very good advice and changed my code around a little bit and eliminated some If statements.
I am not retrieving very much information but it looks so skinny now.
Is this a good thing? Is there something that I should add to the code?
Dim phoneNode
Dim phoneNodeList
ReturnData ... |
I am doing a project where I am analyzing a group of Tweets.
What I need to do is find the occurrence of each individual word. I am fairly new to Redis, so I am not quite sure that my solution is optimal. I am storing a key value pair for each word. The key is a word, and the value is the occurrence count. I then use ... |
I have the following SQL query which takes ~3 seconds to run, maybe ~4. This populates a consultants table with their expected payments for the month.
Unfortunately, the page only loads when this query is finished. Is there any way to make it quicker?
Is there anything you notice that I could do better or any best pra... |
Below is a function from a driver that I wrote for and I2C temperature sensor.
The function takes as input the name of the bus and the device's bus address, reads it's status register, and then reports the status verbosely. (It also returns a values of interest, but that's not important now).
I have two questions abo... |
On my application I use this method to store and to output the data. I would like to know if it is safely and correct.
##store the data###
//sanitize
function clean($testo)
{
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$testo = $purifier->purify($testo);
$tes... |
We have recently started working in ASP.NET and starting a simple CRUD Web application in ASP.Net. Here is the approach we are following to connect to DB.
Connection.cs
public class Connection
{
public SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CWConnectionString"].ConnectionStri... |
This is my code for finding the nearest city within a certain radius. I am not sure, is my code is OK or is it wrong? Please review and offer suggestions on my code.
<?
//Suppose,I have selected a city and fetch the selected city's lat and long and radius
//in to this page.
$file_handle = fopen("Londonstations.csv", "... |
I have an initial list that contains: 1,2,3,4,5,6,7 I want to create an array of StringBuffer that contains only 3 items per element as StringBuffer(String):
1,2,3
4,5,6
7
Initially I resolved this problem as in the following example, but I don't want to use another list to do that:
List accounts = new ArrayList();
Li... |
I am using the code below to capitalize words in a string. I do not want conjunction words capitalized, but always want the first character in the string to be capitalized no matter what the word is. Is this the most optimized way of accomplishing this? How could this be improved?
xText = queryForHeading
xTextSpli... |
I'd like my code to be solid and good. That's why I want someone a little more experienced to give me some feedback so I can improve. Here is the code for a simple stop watch that I created. I feel the code is a bit clumpy and big so that's why I want to get feedback on how to make it more efficient.
Compiled (runnabl... |
I've a lot of code blocks that hide/show some block.
$('#Back').on('click', function () {
$('#FormRow').hide();
$('#TableRow').show();
});
$('#AddLanguageShow').on('click', function () {
$('#FormRow').show();
$("#TableRow").hide();
});
$('table').on('click', 'button.edit', function (evt) {
$('#Fo... |
I have this script to pull data out of the Filepicker API internal. It's mostly reverse-engineering and the code seems to be ugly to me. How can this be improved?
yesterday = (Time.now - 1.day).to_i
start_date = "08/08/2013".to_time.to_i
url = URI.parse("https://developers.inkfilepicker.com/login/")
http = Net::HTTP.n... |
I have recently been asked to do a test prior to an interview to test my C# skills. I am fairly new to C# (6 months) and I think this showed with me producing an overly complex answer to their questions.
I will post the 3 questions below as well as my answers. Please can someone give me a better solution to this. I ... |
I'm working on a parsing engine as part of a personal project, and I'd like to expose certain .NET APIs to the parsed environment. I put together a very simple tagged union that allowed me to nest types, and put together a few functions that built up a tree of namespaces. Before going further, I decided I needed to ref... |
I was curious which way is generally preferred, or if there is even a preference, given these two options:
$.ajax({
url: '../Component/GetSearchFilters',
success: function (response) {
console.log("Outer scope:", this);
}.bind(this)
});
If I was inside of a function where I needed both "this" and o... |
I'm trying to rewrite this:
def flatten(lst):
flat = []
for x in lst:
if hasattr(x, '__iter__') and not isinstance(x, basestring):
flat.extend(flatten(x))
else:
flat.append(x)
return flat
In [21]: a=[1, [2, 3, 4, [5, 6]], 7]
In [22]: flatten(a)
Out[22]: [1, 2, 3, 4... |
I've got a minimal implementation (under 2k minified) of the Asynchronous Module Definition API. So far it handles all of the required stuff (I think; it passes the relevant unit tests, anyway), and none of the optional stuff.
I haven't looked at any other implementations yet, but I'd love to hear feedback from someone... |
I am using the code below to capitalize a string properly. I would like to know if there is a better way to code the surname portion, as the way it stands now can become very bloated depending on how many surnames I plan on adding.
This is a follow up to: Capitalize string except for conjunction words
Dim conjunctions
... |
It is not always possible to simplify program design by strictly managing the lifetimes of objects. If two objects have unpredictable lifetimes, but one of them needs to refer to the other, a simple pointer or reference is a segmentation fault waiting to happen.
One solution would be to allocate the object being track... |
I wrote a small program that aims to take some data from the MongoDB database and put them in the RabbitMQ queue.
I tried to use only promise style but I am a beginner in JavaScript. Could you please help me to improve my first draft?
var mongo = require('mongod');
var amqp = require('amqplib');
var _ = require('unders... |
Someone says that my PHP code is vulnerable to XSS. I asked them what I should do to fix it, but now they don't want to help.
$action=$_REQUEST['action'];
/* send the submitted data */
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name==""... |
I designed this layout in Balsamiq for my ProfileActivityand I tried to replicate it. The screen on the left fits the correct proportions, whereas the screen on the right has a stretched out view of all the content in the activity.
Am I overusing RelativeLayouts? Is there a much easier way to make this? How can I make... |
Taking inspiration from SICP Exercise 2.1, I decided to implement a module in Haskell for rational numbers.
Some of my concerns include:
Is this idiomatic Haskell?
Besides Num, Eq, Ord, Show, and Read, are there other typeclasses I should be implementing? I've got "free-floating" functions toInteger' and rationalDiv.... |
I have to extract friendlyName from the XML document.
Here's my current solution:
root = ElementTree.fromstring(urllib2.urlopen(XMLLocation).read())
for child in root.iter('{urn:schemas-upnp-org:device-1-0}friendlyName'):
return child.text
Is there any better way to do this (maybe any other way which does ... |
I created a user defined literal _c to convert an "integer" literal into an std::integral_constant. Basically, the goal is to allow users to write std::integral_constant instances without the usual boilerplate. Here is the implementation:
#include <type_traits>
template<typename T, typename U>
constexpr auto pow_helpe... |
Please tell me how I could have done this better. The code is here on Github.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write some message on the display.
# This project uses https://github.com/dbrgn/RPLCD.
# sudo apt-get install python-matplotlib
from __future__ import print_function, division, absolute_import,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.