instruction stringlengths 71 71.9k |
|---|
I attempted to recreate the GitHub code frequency graph (example) with a daily granularity using Perl and git log. How did I do, and what improvements can I make? I know that I should try to reduce the frequency of keys on the x-axis, but I have no idea how to do that and maintain scale.
It should be noted that the de... |
I've created a basic site with thumbnail images which when clicked open a modal type window to show a larger image with info related specifically to the image.
It works as I would like. However, I'm trying to develop my limited JS skills and looking at the code, I think there is most probably an easier and cleaner (and... |
I wrote an implementation in Haskell for Project Euler Problem 54:
The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all ha... |
This is the javascript component of a plugin for the Sphinx static site generator that creates instant search results as you type into a search box.
Any comments on organization and structure of the code would be appreciated, especially with respect to binding to DOM events. I work primarily in Python, so I'm still lea... |
I was told that this version is too simple, that need something more complex. I added Entity Framework.
Here my code:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace SalesTaxes
{
public class ShoppingCartContext : ... |
I wrote a program to fill a timetable for a school. There are some simple rules:
Each subject has a preset number of blocks (blocks are 2 hour periods).
Professor provide a valid hours they have to teach.
There cannot be a subject at block and day x if there isn't any professor of that subject that can teach it at t... |
I've wrote this code to calculate the prime numbers between two integers n and m, and I want to optimise it.
#include<iostream>
#include <cmath>
using namespace std;
int main (){
long int T[100][2],n,m,i,j;
int testcase,k;
bool prem;
cin>>testcase;
for(i=0;i<testcase;i++){
cin>>T[i][0]>>T[i][1];}
for(k=0;k<testcase;... |
In my web projects I often need a simple way to trigger callbacks defined somewhere else. Leaving jQuery finally behind me, I was missing their simple event system and tried to create my own. I'd like to know if this is a good implementation since I am not that proficient with Javascript yet.
function Events ()
{
/... |
I've created a helper method that is essentially used to get the default state of an select:
<%= select_tag "question_main_frequency",
options_for_frequency_state(frequency_segment(question)), { class: 'form-control' } %>
The helper method I've created to get the default state looks like this:
def frequen... |
My application has a whole chain of Observables running through it, and recently I found that something was slowing down my (hot) source, but I couldn't work out where.
Obviously, with everything running in series by default, a good first step was to introduce some 'parallelism', so after having done battle with my own... |
Goal: provide binding event mechanism which can use default or custom settings in a most proper, organised and readable way.
var module = (function () {
var settingsDefault = {
clickObject: 'body'
};
var s = settingsDefault;
var init = function (settingsCustom) {
s = settingsCustom;
... |
I made a scripted expression for after effects a while ago. This script is preventing objects to lay on odd pixels when a Keyframe is applied.
// Amount of Keyframes
n = transform.position.numKeys;
// Time
t = time;
// Time of Keyframe
timeOfKeyframe = null;
if ( n != 0 ){
// Time of first Keyframe
timeOfF... |
I recently started C# and I've got the feedback that I still repeat too much. How can I make it less repetitive?
namespace ExtraOefLabo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
... |
Related to this question (and even this Stack Overflow's one) I have been trying to avoid blocking the code. So what I understood it's that is preferable to make all the methods that rely on an async one async themselve (thus not defeating the purpose of asynchronous). Therefore I have changed my code to do the followi... |
This is my code for project euler #35 (in Python):
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million... |
Here you find some code that returns the value of a multivariate Bernoulli density function - for a dice with n faces, where each face has its weight (weight must be positive reals, not necessarily sum = 1) it provides the result of the tossing.
function face = weighted_dice(faces, weight)
% face = dice(faces, weig... |
I have been trying to learn JavaScript for the past few days and decided it was time to put what I had learnt into practice. Here is the program I created. It's a five-question quiz which counts the number of correct questions as you go through the quiz and also ranks you at the end of the program.
//I am going to pla... |
One of the K&R exercises is to write a small piece of software to compare two files and print the first line in which they differ.
Here is my attempt:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#define SET 1
#define UNSET 0
#define BUFFERSIZE 100
void error(char *fmt, ...);
int ... |
I have the following table:
id speed date
1 0 01/01/2015
2 0 01/01/2015
3 0 01/01/2015
4 0 01/01/2015
5 0 01/01/2015
6 0 01/01/2015
7 25 01/01/2015
8 78 01/01/2015
9 13 01/01/2015
10 45 01/01/2015
11 0 01/01/... |
I have a data file which contains floating point data arranged in 4 columns. Each row represent a specific data point. The first column(X) is made up of 100 different values but the values are repeating. Fortunately they are sorted in ascending order. For each distinct value in first column the second column(Y) has a d... |
As the title says, I want a function that takes a vector, as well as the number of bins, and splits the vector in that number of bins, with a minimum length of 1 for each bin.
def split_into_bins(nbin, vector):
"""
Randomly split vector into nbin number of bins, each of random size
"""
permutation = li... |
The purpose of this code is to let me loop over 100 items (up to MAX_CONCURRENT at a time), performing some action on them, and then return only once all items have been processed:
/// <summary>Generic method to perform an action or set of actions
/// in parallel on each item in a collection of items, returning
/// on... |
I have written VBA code to copy and do some formatting and create sheets based on unique reference and insert some information. I want to optimize this code and make it short as much I can. The code is broken into parts to help make clearer what I am doing with it.
Sub Previous_comments_and_modifications()
Dim x As L... |
Curious if there is a better way to write a repository method that receives argument List<int> and checks if the database Contains an int?.
public List<int> GetNumbersByNumbers(IEnumerable<int> numbers)
{
var convertedNumbers = numbers.Select(m => (int?)m);
return Context.TblNumbers
.Where(m => converte... |
I want to write a complete diffie Hellman example for bouncy castle that includes key generation, key exchange, encryption, and decryption. I also want to verify that if Alice is initiating a connection to Bob, that she should send her public key, Parameter P, and Parameter G.
This is also a good reference.
Namespaces:... |
I have made an effect that has the h1 move and then reveals p using .addClass, .removeClass and CSS3 transition. It works perfectly but I think I am repeating too much of the code and I think there may be a way to write it better. I need postShow and postHide to be different because I need setTimeout to be in postShow ... |
Given a letter (A or B) representing the color for N nodes of a graph and the set of M edges. Its possible to make all the graph have the letter A by flipping the nodes connected by an edge ?
Example:
Given the following letter graph:
A - B
Its impossible to make all the letters A by flipping the nodes connected by... |
Related to another answer of mine on Project Euler 35, I found the need to calculate all combinations of certain digits, i.e. 1, 3, 7 and 9, below a given n. I looked around, and didn't find any really good premade solutions, but found some bits and pieces related to Cartesian products, and collated my findings into th... |
I am writing some examples of Java programs on GitHub rsp/ppj for people to learn and I want them to be as simple and compact as possible, to work on Java 1.7.x (a.k.a. Java 7) and to not use any non-standard libraries that need installation.
This question is about my WhereEven example:
a function of an int[] array tha... |
To help my son with his programming skills, I am trying refresh my limited Python knowledge. I chose a simple dice game called Pig Dice.
import sys
import random
HUMAN = 0
COMPUTER = 1
HOLD = False
ROLL = True
class Die:
def __init__(self):
self.value = random.randint(1, 6)
def roll(self):
s... |
I have the following class for Quicksorting.
import java.util.Random;
public class QuickSorter {
public static void main(String[] args) {
Random random = new Random();
int[] randoms = new int[10000];
for(int i = 0; i < randoms.length; i++) randoms[i] = random.nextInt(10000);
quickS... |
This is a follow up question of this one.
Since the original question was posted, it has turned out that in some cases I want the code to be synchronous and in others to be async.
I have updated the code the 'handle registration' method is now fully sync I believe:
public void HandleRegistration(IProgress<string> progr... |
I've got this massive nested for loop with a few if and else statements in nodeJs. The output of all of this is just string which is combined from different values out of JSon object. What I want to do is rewrite it in more efficient way as JSlint plugin for sublime is complaining about complexity of it:
var instancesL... |
Background
I'm writing a wrapper for a significant portion of a native library in Java. The native objects my classes are wrapping are giving me some headaches in terms of design.
I'm not a fan of the two-step initialization idiom but I've resigned myself to use it if the native object has a lot of configuration option... |
I'm flexing the C++ muscle and came up with the following implementation of Mergesort. Any suggestions as to the implementation and style are welcome.
int* MergeSort(int a[], int size)
{
if (size <= 1) return a;
int mid_point = size / 2;
int left_size = mid_point;
int right_size = size - mid_point;
... |
I have just started learning graph algorithms and am trying to arrive at an ideal interface. I understand that this code will not be used anywhere else (I will certainly use Boost::Graph) but I just want to make sure that what I am writing is not completely wrong.
Specifically, my question in the implementation below r... |
I have two questions about my code:
Are there any performance improvements in this implementation or generally (register int ?) that I could make?
What could I improve in my coding style?
void mergesortArray(int data[], int amount){
if(amount == 1) return;
//Precomputing values
int sizeint = sizeof(int... |
I have the following method which calculates average days on market for a sale type segment:
def average_days_on_market_sale_type_segment
# on market days
on_market_days = {}
# 1. get last year sales - note that the dates need to be sequential in time (oldest in time comes first, most recent in time commes... |
I am building an MVC 5 application using code-first Entity Framework 6 and a customised ASP.NET Identity model for authentication.
I will only be authenticating against external OAuth providers (Google, Facebook etc) and persisting the login and claims information in custom code-first EF entities.
Since this is the fir... |
In prepping to teach a workshop on recursion I wrote this code that uses a maze-building algorithm. In doing so I found it really natural to use generators a lot. I feel pretty happy with how the code turned out but its also pretty unusual and I wonder what yall think of it.
This is meant to run on latest chrome (parti... |
public function getData ($term) {
$db = Database::getInstance();
$term = htmlentities($term);
//Kill the script if the term is blank
if ($term == "") {
die();
}
$query = "SELECT * FROM coils WHERE name like '%$term%' or
... |
I have a function for merging data from an object (a PrintTestDataItem) into a template file for a printed label (a LabelFormatDocument called label in this snippet). The LabelFormatDocument is a third-party class that I use to set various fields on my label and I do this by setting the numerous substrings to the value... |
I create constant class , include my url constant , my user web calls .... etc
I put my constant class in Utils package
here is my questions , is it good to inset constant class in Utils package ?
second question , should I separate each element create constant file for url , user ... etc
// url constants
///////... |
Is there anything wrong with using double ternary operator like so:
var stateName:String = state is String ? state as String : "name" in state ? state.name : null;
Here is two lines because someone requested it:
var stateName:String = state is String ? state as String :
"name" in state ? sta... |
The idea is to perform a bit-wise scan of an ushort provided to find any and all matches within an enum collection.
The code I developed is as follows:
public List<T> GetEnumItemsFromUshort<T>(ushort input) where T : struct, IComparable, IConvertible, IFormattable
{
var output = new List<T>();
forea... |
I've recently been working on a small project to provide a simple heartbeat between server and client applications. Pretty happy with it, just wondering if it could function better (I know it could use cleaning, and a standard naming convention, I like to code quick and dirty then clean up)
Any advice would be greatly... |
I am adding two custom metaboxes to the WordPress post page from a plugin. I am currently doing it with two separate instances of add_meta_boxes but this feels very bulky, especially as I go to add more.
Since the plugin is fairly small I dont want to include a framework and was wondering if there was an easier to add ... |
The task is to assign the n numbers given as input by the user in an array . For Ex : If user gives 10 as input then the generated array should be like this ,
arr[0] = 0
arr[1] = 1
arr[2] = 2
arr[3] = 3
.
.
.
arr[10] = 10
The code below works fine but i am using a loop to assign this numbers to an array which can pro... |
This post is a follow-follow-up to this post and its follow-up.
In those two posts we managed to speed-up the solution of an Alberi puzzle, and to create a one-tree-per-region puzzle.
The complete code hereafter can be used to create multi-tree-per-region puzzles.
Using DFS I had little chance to find a valid puzzle, s... |
I wrote a small class that does a database lookup and it generates a collection/Array. The Collection is resorted based on values returned from the database. Finally, the records can be retrieved using the public method called getQuestions().
I trying to move away from procedural code into object-oriented programming. ... |
I use this code to create a common interface around my C++ objects. At first it was intended to only POD types (implemented with functions like malloc() and memcpy()) but later it was modified to allow using a reduced interface for other C++ objects, allowing for things like constructors/destructors to be called by the... |
I have data like:
var data =
[{
"date":"1-1-2013",
"answer":"yes"
},{
"date":"1-1-2013",
"answer":"no"
},{
"date":"2-1-2013",
"answer":"no"
},{
"date":"2-1-2013",
"answer":"no"
},{
"date":"2-1-2013",
"answer":" " ... |
I have a console application that I want to use to send an email notification every day at some time (call it 06:00 local time). To do so at the moment I am using a System.Timers.Timer in the following way.
I have the following implementation of my service class:
public class PerfomanceService : INotificationService
{... |
I am trying to implement AES on GPU using CUDA programming. I use 4 TBoxes in my implementation that requires 4kB of GPU Memory. I have used a 1KB array for 1KB plaintext. first all of plaintext would be copied to GPU memory, then encryption would be started using
cudaMemcpyToSymbolAsync(DEV_message, H_Message, 1024, 0... |
Just experimenting with various Javascript techniques and was wondering if the code below is valid and if there are any disadvantages to using this technique to create html tags from JS object constructors? I know the usual technique is to add the html directly in the body and loop through an array to populate the elem... |
I've completely reworked the previous code, posted here, so that it is a bit more correct regarding dynamic memory management, and also a bit more true to the object-oriented paradigm.
/** A program for Red-Black Tree manipulation: insertion and value retrieval.
* All position relations (first, last, previous, next) ... |
I'm really trying to wrap my head around application safety in some web pages. I'd like to mention some of the things I've done in the past and hear some critiques on how I can get better. Applications I have made in the past have been mostly for hobby, but I'm currently creating one with data that needs to be secure.
... |
Recently I felt the need to write a Mutable<T> class so that I can pass immutable objects through methods, whose value can then be changed. Some examples of immutable classes (including primitive types):
int
long
short
byte
double
float
String (though already has a StringBuilder class
BigInteger
and others.
There is ... |
Here is my code simulating liquid in a pipe cooling under different conditions. How did I do approaching this in an object orientated way? Is there any way I can improve this code?
import numpy as np
import scipy
from scipy.optimize import minimize
from matplotlib import pyplot as plt
class pipeSimulator:
R_w = 0.... |
Curious how sqlite3 would handle different race conditions in a multithreaded environment, I created a simple module called deterministic for serializing the execution of multiple threads that lets the programmer explicitly program in the spots where thread-switching happens. Hopefully this example usage will explain ... |
A week ago, I applied for a 'Software Engineering Internship' at one of the company. Since I know C++, C#, Java well and have worked on couple of ASP.NET MVC projects with MS SQL server before, I knew I was well qualified for the job. Plus, I recently graduated from my Bachelor of Computer Science with High Distinction... |
I've written an object which allows parsing and serializing a command line. I don't in any way consider this done, but this is the beginning of it. I know there are other implementations out there like this, but they tend to be either too primitive or too heavy. This is an attempt to simplify parsing and serializing a ... |
I have written a file to extract text from news articles. The program works as I want it to except it takes hours for it to write the output files. I have tried different buffering options as well as adding the data I want written to an array before writing that to the file. I have almost no experience programming so I... |
I wanted to keep my controller tests DRY, readable, and make writing new tests very simple so that it encourages good practices like one assertion per test (if you have to redo a lot of work over and over, chances are you're just gonna shove more assertions into the same test to avoid the extra work).
Here's the strate... |
I feel like the if-else combination isn't the most optimal and I'm also not sure if I need a loop
var Auktionator = function(){
var rennt = false;
this.versteigern = function(objekt){
if(rennt === false){
for(var i = 1; i<=4; i++){
if(i === 1){
setTimeout(function(){consol... |
I've prepared a simple login form, using prepared statements to prevent SQL injections. How secure is this ?
<head>
<title>Login</title>
<?php
session_start();
// set up a token
$form_token = md5(uniqid('auth', true));
// session form token
$_SESSION['form_toke... |
This is the JavaScript file that i use for my editor that allows people to edit questions from a form.
I'm wondering if this sort of approach to use JavaScript objects is good or that I kind of miss the point here?
$(document).ready(function() {
manager = new Customerformquestionmanager();
manager.formId = firs... |
The point of this code snippet is to calculate and compare an MD5 obtained from a USB device connected to the computer against a database to check its validity.
var md5String = string.Empty;
using (var md5 = MD5.Create())
{
var md5CRC = md5.ComputeHash(File.ReadAllBytes(destinationFilename));
foreach (byte b in... |
I'm implementing a graphical representation of an "analog clock" with moving hands (seconds, minutes and hours), using mainly2 FLTK facilities and the function Sleep(miliseconds):
main.cpp:
#include "iostream"
#include "GUI.h"
#include "Window.h"
using namespace Graph_lib;
#include "AnalogClock.h"
int main ()
try {... |
I'm getting the correct results, but my method isn't the prettiest. Is there any way to do this with less code?
var longestSuffix = function(A, B) {
return rec(A, B, 0);
function rec(A, B, count) {
if (!A.length || !B.length) return '';
if (A[A.length - count - 1] === B[B.length - count - 1]) {... |
I have hand-coded a forgotten-password reset system. I am apprehensive about security issues/vulnerabilities. What part of this can be exploited or could be made more secure?
forgot-password.php
<?php
require_once 'connect.php';
if($_SERVER['REQUEST_METHOD'] === 'GET') {
if(isset($_GET['email']) && !empty(... |
I am very new to Java and although my code works, I know that it must be possible to write this using fewer lines of code. I am serializing multiple objects, eventually I will look into serializing to multiple files, for now, I am using just one file, so it constantly gets over-written. How can I nest or reduce the num... |
I'm using vectors to create matrix and the vector itself is consuming a large space. So I implemented a version that would use less memory and, if possible, be as fast or faster than std::vector.
How can I improve the performance and is there anything that should be changed?
#ifndef __DATAARRAY_H__
#define __DATAARRAY_... |
The script below is taken from this site. It doesn't currently work, but I have made it work at my own computer (not currently accessible) by changing what BeautifulSoup looks for.
The script is intended to print info to the console, however, what I really want is to utilize this script to return a tuple (self.tomatom... |
I have a question regarding creating controls in runtime in ASP.NET 4.0. I'm building a application and in admin.aspx page I have multiple controls (DropDownLists) which are dynamically created with values from a Sql database. I know that for having events fired for dynamically created controls, I have to create this c... |
I recently decided to try and write my own implementation of Linq, which then lead me on to trying to solve some of the problems we have in our code base at work. Our code is littered with the following (obviously a simplified example):
var items = new List<string> { "apple", "dog", "chair" };
if (item... |
I need to validate a variable length string against some white-listed characters. The algorithm that I have works but I have a sneaking suspicion that there is a more elegant solution. The code below hasn't been identified as a bottleneck so ease of maintenance is preferred over a clever but confusing implementation.
p... |
I am attempting to create XML forms using user input to populate certain areas that would appear when loaded into a STIG viewer. Right now everything is working enough for me to create this and have it work just fine.
Is there a way to throw the lower portion which contains the rules and whatnot into a method and have ... |
Note
This question was born in request to post more details from this question on Programmers. Since details may uncover new/different complexity, I'm asking another question here. I also will use this question for reference purposes as it more fully defines my application.
Currently I am seeking to improve
storing... |
I get back two dictionaries, I need to parse through them and put in an array two objects. I think I did a very poor job and I have a feeling there is a better way to make the code more compact and generic.
I think there is definitely a way to combine these two loops. Please advise on any better way to accomplish this... |
Using Apache POI, I want to retrieve a Person from my Excel file by id or by name. To keep the example simple, the Person class is only an int id a String name and in the Excel file, the id starts at A2 (A1 is the header) and the name at B2 (B1 is the header).
I came up with this code:
ExcelDB class:
package datasource... |
I have a program that takes an input from the user (the user's name) and print a result with their name inside a border such as:
*************
* name_here *
*************
The code:
def style_1():
print "*" * (length_of_name + 4)
print "*", name, "*"
print "*" * (length_of_name + 4)
def style_2():
pri... |
I'm a newbie to C++ (coming from C#) and I decided to complete this Code Golf challenge for fun (though I definitely wouldn't say it's short). Essentially, the challenge was to calculate the phi(not_pi()) of all the numbers from 1 to 100, and print them out in a loop, where
phi(n) is the number of integers less than o... |
I wrote a small "game" in Python for practice. I would like if someone could go over it and tell me if there is anything wrong or if there are any improvements I can make.
import time
import sys
class Creature:
def __init__(self, name, hp, inventory):
self.name = name
self.hp = hp
self.inven... |
I am new to Rust. I would like to know any better way of doing this and if it can be done preferably with safe code.
use std::mem;
use std::mem::size_of;
fn show_byte <T> ( element: T) {
let array: * mut u8 = unsafe{ mem::transmute(&element) };
for i in (0.. size_of::<T>()) {
let current = (array a... |
I am looking for some ways to make my code simpler for this currency converter.
currencies = {
"BRL":"(Brazilian Real)",
"USD":"(US Dollar)",
"EUR":"(Euro)",
"GBP":"(Great Britain Pound)"
}
def real_to_dollar():
user_value = raw_input("How many reais? ")
ammount = float(user_value)
conversi... |
Please critique this and make suggestions on the best practices.
//Seasons Divided
#include <iostream>
#include <string>
#include <iomanip>
#include <stdlib.h>
using namespace std;
int main(void)
{
string Answer;
//Character Declarations
string Sex;
string Age;
string Height;
string HairLength;
string HairColor;
str... |
I have referred some class diagram to actually create visitor.
#include <iostream>
using namespace std; //know should not be used, but for simplicity
class Book;
class Pen;
class Computer;
class ICartVisitor
{
public:
virtual int Visit(Book &) = 0;
virtual int Visit(Pen &) = 0;
virtual int Visit(Computer... |
This is a programming challenge I submitted as part of a job interview, which I failed because it lacked "maintainability" and "patterns and best industry practices", so I guess we could all learn something from my mistakes.
The challenge was to write a program that, given a list of programming languages, it'd return ... |
The idea here is to be able to find a USB serial port device connected during runtime, thus not knowing its port number, and use it in the application to retrieve information from the device.
string comportInfo = string.Empty;
using (var entitySearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32... |
I have a data access class:
using CompanyX.DataAccess.CompanyXTableAdapters;
namespace CompanyX.DataAccess
{
public class CompanyXDataAccess
{
#region Invoice
public CompanyX.InvoiceDataTable GetInvoiceByID(int ID)
{
InvoiceTableAdapter ta = new InvoiceTableAdapter();
... |
I am working on a multi-threaded webcrawling program in Java. Each WebCrawler starts at a root page and repeatedly extracts new links and writes them to a database. I have included most of the code below:
public class WebCrawler implements Runnable {
private ConnectionPool connectionPool;
private ExecutorService execu... |
I have written this snippet to find r-permutations of n, i.e. if I have an array of n=3 {0,1,2}, then r=2 permutations will be {{0, 1}, {0, 2}, {1, 0}, {1, 2}, {2, 0}, {2, 1}}.
Can somebody review it and help me optimize / reduce its complexity (I don't want to use recursive function):
"_getAllPermutation": function(in... |
My task was to receive an array of integers and then reassemble the array as required:
The array size is to be of element index 0
The next element (index 1) has the number of even distinct digits (digits that appear in only one integer input but not the rest).
And the next pairs (if any) of elements will store the val... |
I have finished writing my first Node.js app: a CLI app that runs Conway's Game of Life. I am looking for feedback on things that might not have been done the "Node.js way" and what I can do to better improve my understanding of Node.js.
Specifically speaking, looking at the the game.js module, is what I am doing follo... |
After profiling of one project I've found a bottleneck in the code, specifically the line:
String columns[] = line.split("\\s+");
I've tried to find a workaround, but all ready made solutions, such as StringTokenizer and Scanner seem to be less efficient (for example, look at the answer on SO). So I decided to write a... |
Here's a simple function I wrote using recursion. Does this run in \$O(n)\$ time and use \$O(n)\$ space, where \$n\$ is the number of nodes in the tree?
def is_valid(root, min, max):
if not root:
return True
if min is None or max is None:
return is_valid(root, float("-inf"), float("+inf"))
p... |
var x = 0;
document.getElementById("1").addEventListener("click", function() {
if ((x % 2) == 0) {
document.getElementById("dropdown_1").style.display = 'block';
} else {
document.getElementById("dropdown_1").style.display = 'none';
}
x += 1;
});
var y = 0;
document.getElementById("2").a... |
This is a code to calculate somebody's age. It takes 2 inputs:
A specific date (to calculate your age at a specific time or the current time).
The birth date.
print('''# This is Age Calculator Program.
# This program is written by Mahmoud Naguib and it will be improved.
# You can contact me at : https://www.facebook... |
I'd like to get some feedback/criticism on my attempt to write a simple client/server application that reports back the (client's) global IP address.
It would be nice if you could comment on the UDP socket setup, general security or any other drawbacks you were able to spot. Since this is my first attempt in writing Py... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.