instruction stringlengths 71 95.1k |
|---|
I have a rather large UI for editing a user within a Angular application. It is split in multiple tabs and in order to reduce complexity the user cannot change the tab unless there is no validation failure on that particular tab.
However, some validation is asynchronously performed on server side. The validation flow c... |
I have a procedure that collects data from one table and inserts it into another table with the same columns, but after correlating with a few other tables. Since the existing table (from which data will be transferred) has more than a million records, the insertion into the other table (into which the data is being tr... |
I need to validate multiple input fields using React. I am using a simple if-else block for each input field but I would like to optimize my code and make it better. I feel there can be a better way to validate multiple input fields.
validateForm = () => {
const {
firstName, lastName, mobileNo, city, empTyp... |
After having had a look at reflector's code base I decided to write a new, more lightweight mirror list optimizer from scratch: speculum.
The script queries the Arch Linux mirror list JSON endpoint and performs filtering, sorting and limiting of mirrors according to the user's input.
Any feedback is welcome.
#! /usr/bi... |
#! python3
# `regexSearch`: Finds all lines matching a given regex in each file in a given folder.
# Usage:
# The directory to search and regex to be searched for are provided as a command line arguments.
# The 1st and 2nd command line arguments are the directory and regex pattern respectively.
# ... |
I am learning C++ and I need help to review my first code and see how I could improve it in any way. Any suggestions are welcome. It was tested and it is free of bug.
The code is a game called TicTacToe and do the following:
Create a 4x4 game board
Prompt the first user (the 'x' user) to enter their name
Prompt the s... |
I wrote a small script that opens a window using PyQt when a specific file gets created.
This is to let me know when another program (that I have no control over) has finished calculating something. I know at the end of the calculation a specific file is created.
Here is the code:
from PyQt5.QtWidgets import QWidget, Q... |
This code is part of my Hangman game. One of my minor issues is how to properly print out the hangman.
Could you please give me hints on how to make the code less hardcoded? This code is so redundant, shoot me...
Any comments are welcome.
class HangmanState
static void show(int count, PrintStream out) {
switch(coun... |
I have created a program that forms a basic calculator in C which includes the basic operations like addition, subtraction, multiplication and division. But in this case I decided to use a Do-While loop. It is working.
I would appreciate to be pointed out some mistakes and opinions to make the code more presentable.
I ... |
I was tired to always perform pixel manipulation one by one, so I started to create my own templated header to perform computation over pixel (RGB, or RGBA), but I also make it for ND for some cases.
There are few comments in the code for some features that Im not sure yet.
I also develop it as std::array to have oper... |
My code works but would take 160 days to run lol.
#prime factors - ex.3
primes = []
for possibleprime in range (2,100000,1):
isPrime = True
for num in range(2, possibleprime, 1):
if possibleprime % num == 0:
isPrime = False
if isPrime:
primes.append(possibleprime)
#print(prim... |
The module is for facilitating random string generation. The example I use to explain it is the following:
Instead of writing
#vars
age = random.randint(18, 20)
#categories
names = ('Mark', 'Sally')
adjs = ('wacky', 'cool')
adjs_probability_map = (0.1, 0.99)
hellos = ('Hi!', 'Hey!', 'Good morning.')
hellos_probability... |
I am calling matrix implemented with a lambda "lambda matrix". The full working program:
// g++ prog.cc -std=c++17
// gcc 8.2.0
#include <iostream>
#include <cassert>
#include <memory>
[[noreturn]] inline void terror
(char const * msg_, char const * file_, const unsigned line_)
{
... |
Given an arbitrary \$N \times N\$ matrix, find the maximum sum submatrix. This particular approach uses the Kadane's algorithm. What could be improved both in terms of algorithm and code style?
def read_matrix_from_input():
return [[int(s) for s in input().split(" ")] for row in range(int(input()))]
def max_subar... |
C++ newbie trying to build a class to represent a dataset for the purposes of building predictive models of the form y ~ x0, x1,... Since this is version 1, I'm assuming some nice properties about my dataset
It has one y column and one or more x columns
It has all double values
It has no missing values
In order to op... |
Simple bash script to create apache2 virtualhost for localhost. Can be used for public subdomains on developer server with changes - "replace .localhost".
Tested on Ubuntu, but should work where dependency met.
Not for production, for development purposes only.
Use zenity for gui and pkexec for root permissions, so can... |
I have an express handler which i thought was pretty simple, but CodeClimate flagged this method as having a Cognitive complexity of 6 (5 is the max by default without flagging something)
Curious how I could simplify this method to reduce Cognitive complexity.
function updateUser (req, res) {
// Update any fields tha... |
How could I use enums in the following block of code to simplify it? The block is a program that has a command interpreter that returns different data based on user input. Is there a way I could easily apply enums and a match statement to the logic here?
use std::io;
fn main() {
let version = String::from("0.0.1")... |
I am learning Haskell programming language mainly from this source. And there I have encouraged with "an elegant" realization of the quicksort sorting algorithm (the Quick, sort! section). Here it is:
Book's implementation
quicksort :: ( Ord a ) = > [ a ] -> [ a ]
quicksort [] = []
quicksort ( x : xs ) =
let smalle... |
I'm practicing data structures in C and I implemented a queue based on its description:
#include <stdio.h>
#include <stdlib.h>
struct QueueNode {
int data;
struct QueueNode* nextNode;
};
struct Queue{
struct QueueNode* priorNode;
struct QueueNode* lastNode;
};
struct Queue* initQueue(){
struct Qu... |
I have a few servers to fix that repeatedly get their nginx.conf file messed up due to a rogue deploy script.
These are the three sed commands I'm using to fix at present:
sed -i '' 's/^\([[:blank:]]*\)#\([[:blank:]]*\)server_names_hash_bucket_size/\1server_names_hash_bucket_size/g' nginx.conf
The first finds any kind... |
Here is my try on a crawler made in nodeJs with cheerio, I made it with the idea in mind to use it in a future project I wanna make. Here is the git link: https://github.com/Just4lol/CookCrawler
If you look at the index.js you will see how to use it;
const cookCrawler = require('./cookCrawler.js')
cookCrawler.getRecip... |
I always use nested list and dictionary comprehension for unstructured data and this is a common way I use it.
In [14]: data = """
41:n
43:n
44:n
46:n
47:n
49:n
50:n
51:n
52:n
53:n
54:n
55:cm
56:n
57:n
58:n"""
In [15]: {int(line.split(":")[0]):line.split(":")[1] for line in data.split("\n") if len(line.split(":"))==2}
... |
#include <iostream>
int main() {
int letter = 0;
std::cout << "Please type in a number: ";
while (1) {
std::cin >> letter;
//less than 1 or greater than 26
if (!(letter < 1 || 26 < letter)) {
std::cout << "The letter that corosponds to that value is '"
... |
Preface
This is my first work script; normally I'm just mucking around in console or writing snippets. This script has a lot of firsts for me (configs, logging instead of print, try/except). Typically when I just write snippets I don't care if things are breaking. Given this is set up as a scheduled task for work, I tr... |
Preface
This is a follow up to my previous post from not long time ago about containers and filtering. This post can be found here. Now, I will attempt to expand what I have learnt from the answer given by Mathieu.
Context
Using implementation of IPredicate interface I was able to reduce number of line inside my class... |
I am allowing users to upload and drag images with this code. Give me a review of this.
Codepen
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<input id="fileup" type="file" >
<div class="container">
</div>
<style>
.temp {}
.container {
background: black;
}
.masked-img {
overflow: hid... |
This is what I came up with, but I'm not sure if:
putting it in Class is the best approach
multiple repeats (this.val etc.) are acceptable
there is a better approach (maybe with constructor)
class UnitChange {
temperature(val, to) {
this.val = val;
this.to = to;
if (this.to === "toF") {
return th... |
I have the following function which handles requests. It has more than 130 lines
public function run() {
$objectRequests = json_decode(file_get_contents("php://input"));
if (isset($objectRequests)) {
$objectResponses = array();
foreach ($objectRequests as $objectRequest) {
$objectR... |
I wrote my first useful function in C which can be used in a different variety of situations as an alternative to common code logic.
segstr (originally named strseg but renamed to not use a reserved identifier) is a helper/utility function which can be used as an alternative to using strchr, strtok etc. for parsing inf... |
My task was to build a calculator in Python supporting binary addition etc.
To begin I define a couple of custom exceptions :
class MaximumValueException(Exception):
pass
class MinimumValueException(Exception):
pass
I then define the Binary class which does most of the work for me (I know that the division... |
public static void main(String args[]) {
solution(new Command() {
@Override
public void execute() {
{
System.out.println("Hello World");
}
}
}, 1000);
// java 8
solution(() -> System.out.println("He... |
The question is very simple : I have an array of items, that all have a date. According to the date, I would like to split this array into several arrays.
In my case, I would like to split the array into 3 arrays : one that contains result of the last 24h, the other 48h, then the last one on the week.
Here is a minim... |
In this repo I've put together a header only string splitter, allowing for characters and string literals as delimiters.
The (little) library is strictly C++17.
I would like to ask for your comments.
I would also like the code to be as short as possible, so any comments in that direction are also most welcome.
As it ap... |
As the above title states I have a function that I use to populate a collection's status names, currency names and other information that I do not store in the database.
This is my function:
public static List<T> PopulateStatusNames<T>(List<T> items) where T : class
{
if (typeof(IStatusResult).IsAssign... |
I have a dictionary that stores a string and its frequency which looks like this
test_dict={'large blue dog':2,
'cute blue dog':2
'cute blue elephant':1
'cute blue' :3
'blue dog':4
'large blue':2}
My final list need to contain every thing except 'large blue' a... |
I am practicing Rust by writing doubly linked list using raw pointers, Box<node> to allocate data on heap, Box::from_raw to free data from heap. I feel it very silly to use a lot of unsafe blocks.
struct node<T> {
value: T,
prev: *mut node<T>,
next: *mut node<T>
}
impl<T> Drop for node<T> {
fn drop(self... |
(I am not sure of the official CS name for the problem in question, so I just gave it the name of the kata).
Problem
CLEAR CUTTER'S NEEDS YOUR HELP!
The logging company Clear Cutter's makes its money by optimizing the price-to-length of each log they cut before selling them. An example of one of their price tables... |
We use third party addin that downloads market data from the internet into a workbook. The addin works with custom functions that begin with CompanyAddin. For instance, a formula in a cell could look like this:
=A1+CompanyAddin(formulaparameters)
My macro (code below) looks for all formulas that contains CompanyAddin.... |
I'm doing a simple task in Rust after reading the Rust book:
read a text file
split it at whitespace
sanitize words by removing non-letter characters
sort the words by their frequency of occurrence
Here's what I've got, which works, but I'd like some advice:
are there any unnecessary implicit copies that could be re... |
I am integrating a system of perturbed phase oscillators. I define the system of equation and also the Jacobian matrix. I have to reshape the one dimensional vector of system state to a 2 dimensional vector then do the matrix production.
Is there any single-threaded way to make the program faster?
using dim1 = std::vec... |
For an assignment, I have created a solver for the Skyscraper Puzzle:
Each puzzle consists of an N×N grid with some clues along its sides. The object is to place a skyscraper in each square, with a height between 1 and N, so that no two skyscrapers in a row or column have the same number of floors. In addition, the nu... |
I have written a function in XQuery 3.0 (using BaseX) which tests a base sequence against a test sequence, with the goal of determining if the items in the test sequence appear in the same order as the base sequence.
This is best illustrated with an example
E.G.
let $baseSequence := ('a','b','c'..'x','y','z')
Tested a... |
The following is my first real attempt at batch scripting, and I'm new to it so I'm not sure whether what I've done is to best practice. The code works, and I'm open to suggestions.
Basically the following code allows someone to download Node.js and npm per project, a requirement we have so that we can run multiple ver... |
Thanks for your time, I am new to programming and I spent some days making this rock, paper & scissor game. What other possible improvements could I make after the ones I've made myself?
I've tried explaining each step as the program goes on, but I essentially at first generate a computer pick (i.e. Rock, Paper or Scis... |
I wrote a card class a while back in this post here: Previous Question
I know it has been a long time but I recently came back to the project and wrote it using an enum as suggested in the answer to increase readability and to make input less error prone. I've never really used enums in Python so the question is did I ... |
I'm a beginner in OOP programming and I'm wondering what is the best way to put all the windows and functions of a window application in the code.
My biggest questions are:
Am I using classes and function in the right way?
There is an efficient way to create windows and widgets?
Why do I see so many peoples inheriting... |
What would be the best way to organize BlackJack in JavaScript and maybe start with blank slate?
Specific areas:
Updating UI
Incorporating the dealer hand into the Hand class to reduce the repetitiveness
Possibly reducing the nested IFs
Incorporating the Split
I wasn't worried about the betting amounts/payouts/chip c... |
This is a simple blackjack game I finished making using Python. I hope you like it and I'm open to any suggestions or critiques you would give me.
from random import shuffle
import sys
def deal(deck, player, dealer):
shuffle(deck)
for _ in range(2):
player.append(deck.pop())
dealer.append(dec... |
I want to start learning python for fun and so I could dig into machine learning projects later in the future maybe.
I started off with a small calculator project just to get the hang of the language and the IDE and wanted to get some feedback. I prefer progressing in baby steps and get some useful tips even though thi... |
I have a list of unique strings (approx 2500000) of different lengths and I am trying to find if there is any string which occurs as a substring of previous strings.
def index_containing_substring(the_list, substring):
for i, s in enumerate(the_list):
if substring in s:
return i
return -1
d... |
I tried to solve this Left Rotation problem on HackerRank. My code works out for most test cases, but for some it doesn't, probably because they have large number of data. So there seems to be some optimization or performance issue in my code, and I can't really figure out how to fix it. Any help will be greatly apprec... |
How to make insertJson faster (I should keep the script compatible with old versions of IE and other browsers)?
Problem
innerHTML of this section tag:
<section id="two"></section>
is created by loading json.txt to window[p]:
// Gets a tree structure JSON:
getJsonTxt({p:'dir/dir/json.txt'});
Then, it adds the generat... |
I implemented the Multiparental Sorting Crossover as described here in section 4.2. The (compiled) program can be run as follows:
$ java MPSX input.txt
where input.txt looks like this (the first line is the mask followed by three parents):
3 1 2 1 1 1 1 2 2
8 4 7 3 6 2 5 1 9
9 1 2 3 4 5 6 7 8
4 7 9 3 6 2 5 1 8
As ... |
I got some documents (size about 300o/doc) that I'd like to insert in my ES index using the python lib, I got huge time difference between the code and using curl it's obvious that it's normal, but I'd like to know if time can be improved (compared to the ratio of time)
curl option takes about 20sec to insert and whol... |
Is there a more optimized solution to solve the stated problem?
Given an array 'arr' of 'N' elements and a number 'M', find the least index 'z' at which the equation gets satisfied. [ ] is considered as floor().
Code:
counts=0
ans=0
while(ans==0):
s=0
for i in range(counts,len(arr)):
s+=int(arr[i]/(i+... |
I wrote code to (naively) perform automatic memoisation. I tried to write it in a functional programming style, and so did not make use of any global variables.
My Code
def naive_memoise(caches):
def memoise(f):
nonlocal caches
def mem_f(n):
nonlocal caches, f
if f not in cac... |
Path of Exile is a PC game where players can list their items for sale. The game has a public API that serves JSON which contains all of these items. My application consumes that JSON and indexes the items in a way that is easily searchable.
Json.NET provides an easy, one-liner method of deserializing JSON to a C# mode... |
I have a class called HtmlFile which has a method called generate. This method is responsible for generating an html file from handlebars template and data object provided in the HtmlFile class constructor.
I am confused on what code design should I use for this use case and what variable names to choose.
class HtmlFil... |
I'm a beginner coder, doing it solely for fun, having started coding about two months ago with Python. I have a working piece of code for calculating area and volume of different geometric shapes, using user input of "radius".
As I have said, the code works but I would like to know how I can improve it to be shorter, f... |
Background
I have a vba solution that I use to ingest investment text reports and reformat them for analysis in Excel. It works, but the macros involve a lot of direct manipulation of Excel objects, and have no unit-testing.
After finding RubberDuck, and reading several years' worth of excellent posts from @MathieuGui... |
Since my rather mediocre attempt at making a Space Invaders game, I stumbled on a cache of Visual Basic for Applications games written by Japanese excel wizards. I have even seen someone create Zelda?! What an inspiration! Making complete, beautiful, fun arcade / GameBoy style games inside of an Excel spreadsheet is p... |
Context:
I have some C code that uses a lot of bit-flags. The flag-sets may have a couple of hundred members. Currently these flags are defined as a 32-bit mask that must be applied to a specific element.
/* Flags: */
#define OF1_RESIST_FIRE 0x00000001L
#define OF1_RESIST_COLD 0x00000002L
#define OF1_RESIST_A... |
I have a price as a Double, which I should format it as a String.
Should I use an extension instead of classical class to encapsulate "formater", "serializers", etc? Or is there an even better alternative?
Using Class
class PriceFormatter{
let value:Double
init(_ value:Double){
self.value = value
}... |
I just dipped my toes in Java today (coming from C++) and made a few things to learn it. The standard stuff like Atari Breakout, Tic Tac Toe and this calculator. This has been done so many times before!
Calculator.java
import java.math.*;
public class Calculator {
private static final int MAX_DIGITS = 10;
private... |
Isn't there a better way to create my constants that I can use elsewhere in my code ?
export default class AppConstants {
}
Object.defineProperty(AppConstants, 'APP_NAME', { value: 'iVoc'})
/*
*...
*Other constants
*/
|
Problem
I have \$N\$ words. For each valid \$i\$, word \$i\$ is described by a string \$D_i\$ containing only lowercase vowels, i.e. characters 'a', 'e', 'i', 'o', 'u'.
We check the number of strings \$D_i\$ and \$D_j\$ which, when concatenated into a new string \$M\$, contain all 5 vowels. What is the total number of... |
I have written some code that takes two integers and returns the numbers of numbers that are both a square and a cube. I would like to know if there is a more efficient way to write this. I have only just started learning Java so any feedback would be greatly appreciated.
Scanner input=new Scanner(System.in);
double a=... |
I have the below code, which handles inbound emails in my application, saves the actual email content (text + attachments) to my database, and the saves the actual attachment files on the server.
In my Email.php model, I have the below function which handles the incoming email. The $token is the first string of the ema... |
I’m learning F# and trying to find a more ‘functional’ way to code a simple program that retrieves the price of BTC and calculates the EUR value of an amount of Bitcoin.
open System
open System.Net
open Newtonsoft.Json.Linq
let myBTC = 0.1234567
let client = new WebClient()
client.UseDefaultCredentials = true
let pric... |
This was my assignment.
Write a C++ program that reads in a series of test scores. If the test score is >= 90 && , <= 100; print the letter grade 'A'. If the score is >= 80 but < 90, print the letter grade 'B'. if the test score is >= 70 and < 80, print the letter grade 'C'. If the test score is >= 60 but < 70 print t... |
Sentiment words behave very differently when under the semantic scope of negation. I want to use a slightly modified version of Das and Chen (2001) They detect words such as no, not, and never and then append a "neg"-suffix to every word appearing between a negation and a clause-level punctuation mark. This method is v... |
This config has 3 main features but there seems to be a lot of duplication and I wonder if I could improve it.
1 Detect all pngs and jpgs in static/img and try a webp version if the requesting browser supports it
2 Detect non-ES6 supporting browsers and serve site.babel.js, otherwise serve site.js which is un-babelifie... |
I have implemented a simple dynamic vector library in C. It is a header-only library.
Full library listing -
void_vector.h:
#ifndef VOID_VECTOR_H
#define VOID_VECTOR_H
typedef enum {
VV_SUCCESS,
VV_MALLOC_FAILURE
} vv_err;
typedef struct vv {
size_t length;
size_t size;
void *data[];
} void_vector... |
Description
A robot lands on Mars, which happens to be a cartesian grid; assuming that we hand the robot these instructions, such as LFFFRFFFRRFFF, where "L" is a "turn 90 degrees left", "R" is a "turn 90 degrees right", and "F" is "go forward one space, please write control code for the robot such that it ends up at ... |
I have come up with the following snippet by building upon the answers given to my StackOverflow question. Just trying to get some other eyeballs to review things so that they can point out any egregious mistakes that I probably made.
One area that was a bit tricky to me to get working is the bottom half of the readFil... |
The following code gets 100% on the PermCheck task on Codility. It should be O(N).
The question is:
A non-empty array A consisting of N integers is given.
A permutation is a sequence containing each element from 1 to N once,
and only once.
For example, array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
is a pe... |
This code is to solve the Hacker Rank problem array left rotation.
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
Given an array of n integers and a numb... |
I wrote code to (naively) perform lru memoisation. I tried to write it in a functional programming style, and so did not make use of any global variables.
My Code
from collections import deque, defaultdict as dd
def naive_lru(mx=None):
"""
* Closure that returns a memoiser.
* Params:
... |
I have an agreement with a customer. When the agreement ends, the customer needs to pay. The amount which the customer needs to pay increases for each month that has passed since the agreement was initiated. The maximum duration is 3 years, so I have a final expiration date. From this final expiration date, I must be a... |
I have a class Record which keeps entries of strings(implemented using vector of strings). I want to keep the data member private to the class. To get entries, I have defined a member function get_entry which accepts a reference to vector of strings to store results.
Below is the code.
#include <iostream>
#include <vec... |
i'm using a dataframe full of headers/field names to develop a schema and I need unique values for each header - but each header should be represented. I want to loop though the dataframe list of fields and the second time I come across a field name, I want to add an ever increasing number to it. The order is important... |
From some generated code I get a
javax.xml.datatype.XMLGregorianCalendar and I want to convert it to a LocalDateTime without any zone-offset (UTC).
My current code accomplishes it, but I think it must be possible to acheaf the same result in a more elegant (and shorter) way.
public static LocalDateTime xmlGregorian... |
This is what I wan't to do:
In my app I've 2 custom widgets called SelectItems. If the user clicks on item, it changes the background color. Everything is working just fine, but a code, which manages the state is a bit cumbersome:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp ex... |
Review compatibility, readability, good code standards, security.
This is for development server, where webmaster uses GUI fo IDE and fine way to create quickly apache2 virtualhost using GUI but fallback to text interface is present. Second review of script with applying previous review and adding more features.
I`ll ... |
Building on a previous answer and an attempt to write a comprehensive XMLHttpRequest example that covers all kinds of possible errors and return them to caller gracefully instead of a crash.
function Remote() {}
Remote.upload = function(formData, progressHandler) {
return new Promise(function(resolve, reject){
... |
Synology NASs have a Task Scheduler that allows you to schedule deletion of files over X days old from recycle bins. This feature isn't working for me–running the task results in no files being deleted. The task works if I schedule a full deletion of the recycle bin, but I'd prefer to only delete a file if it sits in t... |
I am developing my own kind of Enumeration like SmartEnum but trying to prevent the user to provide a recursive-ish type definition like below:
public sealed class TestEnum : SmartEnum<TestEnum>
{
public static readonly TestEnum One = new TestEnum(nameof(One), 1);
public static readonly TestEnum Two = new Test... |
I have this algorithm, called Variable Elimination, which is used quite often in my code-base (library). It is an algorithm for factor graphs (a type of bipartite graphs), used to efficiently maximize something over the nodes, thus I need to make it as fast as possible.
Since I had 5 separate implementations of this al... |
This semester a classmate and I visited a course on functional programming in our university. For grading, we've to submit a small project which should be written in Clojure and make use of functional programming.
However, the topic of the course itself was mostly about Clojure and its syntax and not so much about fun... |
I'm working on a stack implementation using a linked list, but I have a strong feeling that I overcomplicated my solution. I would appreciate it if you review this code and give me any suggestions on code and style.
#pragma once
#include <functional>
#include <iostream>
#include <type_traits>
#include <stdexcept>
templ... |
I'm doing the exercices from clojureacademy.
Here are the instructions for this one.
Bob is a lackadaisical teenager. In conversation, his responses are very limited.
Returns "Whatever." if given phrase is one of the following inputs:
"Tom-ay-to, tom-aaaah-to."
"Let's go make out behind the gym!"
"It's OK if yo... |
Given a string of size 9 that represents a tic tac toe board, determine if X or O has won, or if the board is in an invalid state. Any other character aside from x, X, o, O represents an empty spot on the board.
Input: 012345678
Board:
0 1 2
3 4 5
6 7 8
TicTacToe.cpp
#include "tictactoe.h"
#include <algorithm>
#incl... |
I have trained a polygon detector neural network to recognize the mask of "quadrilateral" (the mask generates curvy lines so it's not exactly a quadrilateral). I would like to get the corners of the quadrilateral.
I believe the best approach is to get the points in the mask that are closest to the corners of the image.... |
Following is based on a problem description from a Codility test, as a task in an interview.
DeepestPit - problem description
A non-empty zero-indexed array B consisting of M integers is given. A pit in this array is any triplet of integers (X, Y, Z) such that:
0 ≤ X < Y < Z < M
sequence [B[X], B[X+1], ..., B[Y]] is ... |
I write a web app that shows events on a multi room scheduler. I use VueJS for the first time on a real project.
Here, I loop through the events array every room column (two nested v-for). In jQuery I need to loop once through this array to fill all columns at once.
My question: is there any other more efficient way to... |
I have 2 dates that I would like to have the difference between them in days and if less than a one day simply show "less than a day".
remainingTime() {
// Scientific notation of 8.64e+7
const DAY_IN_MILLISECONDS = 8.64 * (10 ** 7);
const date1 = new Date('2019-02-28T01:22:06.671Z').getTime();
const date2 = ne... |
I'm a junior developer (couple years into it) and very new to AJAX.
I'm writing an internal inventory application built on MVC and right now I'm dealing with adding and removing items to/from a cart. When the user select an item to take in or out, s/he is brought to the cart page, where they can choose to add or dimini... |
I need to get length of the longest sequence of numbers with the same sign. Assumes that zero is positive. For example:
{10, 1, 4, 0, -7, 2, -8, 4, -2, 0} → 4
{0, 1, 2, 3, -2, -4, 0} → 4
{1, -2, 0, -1} → 1
I wrote a function:
unsigned getLongestSameSignSequenceLength(std::vector<int> const& a)
{
unsigned maxlen =... |
Scientists have found that a text can still be read even if only the first and last letter of a word are in their right place. The remaining characters within the word can be arranged randomly.
Suppose you want to send a text whose content is checked for specific words by a filter. Instead of encrypting it, one could a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.