instruction stringlengths 71 71.9k |
|---|
I'd like to have neater URLs, no more and no less — I'd like to be able to write /page/subpage instead of something like ?p=page&s=subpage.
I've looked at various PHP frameworks and routing classes to see how they did it. Since most of them come with features I don't need, I wanted to try making my own system using onl... |
I'm trying to write my first "complex" program in Java. So far, I created a local H2 database but I'm not sure about the quality of my code (I'm newbie in Java) because I don't know how I can deal with exceptions and I don't feel comfortable with the JDBC code.
public boolean create(Project project) {
String id = UU... |
I want to check if some line ends with any substring defined in some list. Is there a better way than following one?
endsA = ['foo', 'bar', 'fur', 'beer']
endsB = ['door', ... ]
def checkEnds(line, ends):
for end in ends:
if line.endswith(end):
return True
....
if checkEnds(line, endsA):
... |
I'm trying to create a class to connect to Redis in Express. I don't think my code is good enough as I got variable db hanging out.
'use strict';
var redis = require('redis');
var bluebird = require('bluebird');
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
var debu... |
The scenario is as follows. The API of my program will allow the user to perform some method on a particular element (let's say a tuple from a database). If this parameter is not passed to the function, then the "default" behavior is to look for a list of elements (from a database query, for example) and to act on all ... |
I wrote a Simon clone in JavaScript, HTML, and CSS. It's extremely simple, but turned out fairly well.
I'm looking for general feedback, as well as these things specifically:
I opted to try to do any required animation manually, instead of relying on jQuery. I wanted to see what went into animations. The only animatio... |
The script works but I know that it can be improved. Please note that my scripting skills are very basic :) (as it can be seen in my Frankenstein script – I took bits and pieces of the code from different tutorials).
I would appreciated if someone could review this script and identify some major flaws.
Some other quest... |
This is the question from Oracle docs:
Write a generic method to find the maximal element in the range
[begin, end) of a list.
I had my implementation like this:
public static <T extends Comparable> T maximalElement (List<T> list, int from, int to) {
T max = list.get(from);
for (int i = from + 1... |
I'm just trying to understand and use unit tests, which from what I can tell is exposing the issues with my code. A lot of what I do is MVC/WebAPI. One of the big issues I come across is that my methods end up too long, doing too much, which makes it very difficult to test them.
Description of what the code is for:
... |
A while back this question proposed a constexpr compile-time Sieve of Eratosthenes. It also linked to another SO question about compile-time computation of CRCs. I've found a place where I'd like to precompute the hash of a few C-strings, so I used those previous questions as a base.
I'm implementing the one-at-a-time ... |
I've started to use extension methods to provide data layer functionality in our project. Our project is an MVC website using Code First Entity Framework. So, I've done things like this:
namespace OurProject.Models
{
public class Project
{
public int ProjectId {get; set;}
public string ProjectNa... |
I've created my first ReactiveUI app in WPF.
Simply, the user enters their full name in one textbox, and then the name gets split into its parts and displayed in the other textboxes. This is just an example ... I realise parsing names is often futile!
MainWindow.xaml:
<Window x:Class="TestHumanName.MainWindow"
... |
I'm a beginner and like to experiment new things so today I tried to implement sorting method for an array without using any Sort and the actual challenge was to do it without using the bubble sort algorithm. I created my own but I feel that there are some things that can be shorten because it's quite long. My main ide... |
I am filtering array of objects with object properties provided by the user. The goal is to return an object property 'label' by matching the property 'value'. 'input' provided to the function can be either array of one element or many elements or not an array. I'm using lot of loops to accomplish this. Any suggestions... |
Reviewing code doesn't necessarily require actually building it, but it's often helpful to do so in order to evaluate fully. I usually create a CMake project and build from there. Since we're all about code here, naturally, I decided to automate part of the process. Specifically, here's how to use this code:
Hit... |
What is the cleanest way to use dictionaries and protect against an unhandled ArgumentException if the key already exists in the dictionary?
I'd like to say that I can always guarantee uniqueness upstream, but I'm dealing with legacy code and mildly corrupt data from an old bug in the system.
I find myself using this p... |
I would like someone to review my code and maybe give me some advice to maintain it because I'm still a beginner.
public static boolean NewTerrainCamPos = false;
public static String textVal;
public static String textVal2;
public static String resiveTex = "1";
public static String resiveTex2;
public static final int ... |
Is this a bad solution to the FizzBuzz thing?
I decided to make it print "Fizz Buzz" for the numbers divisible by 3 and 5 just for practice/understanding.
for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
output += "fizz";
if (n % 5 == 0)
output += "buzz";
if (n % 5 == 0 && n % 3 == 0)
o... |
Including the full module, but the method I'm interested in is createIndex, feels more complicated than I think it should be. Still new at both node and elasticsearch
/*jslint node: true */
'use strict';
var EsConnect = require('./EsConnect');
var inet = require('inet');
function NetFlowStorage(es, logger, config) ... |
I'm a bit of a neophyte when it comes to C++, and so I'd like some feedback regarding a recent project.
The code sits on a Raspberry Pi and streams camera data over TCP on a specified port.
The MJPGWriter class:
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
... |
I made a basic website to practice HTML and CSS that will display 3 fruits with their given scores in an Olympic podium sort of way.
Have I used any bad practices and what I should do instead?
What can I do to fully optimize and shorten my code?
How readable is my code? How can I make it more readable?
<html>
<head>... |
The goal is to show message for users that are less 25 years old. The personal ID consists of 081010333333, where 08year, 10month, 10date. I made code and it's very messy. So the question is: how to make it "right"? any advices and solutions are welcome. One on codepen and the code itself:
$('input').on('change keyup... |
In an effort to create ever-improving code, I've written a DelegateCommand that takes a generic type parameter to be acted upon. It's pretty trivial, so it should hopefully be easy to review.
In order to do this, I had to create two interfaces: IGenericCommand and IWindowsUniversalCommand.
/// <summary>
/// Requires th... |
I have an url and need to check whether it has some second-level domain (SLD) from a list. For example for SLD foo.com I need to approve hosts foo.com, some.foo.com and reject host kungfoo.com. There is some solution:
domains_a = ['foo.com', 'bar.com', 'fur.net', 'beer.org']
domains_dot_a = ['.foo.com', '.bar.com', '.f... |
Apart from merging the 2 get methods, what else can I do to optimise this?
Both input and output cannot be changed. Is there a way to iterate a map while writing to it?
// String condition - "cust" for customer group, "item" for itemGroup
public HashMap<String, ArrayList<PriceTable>> getPromoForViewGroup(
S... |
I need to do a card for showing some data. I had some problems with the blue left box on the left side, and to add custom paddings. It think I can add padding with a more simple way, but I don't know how. I don't want to use nth-child because it's not supported on old IE. I want an opinion about my code :
html
<table c... |
I am working on a source line parser using PPI. After working a while, I realized that
it would be nice if the PPI API had included such and such functionality. As a very simple example, the PPI::Element contains a class method that returns the class name of the current element. This method must be called quite often ... |
I have a file with more than 100k rows, but the structure is simple:
Date _|_Name-Position-Color_|_Summ
17.11.2015 |"Name1 | 8813,52
| Position1 |
_|_Color1" _|_
19.08.2015 |"Name2 | 3587,86
| Position3 |
_|_Color5... |
I'm using dapper-dot-net for data access in my ASP.NET MVC application.
So in order to supply a connection string I've came up with the following pattern:
public static class ConnectionStringManager
{
private static readonly SqlConnection conn;
static ConnectionStringManager()
{
//initialize the co... |
Activity
public class StopWatchActivity extends AppCompatActivity {
int seconds;
boolean running;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stop_watch);
runTimer();
}
public void ... |
This code sets and shows an image file on a QGraphicsView.
I'm interested in seeing how to improve readability and reduce redundancy.
void QtReader::addPadding(const int& querybase, const int& answerbase, QString &target){
if (padding){
if (querybase >= 10){
target = "0" + QString::number(answe... |
I would like to use the following routines in my submission script for GAMESS calculations. Before I do, I would like to get some input if I can improve it somehow.
The three messaging routines (message,warning,fatal) are taken from my earlier review request, although I have chosen a more verbose name.
Since I am not ... |
This is a C++ program which outputs a Mandelbrot fractal image in a graphics window and lets the user zoom and pan around the image, generating a new image each time the user does so. I'm using SFML for the graphics part.
Because it generates a new image after every zoom or pan, it is pretty slow, especially with a 100... |
I read a lot of articles recently concerning XAML, WPF, data binding and MVVM. I also watched some MVVM tutorials and downloaded some MVVM samples. I finally got my first MVVM sample to work, but there seem to be different "flavors" of MVVM, or maybe there are just many people who get the whole thing totally wrong, I d... |
I'm a PHP Developer. I'm trying to learn Python. So I tried to create a simple game, a Number Guesser.
I tried to comment out as much as possible without making super obvious comments.
I also made the attempts message color to be red.
Here's my code.
# 1. Print a message about the game
# 2. Tell the user that the ra... |
I have a big Python dictionary with more then 150,000 keys every key has list value. This dictionary contains infinitive words as key and all grammatical forms of these words as values:
{"конфузити": ["конфузить", "конфужу", "конфузиш", "конфузить", "конфузим", "конфузимо", "конфузите", "конфузять", "конфузитиму", "ко... |
I have the following code that takes a Point and a given tolerance value and looks for all other Points that fall within the tolerance from a Point array. Now this code is quite slow, does anyone know a faster way of doing this?
Also if you have any tips on how I can improve my coding style, if needed, that would be gr... |
It's been a year or two since I last dabbled in jQuery and have attempted to write a simple "on key press move to the next element" script. However my first attempt has a lot a repetition. I just know there is a more elegant way to write this, probably using a dictionary of elements or such.
$("#DialFirst").keypres... |
I am trying to create pagination with pure PHP and jquery. I have done this and it works exactly how I want it to work. Essentially I get all products from my database using PHP.
I then populate the whole page with the products and hide every row after the first 6 products. Then using jquery I create the pagination but... |
I have the following code that takes input of Line arrays and attempts to find the intersections on the end points between them. The value _nConrerTolerance is an int of a value of around 10% of the average Line length to allow the lines to not need to be exactly on each other. Now obvisouly this code will be quite slo... |
I have written this program to deal 7 cards to one player.
#include <iostream>
#include <string>
#include <cstdlib> //for rand and srand
#include <cstdio>
#include <vector>
using namespace std;
string suit[] = {"Diamonds", "Hearts", "Spades", "Clubs"};
string facevalue[] = {"Two", "Three", "Four", "Five", "Six", "Seve... |
I've made a data structure for mathematical expressions. I want to parse mathematical expressions like:
\$x = 3\$
\$y = 4\$
\$z = x + y :\$
into an evaluated document like:
\$x = 3\$
\$y = 4\$
\$z = x + y : 7\$
where \$=\$ is assignment and \$:\$ is evaluation.
The data structure must handle errors:
Invalid input ... |
I have the following code which inserts a new element of the same type over and over again to the parent element. I am new to JavaScript so was wondering if there was a better way of doing this. I apologise for the variable names, I'll get around to changing those later, just allows me to see the flow better. I'm tryin... |
I have refactored the version of the previous (and initial) iteration according to the answer by alexwlchan. As a reminder, this snippet compares breadth-first search against its bidirectional variant. See what I have:
#! /usr/bin/env python3.4
import time
import random
from collections import deque
__author__ = 'Rod... |
I have written a 2 player chess game in C++.
Things I have accomplished so far:
Legal moves validation
Bit board generation
Things I look forward to (would appreciate advice on them):
Move generation
Move ordering (based on move values for each square)
Pruning
Reading data from opening books
Here is the model break... |
I wrote a small header-only C++11 header for converting between various C++ time formats:
// time_utils/time_cast.hpp
#ifndef TIME_CAST_HPP
#define TIME_CAST_HPP
#include <chrono>
#include <ctime>
#include <sstream>
#include <iomanip>
#include <string>
namespace time_utils {
using chrono_time = std::chrono::time_poi... |
This will be my third post of this program, I have received a lot of great feedback and have learned a lot from the community. I have edited this program a lot, and am here for another review to see if I got it correctly. I had a hard time implementing one minor fix with output stream delimiter which was suggested in a... |
The goal is to have a helper class to wrap the concept of a resolution safely,
encapsulating the range check into the class, since otherwise it can get lost by
a client not so cautious.
I think this is all the context that's required, but an additional bit of info that may be helpful is that this looks a bit like what ... |
I have written a function that I want to protect from spam bots. I have used two techniques the first being filter after submit. After reading around I obtained the foreach loop from here and I have also written a piece of code that uses the spam honeypot protection technique.
However what I need to be checked over is... |
This code makes summaries from larger texts.
I have searched around for an algorithm and found the following:
Associate words with their grammatical counterparts. (e.g. "city"
and "cities")
Calculate the occurrence of each word in the text.
Assign each word with points depending on their popularity.
Detect which p... |
I have two dictionaries that I need the keys to match and if they match i will get the value of the first dictionary and then get the value of 2nd dictionary and build a new dictionary out of those.
dic1 = {u'ShutterHours': 732, u'ShieldHours': 732, u'MaskHours': 28, u'TargetHours': 790, u'GndRingHours': 25}
dic2 = {u... |
I just wrote a simple script cmd to hide private folders by combining several scripts from the Internet. Can anyone give me suggestions for improvement?
This batch file uses a password hidden by powershell script. Then I create a shortcut and run attrib -s -h, so it is not easy to find.
It works just gave attrib -s -... |
I am trying to implement the MVC pattern in C++ & QT, similar to the question here:
Other MVC Questions
The program has 2 line edits:
mHexLineEdit
mDecLineEdit
3 buttons
mConvertToHexButton
mConvertoDecButton
mClearButton
and just modifies strings.
The difference with the other question is that I am trying to impl... |
I'm trying to achieve, for lack of a better term, a "view" pattern in C++. It's probably most comparable to "views" in the Database world, where one can make a query, and then perhaps aggregate the data, or turn otherwise interact with it without actually duplicating the data.
I've tried to reduce it down to a simple e... |
This code outputs the smallest number with more divisors than the input:
from operator import mul
from math import sqrt, ceil
def next_prime_factor(n):
if n % 2 == 0:
return 2
for x in range(3, int(ceil(sqrt(n)) + 1), 2):
if n % x == 0:
return x
return int(n)
def factor(n):
... |
I have a sliding panel that I want to show content in. The content that I want to appear depends on the button that triggers the sliding panel. My project is growing rapidly and I would like to reusable jQuery code or perhaps a plugin. My code works, for example sake I have 6 buttons and 6 hidden divs in side of a slid... |
Code from my last project, that has to work on Python 2.7 and Python 3.
I want to get a path as a unicode string from argparse:
parser = argparse.ArgumentParser(
description='Organize your movie collection using symbolic links')
parser.add_argument('media_src', metavar='FILE|DIR',
help='Media fi... |
Let's pretend the following:
<?php
// Functions to validate/sanitize user input
function validateUsername() {
// If accepted, return true, else return false
}
function validatePassword() {
// If accepted, return true, else return false
}
function validateEmail() {
// If accepted, return true, else re... |
I implemented the lightweight cipher Twine described
here but it seems to me that this is not sufficiently optimized.
For example, below I have the key expansion for 80 bits:
private void expand80Key(byte[] key)
{
short len_x = 20;
short key_size = 10;
short iterator = 0,iterator2=0;;
byte temp_v... |
I have written my first program in go. It's rewritten from python.
Program takes csv file, emulates query SELECT X, Y, SUM(Conc), SUM(ToxConc) FROM very_big_table GROUP BY X, Y. And runs on terabytes of data.
It's written messy, but runs 100x faster than same program written in python.
Here is full code.
As you can... |
I have this simplistic Python class for representing directed weighted graphs (digraphs for short):
Digraph.py
#! /usr/bin/env python
__author__ = 'Rodion "rodde" Efremov'
class Digraph:
"""This class implements a directed, weighted graph with nodes represented by integers. """
def __init__(self):
"... |
I have been using NLog for logging purposes in my web applications, but it was not injectable. More precisely, each class using logging declared the logger like this:
private static Logger logger = LogManager.GetCurrentClassLogger();
Since my logging is very simple, I have defined some extension methods to easily log ... |
Here is a nodejs code that copies values from one object (submitted from a firm) to a model object.
Model:
var directory_model = {
"link_title": {
"value": 1, // This needs to be filled with object data
"validation": null
},
"link_desc": {
"value": 2, // This needs to be filled wit... |
I have a Python script that runs three compiled programs and makes them communicate via standard I/O. This is my first time using pexpect. My program runs very slowly. Is there anything that I can do to speed up the program? If not, I can try to do it with C/C++ pipe/fork.
import pexpect
import os
Checker = pexpect.sp... |
I have translated Dijkstra's algorithms (uni- and bidirectional variants) from Java to Python, eventually coming up with this:
Dijkstra.py
import heapq
from Digraph import Digraph
from random import choice
from random import uniform
from time import time
__author__ = 'Rodion "rodde" Efremov'
class HeapEntry:
def... |
Below comes a Value Object to represent UserId in ASP.NET application. It implements Value Identity, so equality is defined by matching of the state calculated at the moment of comparison. It depends on
public interface IAuthenticator
{
int CurrentUserId { get; } // may be impersonated
int Intera... |
This fairly clunky looking VBA script successfully pulls names of countries from an Array, but could it be made shorter?
Mass of text from Column C onward in each row may contain the names of countries, which I want to pull into the corresponding cell in row A. What I have so far is not pretty...
Sub PullCountries()
Di... |
I have implemented a filter for filtering a IEnumerable of a specific type.
To accomblish this goal i have created three classes: FilterOption, Filter and the FilterManager.
FilterOption.cs
public class FilterOption<TFilterOptionType>
{
private bool _isSelected;
public bool IsSelected
{
get { retur... |
My code is very slow to run, and I am trying to find a way to make it more efficient. I know there must be a better way than to write each modulo operation.
The goal of the script is to find the smallest possible number than can be divided by numbers 1 to 20 without a remainder.
def divide
(2..Float::INFINITY).each d... |
I have been trying to write a BrainF*** program that prints the Fibonacci sequence numbers repeatedly. I was wondering whether this is the most efficient way to do it. I basically repeatedly duplicate two cells into a third cell, and shift one cell forward and repeat.
+++++[->----[---->+<]>++.-[++++>---<]>.++.---------... |
The following is my first try at this classical interview question. It is quiet different from the solutions Gayle Laakmann provides in her book, and in another question on stackoverflow, someone initially mentioned there are better ways to do it.
I think my solution should run in O(n) time and use O(n) space. Would b... |
This class is for fast and small footprint buffering made specially for network I/O. It is similar to so-called circular buffers, but is not circular.
#ifndef _IO_BUFFER_H
#define _IO_BUFFER_H
#include <cstdint>
#include <cstring>
#include <cstdio>
namespace net{
template<size_t CAPACITY>
class IOBuffer{
public:
... |
I would like to use the following routine in my submission script for GAMESS calculations. I am not entirely sure if this is the optimum way to go.
This function would need one of the messaging routines, message, to function properly, but I decided to put echo in front of it, since this is basically what it does any wa... |
I execute the following SQL statement to get back an data object into a variable.
try {
$getUser = $db->query('select * from user where user.user_id = '.$user_id);
} catch (Exception $e) {
echo $e->getMessage();
die();
}
from this I print out the information on the page where necessary e.g. the foll... |
(See the newer version here: CodeReview question markdown downloader)
As an adjunct to From new Q to compiler in 30 seconds, I've created a Python script to automatically download the markdown from any question on Code Review and save it to a local file using Unix-style line endings.
For instance, to fetch the markd... |
I created an application from 3 layers, DAL, BLL, and Representation layer in ASP.NET Web API. In DAL i have 4 Classes:
- DatabaseContext.cs, UnitOfWork.cs, GenericRepository and UserInfo. In BLL i have a class called UserRepository that implemnet the IUserRepository interface.
In the Representation Layer i have a co... |
As an introduction, I would like to have my inputs validated with the built-in validation HTML5 attributes, e.g. use pattern for text input. So this is my sample code that implements that.
Is it considered best practice while handling event, to access event.target, which is the original DOM, and do something with it, r... |
I've been writing code for a little while but I'm a little slapdash. I'd like to get better so I've been having a glance at best practices, other peoples code and reading a whole lot. I'd appreciate it if you could read through my code and make some suggestions and explain why. You'll find some of my code below.
I want... |
Role based security does not work for me well in a multitenant app, as I need to query DB to decide on permission allowance. Here is the solution I came to.
All implementations of this interface will be auto registered in IoC container (note covariance/contravariance support):
public interface IResourceAuthorizer<out T... |
So currently I have this basic little chat bot that can read commands and can timeout users if their message contains a banned word or phrase. I was wondering how I can improve on this bot to be able to !add "word" to the set of banned words and overall general flaw improvements.
import string
from Read import getUser... |
So, yes, I know that "you shouldn't derive from std containers" but by now it's more of philosophical rule in my mind than a technical one. I've googled again for the one fundamental reason one should never-ever-ever-ever-do-that-ever-ever-ever-or-you-die but couldn't find it.
So, if there's nothing fundamentally wrong... |
I am faced with a design issue that has been discussed on SO several times, the most similar question being this one. Essentially, I want polymorphism for a CUDA kernel in the form of a "generic" kernel that can apply a "user-supplied" function to every element in an array.
In C++, one could achieve this design by usi... |
I have made a simple static parser for a bigger program. This parser takes a string that has comma deliminators and I need to separate the strings in to a vector for handling in a different section of the code.
I would like this to run as fast as possible so the rest of the program isn't tied up separating strings. I a... |
I've written a simple demo for Conway's Game Of Life for self-practice.
How can I improve the code, especially the processLife() method which traverses and updates the next state of every element in the matrix.
The complete code is down below;
For those whose eyes are tired of looking at code here: Gist Link
public cla... |
I'm working on a program that generates a maximal geometric progression of at least 3 integers when given a number that the greatest value shouldn't exceed.
My current code works, and it's quick(ish) with small numbers, but anything past 100 takes far longer than I'd like, as I need to calculate numbers in ranges from ... |
I've implemented a templated DBSCAN for general use. At the moment, it's going to be used on Android through the JNI. I used Wikipedia's pseudocode and a little bit of the DBSCAN paper for reference. It's pretty naive, so I'm wondering how I can speed it up, and what I can do to make it perform reasonably well on a pho... |
As an effort to teach myself Swift as well as to get familiar with machine learning algorithms, I've been trying to implement common algorithms, starting with a Random Forest. This is, for the moment just one of the tree, but I have been trying to implement it just from the theory, without looking at pseudo-code, in or... |
The Node.JS HTTP and HTTPS modules only provide .get shortcut function, unlike AngularJS's $http which provides them all. I went about creating a function that returns one of these shortcut functions:
'use strict';
var http = require('http');
function httpF(method) {
return function (options, body_or_cb, cb) {
... |
Can somebody please try and help me speed up my code? The file is ~12MB (you can download it here). It takes around 500-600 milliseconds to run on my i7 4790k.
import java.io.FileInputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
impor... |
I wrote a JavaScript source which regrouping by new key i.e. following JSON to the other:
{
"items" : [
{
"company" : "A"
, "name" : "Prod_A01"
}
, {
"company" : "A"
, "name" : "Prod_A02"
}
, {
"company" : "B"
... |
Forgive me if this is too simple, but I'm a beginner trying to learn and understand. I came across an exercise to create these three basic functions, and this is what I came up with.
Any glaring errors?
This program defines three functions:
sum(x,y)
range(x,y,step)
rangeSum (start, end)
sum will give you the sum ... |
My son just started high school and in Math, he was asked to do some stats homework. The exercise was to count all the vowels in a passage of text, then answer some questions about frequency.
Out of curiosity, I wrote a quick Python script to count the vowels:
text = "Australian Rules Football is a ball game played by ... |
How do I improve the following?
List<int> list = new List<int> { 1,2,3,0,5,7,0,6,0,0 };
list.Reverse();
list = list.SkipWhile(l => l == 0).ToList();
list.Reverse();
The goal is to trim trailing zeroes.
|
I'm making a a simple labyrinth. I want to make it so that I could hit a wall, and if I did hit the wall, I wouldn't cross it.
from turtle import *
from time import *
speed(0)
for a in range(0,401,20):
sety(a);
forward(400);
#write(a);
forward(-400);
home()
left(90)
for a in range(0,401,20):
setx(a)
forward... |
I'm logging data from an embedded platform over UART. This gets saved to a log file and I want to process the saved log with Excel.
I have no idea whether what I did was even remotely a good solution. My VBA experience so far consists mainly of code only used once. However, since I'll have to use this for every measure... |
Formally, a deterministic finite automaton is a 5-tuple \$M = (Q, \Sigma, \delta, q_0, F)\$, where
\$Q\$ is the set of all possible states
\$\Sigma\$ is the alphabet
\$\delta \colon Q \times \Sigma \to Q\$ is the transition function
\$q_0\$ is the starting state
\$F\$ is the set of accepting states
Basically, each DF... |
Here is a puzzle:
U2 has a concert that starts in 17 minutes and they must all cross a bridge to get there. All four men begin on the same side of the bridge. You must help them across to the other side. It is night. There is one flashlight. A maximum of two people can cross at one time. Any party who crosses, either ... |
Is there any smart way to compress the following code:
def __total(self, x, y):
count = 0
for x_offset in range(-1, 2):
x_index = x + x_offset
for y_offset in range(-1, 2):
y_index = y + y_offset
if 0 <= x_index < self.Size and 0 <= y_index < self.__Size:
... |
Problem:
Find all the pairs (a, b) whose product is equal to the sum of all numbers in the sequence [1..n] excluding both a and b.
I have made code for one program and need refactoring for code to get execution in less time. I am currently getting 13 sec for 500 number range.
def get_correct_array(n)
beginning_time ... |
Since the deprecation of C-style for loops in Swift 2.2 (and the removal in Swift 3),
several questions about the possible replacements were asked on Stack Overflow. In most cases, a for .. in loop
is the appropriate replacement:
for i in 1 ... 5 { /* ... */ }
for j in 10.stride(through: 0, by: -2) { /* ... */ }
for el... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.