instruction_seed stringlengths 71 95.1k | _source stringclasses 1
value |
|---|---|
While checking my SPs today I found that I have,
SELECT COUNT(*)
,CASE WHEN ISNULL(MIN(COALESCE(MP.NewPrice, MP.Price, 2147483647)),0) = 2147483647 THEN 0 ELSE ISNULL(MIN(COALESCE(MP.NewPrice, MP.Price, 2147483647)), 0) END
FROM MerchantsProducts MP
I need to replace this with something which make more sense. Can ... | stackexchange/codereview |
The chart data is stored in a nested dictionary struct @line_charts, and I need to convert the prices to target currency with the function exchange_datasets_currency. It should finally return the @chart in the end of method.
Is there any way to improve my pattern?
def sample_a
@line_charts = [get_line_chart(@from, ... | stackexchange/codereview |
I am writing a Model to read, write and store settings.
I think my code is pretty good, but I am not 100% sure.
Any advice on how I could possibly improve it is welcome.
import ntpath
import yaml
class Settings:
def __init__(self, paths=None, default_path=None):
"""Load, write and store settings
... | stackexchange/codereview |
Below you can find a Kotlin based implementation of the Knuth-Morris-Pratt substring search algorithm.
class KnutMorrisPrat(R: Int, private val pat: String) {
private val m = pat.length
private val dfa: Array<Array<Int>> = Array(R) { Array(m) { 0 } }
constructor(pat: CharArray) : this(256, String(pat))
... | stackexchange/codereview |
Follow-up to Python program to find a word ladder transforming "four" to "five"
I'm trying to write a program to solve a word ladder puzzle to brush up on my Python. For those who don't know:
A word ladder puzzle begins with two words, and to solve the puzzle one must find a chain of other words to link the two, in wh... | stackexchange/codereview |
This is my first question here and I'd like to get some feedback. The program works but I'm not sure the classes I've used are right.
First, a class to calculate the Body Mass Index from a double (kgs) and an integer (height in cm):
//Data taken from https://codereview.stackexchange.com/questions/216933/java-swing-exer... | stackexchange/codereview |
I wrote a partial implementation of Snake in Haskell. As of now, it only supports the movement of the snake. However, since the code is getting complex, I'm requesting for a review of the code before I add on the food, growing and scoring functions.
I'd be glad to hear any suggestions on how this code could be written ... | stackexchange/codereview |
I wanted to store some dictionary data (key/value pairs of strings) in C, and decided to use a trie.
I found what looks like a good implementation here, along with some nice notes.
In this implementation, each node in the trie is a trie itself. Each node has next, prev, child, and parent properties, pointing to other n... | stackexchange/codereview |
I have a comments page on my site and I was wondering if it is vulnerable to some sort of sql attack or something else. At the moment users can type what they want, they can even write a php script and it will upload to the database. Is this a problem and how can I fix it.
This is the script I use:
$name= $_POST['name'... | stackexchange/codereview |
Consider this setup:
class UtilityClass
{
public function formatNumber($input) {
return number_format($input, 0, '', ' ');
}
public function trimText($input) {
return substr(trim($input), 0, 100);
}
// bunch of other methods
}
class SessionClass
{
public $utils;
private $p... | stackexchange/codereview |
Premise
I have written a function in VBA, called FILTER_RANGE(), which accepts a Range object and a filtration parameter. Unlike the existing FILTER() function, this FILTER_RANGE() will return a Range object: the subset of the original Range that was preserved by the filter.
"Filtering a Range"
To clarify what I mean b... | stackexchange/codereview |
Can someone please go through this?
#include <iostream>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <set>
#include <cmath>
#include <cstring>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <stdlib.h>
#include <vecto... | stackexchange/codereview |
At the moment I'd like recommendation where I can change and what I can use to improve on simplicity and modularity. If I'm practicing good naming conventions as to provide clean readable code. Any critique is much appreciated.
import time
import re
import requests
from bs4 import BeautifulSoup, SoupStrainer
import pa... | stackexchange/codereview |
I'm new to web development and this is my first website. I was wondering if my login and registration system is secure. I was also wondering how to handle viewing parts of a webpage when the user isn't logged in (ie. hide a section if the user isn't logged in). Sorry in advance if there's irrelevant stuff in the code.
... | stackexchange/codereview |
When scraping and saving data into a file, Which method is more efficient when saving scraped data to a file?
open the file first, scrape, and save the data all while the file is opened, or
store the data into a dictionary and then save it to the file?
For example, the following two scripts scrape data from Yahoo Fin... | stackexchange/codereview |
This is a simple web form handler in PHP that sends a completely filled web form to a email.
I see lots of repeating code. What is the best way to reduce repetition?
Is my way of checking for fields being empty good? The "empty()" method seems to also treat "0", "0.0" and similar values as empty.
Am I doing something ... | stackexchange/codereview |
I need to delete a file when an error occurs during loading it. It is not allowed to perform async operations in a catch block.
This has lead me to writing the following code:
public async Task LoadFromStorageFile(string fileName)
{
StorageFile file = null;
Exception ex1 = null;
... | stackexchange/codereview |
I created a function that filters data and I want to know if it's fully secure to filter user input data.
function user_input_data($data,$options) {
$output = null;
$error_msg = "";
$check_length = false;
$options_fetch = array(
@$length_max = $options["length_max"],
@$length_min = $options["len... | stackexchange/codereview |
I'm new to using JS for anything other than DOM manipulation, so I'm not sure if the following code is taking full advantage of the Async concept in JS.
This is an example of a function I'm writing in my Discord.js bot project. The function checks for new RSS feed items from a given URL and then calls another function ... | stackexchange/codereview |
I read this article that I really liked and wanted to implement the ideas it had. It basically says don't use $scope or ng-controller; instead, use directives with templates that get their angular magic from the directive's controller.
angular.module('myAppContestantList', [])
.directive('myAppContestantList', functi... | stackexchange/codereview |
Now that async generators are available in the platforms I care about, I figured I'd try porting Python's ingenious with construct to JS as a utility. My first stab looks like this:
type Index = string | symbol | number;
function isIndex(obj: any): obj is Index {
return (
typeof obj === 'string' ||
... | stackexchange/codereview |
I have a set of directories. For each directory I have a set of relative file names. I would like to select any of these relative filenames using completion, and then later reconstruct the absolute path of the filename.
In order to create a list of relative filenames for a given directory, I created this function:
(de... | stackexchange/codereview |
I am a beginner trying to fetch a random line from a file and wondering if this code can be improved. Should I use try and catch in this case? Should I take a parameter for the function "quote"? How can I take several alternatives for searchText? (E.g. "hello", "hi" or "hey" but one is enough to return true.)
def getI... | stackexchange/codereview |
I do most of my programming in C/C++ and Perl, but I currently learning Fortran. I began by coding up a simple program, something that took me < 5 minutes in Perl (see this thread from BioStar). After working for several hours on a solution in Fortran 95 (teaching myself as I go), I came to this solution.
implicit none... | stackexchange/codereview |
I have an application that needs to validate user passwords to a very reasonable custom validator, which is heavily based on NIST-2017 requirements. The validator intends to satisfy the following restrictions:
At least n characters (default n is 12);
No more than n sequential, neighboring digits, things like 123, 1212... | stackexchange/codereview |
This is my first Powershell script ever so bear with me.
I'm trying to replace values in a sharepoint list from a CSV file:
Param(
[Parameter(Mandatory=$true)][string] $csvFileName = $null,
[Parameter(Mandatory=$true)][string] $sharePointWebUrl = $null
)
$isError = $false
cls
$csvFileName = $csvFileName.Tr... | stackexchange/codereview |
Is there any simple way to improve this revamped code from an earlier version? I am looking for improvements that are SIMPLE, not more that post-advanced please.
import time
import os, signal
#Username = '_'
A = '''
<!DOCTYPE html> is the declaration tag for a standard HTML
document. This is used to tell the browser... | stackexchange/codereview |
I wrote a function to generate a complicated version of the pascal triangle. The generated triangle should look like that:
┌─────────┬───┬───┬────┬────┬────┬────┬────┬───┬───┐
│ (index) │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │
├─────────┼───┼───┼────┼────┼────┼────┼────┼───┼───┤
│ 0 │ 1 │ │ │ │ │ ... | stackexchange/codereview |
Input:
Enter a decimal number: 101
Output:
The binary number is : 1100101
I have solved this way->
#include <stdio.h>
int main(void){
int input=get_input();
long long complete_integer=binary_conversion(input);
reverse_digits(complete_integer);
}
int get_input() {
int number = 0;
printf("Enter a decimal numbe... | stackexchange/codereview |
I'm kinda new to javascript and have question about it. Now my practical project is growing a bit bigger. I got the following if else statement. Is it possible to refactor this ? Should i use an use case or are there other options or will this decrease the loading speed of the application.
(function () {
'use stric... | stackexchange/codereview |
This is an interview question.
For the purpose of the question, a valid English word is a string that begins with an uppercase English letter, and the rest of the string contains only lowercase English letters. I needed to implement two functions:
A function that receives a String and returns true if the ... | stackexchange/codereview |
I have implemented an nth prime algorithm in Rust that uses value lookup for n < 6, trial division for n < 1000, and a sieve function for n > 999. How can it be better optimized?
pub fn nth(x: u32) -> Result<u64, String> {
match x > 0 {
true => match x {
1 => Ok(2),
2 => Ok(3),
3 => Ok(5),
... | stackexchange/codereview |
I was just wanting a code review on this image slider I made. I don't have anyone else to give me their opinion on the code I write outside of work.
Is this sloppy? Is it wrong? Is it ineffective? Does it have bad performance?
You can see my repo on the slider here.
deitySlider.js
var deitySlider = {
init: fun... | stackexchange/codereview |
The story here is about a console application that replays to a test system string clauses already imported in the production system.
Looking forward to your comments.
namespace MyCompany.Department.ProjectXYZ;
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
usi... | stackexchange/codereview |
I am working on a photo editor, which displays a preview to the user on a canvas. At various points in the app, the user may use sliders to adjust properties of the photo, such as scaling, rotation, etc. The preview needs to be updated in real time, as the user drags the slider.
As I understand, pointer events are fire... | stackexchange/codereview |
This program attempts to solve the following challenge:
There is a 2D grid of cells containing N lamps. Each lamp illuminates its own cell as well as its eight neighbours. How many lamps can you possibly remove such that each cell that was originally illuminated remains illuminated?
My code:
import java.util.*;
cla... | stackexchange/codereview |
Given a large bounding rectangle ("envelope"), a list of points, and a maximal aspect ratio, the goal is to find a rectangle within the envelope, whose aspect ratio is bounded within the given aspect ratio, that contains a largest number of points from the list.
For example: if the envelope is the rectangle with corner... | stackexchange/codereview |
I have a common List in mind which looks something like this:
it has one remove button
one input in which user can enter the name of element and on clicking insert the element will be added in the list.
For this i have added HOC like this:
function ListHOC(Component, data, listName, placeholder) {
return class exte... | stackexchange/codereview |
The issue I have with this class is that most of the methods are almost the same. I would like for this code to be more pythonic.
Note: I plan on replacing all the for loop constructs with list comprehensions.
class Sorter(BaseCrawler):
def __init__(self, base_dir):
self.base_dir = base_dir
def by... | stackexchange/codereview |
The following Awk code was created in order to verify if free memory from the top command is less than 20% of the total.
I've noticed that I actually do not need the top -n1 | grep Mem |, because the FREEM and TOTALM parameters are inside the third awk line.
But on the other hand, I could not run the Awk as:
awk -v FR... | stackexchange/codereview |
I have a DataFrame of data from a survey that was repeated over several years, asking people about their income and how much money they had in savings. For simplicity, let's pretend it looks like this:
In [1]: nominal.head()
Out[1]:
year1 ... year11 income1 ... income11 savings1 ... savings11
0 1992 ... NaN... | stackexchange/codereview |
I have a list of 6 items, and each one on click reveals a div that runs 100% wide under the row of list items. The code works, but the div opens very slowly and kind of choppy. Is there anything I can do to help it run more smoothly?
My HTML is set up as such:
<ul>
<li><a class="artist-logo" href="#arti... | stackexchange/codereview |
I have wrote some service in AngularJS that use defer, can you check my code and tell me if I getting it right?
Service (I dont really like name: WatchableTeaser, have you got another?):
.factory('Teaser', function ($resource, DateUtils) {
return $resource('api/teasers/:id', {}, {
'query': {method: 'GET', i... | stackexchange/codereview |
This question contains some C# code I've written as well as a XML format I have designed. My C# code runs a series of "jobs" by loading the XML file and then calling different SQL stored procedures and E-Mailing the results to different addresses. My question specifically relates to the C# code to parse the XML documen... | stackexchange/codereview |
This is a custom case insensitive nested dictionary class created by me, its main usage is to populate QTreeWidget and keep track of said QTreeWidget, the main incentive behind this class is to prevent case insensitive duplicates from entering the tree, and to report the indexes of the nested keys (d = {'a': {'a': {'a'... | stackexchange/codereview |
The idea with this script is to provide a way to work with configuration (xml) files for PowerShell scripts. These files may contain credential information which needs to be secured; those would be held under a special element name, Credential. Someone setting up the configuration file could set it up with the passwo... | stackexchange/codereview |
I've created a dictionary subclass with a set of default immutable keys.
from collections import MutableMapping
class Bones(MutableMapping):
"""Basic dict subclass for bones, that forbids bones from being deleted
and new bones from being added."""
def __init__(self, init_val=0):
self.bones = {"bet... | stackexchange/codereview |
This is a follow up on this question and has now a follow up question here.
I have implemented some changes to the class below and also added the method AddChildRange() to the ArchiveTreeEntry class.
I have kept the method as static, as this method is the only purpose of this class, and none of the passed items will be... | stackexchange/codereview |
disclaimer: I've posted this around but the question keeps being put on hold for being inherently opinionated which I understand, just looking for some vague direction as to how a more experienced developer would approach this problem. I think this is the right place based on what I'm asking and I apologize if not.
So ... | stackexchange/codereview |
Edit for posterity: The library you're looking for is Hspec.
I recently started writing Haskell tests with HUnit.
My general setup looks something like this:
import Test.HUnit
import Widget (foo, bar)
tests = TestList [ "foo" ~: testFoo
, "bar" ~: testBar
]
testFoo :: Test
testFoo... | stackexchange/codereview |
Please review my pointer class.
template<typename T>
class Ptr {
public:
Ptr(T* t, int s = 1) {
sz = s;
p = new T[sz];
for (int i = 0; i < sz; ++i) {
p[i] = t[i];
}
}
Ptr(const Ptr&) = delete;
Ptr& operator=(const Ptr&) = delete;
Ptr(Ptr &&t) :p{t.p}, sz... | stackexchange/codereview |
I'm trying to develop a simple program to evaluate integral powers of a complex number \$z\$ , that is, \$z^n\$, where \$z\$ is in the algebrical form \$a+i b\$ and \$n \in \mathbb{Z} ^{*} _{+}\$.
How I was trying to proceed:
First, I defined a product function, and next I intended to define a exponentiation function ... | stackexchange/codereview |
I'm looking for tips on how to clean up this code and/or make it more efficient.
Keep in mind I am a seriously new programmer and if it is too advanced it's likely to go over my head.
import random
cscore = 0
pscore = 0
print 'I would like to play a game. \nThe name of the game is Rock, Paper, Scissors.'
rest = 'y'
whi... | stackexchange/codereview |
One of the servlet in my web app takes parameters in the form www.service.com/servletname/parameter1/parameter2.
The first parameter is required and the second parameter is an integer.
I've made some code to validate the parameters but it looks really really messy. Is there a nicer and cleaner way I can write the foll... | stackexchange/codereview |
This is a follow-up question to My last question. From then on, I think that I have improved quite a lot thanks to a large amount of feedback I received from my last post. This will be the last time I ask for feedback based on this code. I am looking for any feedback on best practices or coding style but to be honest a... | stackexchange/codereview |
I am looking to submit the following code (adapted to fit into java.util obviously) which significantly improves performance and reduces useless allocations of java.util.UUID. Help me find the bugs and stupidity before I submit myself to the judgment of the JDK maintainers! :-)
benchmark instances Bytes n... | stackexchange/codereview |
pandas.DataFrame.insert can only handle an int for it's loc kwarg this is inconvenient for the user with medium to big data. In an attempt to solve this problem temporarily for my development environment I have come up with the following methods. I'm testing out as hot patches but I plan on implementing them in my fork... | stackexchange/codereview |
I need to select some "work types" from a channel. These "channels" are in "work groups" and both channels and work groups need to have permissions to view them (tables are ChannelUsers and WorkGroupUsers to check this). The views that can be selected are as such:
this.views = {
"*" : ["*"],
"index" : [
... | stackexchange/codereview |
Writing an EventLoop in C++. Few requirements, from a user perspective:
Must be simple to use (as simple as the Javascript event loop)
No type casting, no complex registering of event handler. Plain and simple API.
Event handlers have the proper event type passed to them as reference.
Should be able to register handle... | stackexchange/codereview |
Given a set of overlapping boxes, and a set of points, I'd like to be able to determine which of the boxes contain each point. The number of points is much larger than the number of boxes, and I'd like to do it faster that brute force, so I'm trying to do it with a map-like structure.
My current attempt is below, it se... | stackexchange/codereview |
Here is a small script I wrote to get the HNews ask section and display them without using a web browser. I'm just looking for feedback on how to improve my style/coding logic/overall code.
#!/usr/bin/python
'''This script gets the headlines from hacker news ask section'''
import urllib2
import HTMLParser
import re
... | stackexchange/codereview |
So I've made a button in the right-bottom corner of my HTML-page, but I was wondering since it's the first time I've made this, if there is another better way to do this, or if you guys can see anything funky about the way I did this?
This post is mostly to learn how to do things the right way, since I'm a beginner at ... | stackexchange/codereview |
I have this small program for learning an artificial neuron to act as a simple signal counter: my cell has four input wires (also called dendrites) and a single output wire (also called axon). If at least two input signals are strong enough, the axon is activated. I consider the neuron to be learned as soon as it "gues... | stackexchange/codereview |
The function validates whether the input is an int, is there a way to make this more concise and is it best practise to use the try/except or just if/else? I then want to create a similar function for checking whether the input contains letters only using isalpha()
def int_validation(prompt):
"""
Validate the g... | stackexchange/codereview |
I'm currently learning rust and need a rocket file upload enpoint for a project.
This is what i currently have:
It needs to get the file, convert it and add a entry with the file name and timestamp to a database.
#[post("/upload?<auth>", data = "<file>")]
pub async fn upload(
config: &State<Config>,
... | stackexchange/codereview |
I would like to modify my shortest path finding code to use multithreading and improve its performance. The algorithm must be able to work with negative weights, and as a result, we cannot use Dijkstra's algorithm. Instead, our approach combines three algorithms: Bellman-Ford, SPFA_Queue (shortest path fast algorithm, ... | stackexchange/codereview |
This code checks if the given integer is a palindrome. If it is, prints given integer is a palindrome else, not a palindrome:
from collections import deque
def polindrome(input):
d = deque()
d.extendleft(str(input))
result = int(''.join(d))
if input == result :
return input , 'is a polindrome'
else :
ret... | stackexchange/codereview |
The code below implements a brute force method to find an energy optimal path for a given amount of time t_aim using recursion (the recursion function is optimalPath).
It seems the code works as expected. The transition energy and time is provided by transEnergy and transTime. v_tmp holds indices to the found transitio... | stackexchange/codereview |
I have a small Person Domain Model as follows:
public class Person
{
public Person()
{
FirstName = "John";
LastName = "Doe";
BirthDate = DateTime.Now.AddYears(-18);
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid PersonId { get; set; }
[Max... | stackexchange/codereview |
I have this logic that I wanted to see if there is any better way to build this select control. I am using the includes to look for data in the array and then I have a if statement to build the selected flag.
$.each(guidelineMeetingDates, function (index, value) {
var b = selectedMeetingDates.includes(value.Meetin... | stackexchange/codereview |
I have a controller action that takes JSON bodies. I know, that the JSON is either of type A or B, where both classes are of interface IModel.
[HttpPost]
[Route("api/post/")]
public IHttpActionResult MyPost([ModelBinder(typeof(MyModelBinder))]IModel viewModel)
{
doSomething(viewModel);
... | stackexchange/codereview |
I've been writing a small Rust module recently with the sole purpose of speeding up my Python program, which is a Conway's Game of Life simulation. The function written in Rust is called from Python using the maturin package and PyO3 crate (on Rust's side).
I've come up with a working prototype, but there are still a f... | stackexchange/codereview |
I'm using an LC3 microarchitecture simulator to write assembly code. I've only been writing assembly for about three weeks, so I am still very new.
My goal is to print all the numbers leading up to a set value, so for example, if the user selects '6' the console prints 012345. My code works, but the unit test says my c... | stackexchange/codereview |
I implemented the nice linux command. How can I improve the program? In terms of optimization, error handling, bugs and possible undefined behaviors
#include <stdio.h>
#include <sys/resource.h>
int my_nice(int incr)
{
/* adjusts the nicess value of a process by +incr.
Returns -1 on failure.
Returns n... | stackexchange/codereview |
I want to create a wrapper around this third party package class so that I don't litter my app with calls to it. The idea being that if there are breaking changes to the package (rename the class or one of its members), or if I want to delete the package, I can just change my implementation of it in this one file. Here... | stackexchange/codereview |
I'm not sure if anyone else has ever heard of Factman, or even where the name comes from, but my AP Computer Science teacher calls this project Factman, so that's what I'm going with.
Naming aside, the game is simple. Players take turns choosing from a list of numbers. They get the number added to their score, but th... | stackexchange/codereview |
For the past four years I've attended a private school which requires its students to wear ties. I've found that it's far easier to figure out what combination of shirt, pants, and tie that go together the night before, as it can sometimes be a tedious process. To make this process simpler, I had the idea to create a s... | stackexchange/codereview |
This is a pretty basic bash script (3.2 on Mac). I am downloading 584 images from a site in order to create an album.
#!/bin/bash
urlFirst="http://150.216.68.252:8080/adore-djatoka/resolver?url_ver=Z39.88-2004&rft_id=http://150.216.68.252/ncgre000/00000012/00011462/00011462_ac_0"
urlSecond=".jp2&svc_id=info:lanl-repo/... | stackexchange/codereview |
I found a bit better implementation for Java Arrays.sort(int[]). To make this code review more simple I divide this questions to several parts.
The goal of this question is to find more ways to increase the performance even better.
Edit: Tested over Java 6, win 64 bit. In average for equal redistributed input(did not t... | stackexchange/codereview |
Which unit testing approach and WHY do you prefer?
Inheritance-driven-testing
public class GivenSynchronizedDataLink : TestBase
{
internal SynchronizedDataLink Subject { get; private set; }
protected Mock<IDataLink> DataLinkFake { get; private set; }
protected Mock<IAutoReaderWriterLock> ReaderWriterFake {... | stackexchange/codereview |
I have product results with some filter, and the one is category. I'll get the category list from product results. the model category and products is one to many relationship.
This is the search query:
$results = Product::where('available','=', 1)->whereRaw('stock_available > min_quantity');
$results = $results->where(... | stackexchange/codereview |
I'm a beginner in the coding world, and I've been learning Java recently. I tried to make a small text game with the limited knowledge that I currently have of Java. I would like you to tell me ways to improve my code, so that I can learn it better. I currently feel my code is a bit messed up, but at least it's a start... | stackexchange/codereview |
This is a challenge up on Programming Praxis, however there are no Java solutions, and there are few Java implementations elsewhere on the internet.
Most of these implementations simply search the grid for the words that the user is supposed to find. This program finds ALL of the dictionary words that are in the word ... | stackexchange/codereview |
On my page I have a mouseup eventlistener on document. I want to be able catch if the clicked elements has a specific id in any of their parents.
What I'm doing now is to loop over the e.path and only push the ids to an array and from there check if the array includes that id (the id is: getme). You can see the code be... | stackexchange/codereview |
New to Neural Networks and before I move on to gradient descent I would like to make sure I have got basic idea right. (Sorry that the class is called perceptron I know that this isnt technically right, I adapted this code from
and AND gate NN). This NN is made to learn the XOR function.
#include <iostream>
#include <... | stackexchange/codereview |
I am working on an implementation of the Needleman-Wunsch sequence alignment algorithm in python, and I've already implemented the one that uses a linear gap penalty equation for scoring, but now I'm trying to write one that uses an affine gap penalty equation.
I tried using as a reference the chapter that covers this ... | stackexchange/codereview |
I shall make a JavaScript-function which does the same as PHP's array_diff:
http://php.net/manual/de/function.array-diff.php
Because it is intended to use the function as a (internal) library-function I have tried to catch everything which could possibly go wrong concerning incorrect usage.
Moreover I've tried to docum... | stackexchange/codereview |
Is this image uploading script safe? I have spent my day researching this and it would be very much appreciated if you could point out any errors or ways to make it safer.
<?php
$max_file_size = 1048576; // expressed in bytes
// 10240 = 10 KB
// 102400 = 100 KB
... | stackexchange/codereview |
The following code solves Project Euler Problem 121. I will quote the description of the problem
A bag contains one red disc and one blue disc. In a game of chance a player takes a disc at random and its colour is noted. After each turn the disc is returned to the bag, an extra red disc is added, and another disc is t... | stackexchange/codereview |
Create a simple function that given 3 inputs - number 1, number 2 and operator - calculates the result. The function supports DMAS operations, and accepts only integers
Is there a better way of solving this problem?
#calculator
def calculate(x , y , op):
if op == '+' :
z = x + y
elif op == '-' :
... | stackexchange/codereview |
What would be the best way to refactor this :
@busy.each do |b|
title = b.title
@events << {
:id => b.id,
:title => title,
:start => b.busy_start_time(b.start_date,b.start_time),
:end => b.busy_end_time(b.end_date,b.end_time),
:allDay => false,
:recurring => false,
:color => 'black',
... | stackexchange/codereview |
The question is:
Given a non-negative int n, compute recursively (no loops) the count
of the occurrences of 8 as a digit, except that an 8 with another 8
immediately to its left counts double, so 8818 yields 4. Note that mod
(%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/)
by 10 removes the right... | stackexchange/codereview |
I found the following challenge online:
Create a function that takes a string and returns that string with the first half lowercased and the last half uppercased.
eg: foobar == fooBAR
If it is an odd number then 'round' it up to find which letters to uppercase.
That sounded easy enough but I found the last requiremen... | stackexchange/codereview |
#include <stdio.h>
#include <stdlib.h>
#define RED "\x1b[31m"
#define GREEN "\x1b[32m"
#define YELLOW "\x1b[33m"
#define BLUE "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN "\x1b[36m"
#define RESET "\x1b[0m"
int main () {
int n1 = 1, n2 = 0, i = 0, limit = 0, neg = 0, pos = 0;
printf("En... | stackexchange/codereview |
I've been working on a large Ruby on Rails application for several years. We inherited it and refactored and upgraded it, but there are some sections that have not been touched in at least 5 years (parts created by the original developer(s)). One such section is payment processing code. The code works for the most part... | stackexchange/codereview |
I wanted to convert C++ data structures to JSON with little code. More specifically, I wanted to convert C++ data structures to nlohmann JSON representation.
Project context: The goal is to use this in a somewhat large professional application (~50k code-lines) deployed for years in a not so critical product. I'm just ... | stackexchange/codereview |
I've been thinking about error handling in C++ lately. Exceptions are a great way of handling errors in most applications. However, I work in the games industry where it is commonly accepted that exceptions should be avoided, so I'm looking for a clean and simple alternative. (The validity of avoiding exceptions in gam... | stackexchange/codereview |
I'm working on a linked list to save the information of students. I can insert anywhere on the list, delete and sort it. Now i'm reviewing the code to try to simplify it somehow. I don't know if the .c's and the .h's of the project are correctly arranged.
The program complies and runs as it should.
Do you think the me... | stackexchange/codereview |
I've implemented a small single-header library over the C++20 coroutines. This library only works on a single thread and it is limited to Linux because it is also based on epoll.
The library does not implement C++ exceptions in any way.
A feature of the library is that you can add "modifiers" to coroutines. If present,... | stackexchange/codereview |
PLEASE NOTE:
The code below has "commented out" code; however, no code is actually commented out!! Check my GitHub link below. I did that solely to highlight the relevant code sections. Code in my MainActivity and BaseCalculatorActivity, for example, are tightly linked to Android. Those are irrelevant to the alternativ... | stackexchange/codereview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.