instruction stringlengths 71 95.1k |
|---|
It's taking 2.4 MB of memory and 20 ms.
It's my solution for Two Sum problem on LeetCode. How can I make it better using closures and other stuff? Kindly review the code.
use std::convert::TryInto;
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) ->Vec<i32> {
let mut status:bool = false;
... |
Consider the infinite sequence u, where u is defined as follows:
The number u(0) = 1 is the first one in u.
For every x in u, then y = 2 * x + 1 and z = 3 * x + 1 are also in u.
There are no other numbers in u.
u is sorted in increasing order, with no duplicates
The sequence:
u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, ... |
Code
List<Element> elements = GetElementsList();
ISet<string> usedInnerElements = new HashSet<string>();
foreach (Element element in elements)
{
foreach (InnerElement innerElement in element.InnerCollection.InnerElements)
{
usedInnerElements.Add(innerElement.SomeValue);
}
}
class Element
{
pu... |
I'm trying to write a JSON.stringify wrapper that never throws exceptions, and also includes properties like those on Error.
I think this means it has to:
handle cycles
handle BigInts
catch exceptions thrown by a getter
use Object.getOwnPropertyNames to find all properties, not just enumerable properties
I've had a g... |
This code solves Project Euler problem 35:
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?
from ... |
I have written an application for lawyers' offices. There is an API to fetch info about court cases. I have implemented API calls for front end when user enters particular case; one tab is filled with info from this API about this case's state in court.
This code is run from a daily cron job; for all the cases in my ap... |
Hello I have this function that takes array of objects and takes a specific value from the object and creates array of strings that can make mapped to dropdown selector.
const value = {
Value: [{
"Activity Id": "04912309-35",
"Activity Name": "SCAFFOLD SUPPORT TEAM - CARPENTERS & LABORERS",
"Start... |
I have created a splash screen library in jQuery. The splash screen will display until the website has completed loading all the images. I just wanted to review if there are any improvements.
Here is the code:
(function (window, document, undefined) {
$.SplashScreen = function (options) {
var settings = $.e... |
EDIT: Changed title, few mistakes in code were resolved (now working properly)
The GUI I am trying to make will be a simple QTabWidget, leading a user straightforwardly towards the end tab by tab.
For now, I have three *.py files - main.py, tab1.py, tab2.py. In main.py is the main window of the app and function to run ... |
I have implemented a correct version of DFS (with comments explaining the implementation):
from lark import Lark, tree, Tree, Token
def dfs(root_node : Tree, f) -> Tree:
"""
To do DFS we need to implement a stack. In other words we need to go down the depth until the depth has been
fully processed. In oth... |
I recently wrote a login function in my express application that does the following:
Verifies the user's email and password are correct
Generates a JWT Access Token with a short expiry date, and then sends it back to the user
Generates a JWT Refresh Token with a long expiry date, and then saves it to MongoDB. I will t... |
This is my solution to Leetcode #210, Course Schedule II.
There are a total of numCourses courses you have to take, labeled from
0 to numCourses - 1. You are given an array prerequisites where
prerequisites[i] = [ai, bi] indicates that you must take course bi
first if you want to take course ai.
Return the ordering of... |
I've tried, as practise, to write a Python 3 script which takes a list of paths to files/directories and compresses them with tar, before encrypting the resultant tarball with gpg (for backing up to an external location). The script allows the user to choose which compression and encryption algorithms to use, and where... |
I need to update a multidimensional array by same key paths of a multidimensional array.
I think my code can be better condensed :
//source
$array = [
"hero" => [
"name" => "Peter",
"job" => "Spider Man"
],
"dog" => [
"age" => 5,
"toys" => [
"first" => "bone",
"second" => "ball"
]
... |
I am given a CSV file of stations, with data like this:
station_id,date,temperature_c
68,2000.375,10.500
68,2000.542,5.400
68,2000.958,23.000
68,2001.125,20.400
68,2001.292,13.300
68,2001.375,10.400
68,2001.958,21.800
68,2002.208,15.500
and so on for many different station_ids.
Then I want to create a Python program t... |
This is a problem of a past bioinformatic contest (requires an account). My solution works but is too slow for some test cases.
Input format
The first line of the input contains one integer \$T\$, \$(1 \leq T \leq 3)\$ the number of test cases. Each test case is specified by four lines.
The first line of each test case... |
Background
I am devising a simple file format to store some (possibly large) binary data together with some metadata that specifies how the data was generated:
<HEADER | 4 bytes> (specifies 'size' of METADATA)
<METADATA | 'size' bytes>
<DATA>
The use case is that if at some later point I just want to inspect the metad... |
I have the following specific task, for which I have written code, in Rcpp, but it doesn't scale well and I would like to improve it. I'll describe first the steps of the procedure
Step 1:
We have matrices of dimensions (K+1)x(K+1), which have non zero values on the positions displayed, and this can be generalized for ... |
Recently I needed to expand the exports in a file to all methods in order to allow for Jest tests to cover more of the code (without using Rewire). Beforehand, only the functions used by other production files were exported, meaning unit tests only covered the exposed methods and not the non-exported ones. I'm wonderi... |
CodeSignal put out a challenge by Uber that involves writing a "fare estimator" that involves a function dependent on cost per minute, cost per mile, ride time and ride distance.
The formula is along the lines of:
fare = (cost per minute) * (ride time) + (cost per mile) * (ride distance)
where ride time and ride dista... |
I have created a snake game in Python. It is a single-player game, where the snake has to eat the red dots in order to grow longer. I just wanted to review if there are any improvements.
import turtle
import random
import time
screen = turtle.Screen()
screen.title('Snake made in Python')
screen.setup(width = 800, hei... |
I have a Send method that is working but want to refactor a portion where it is using PostAsync().Result and ReadAsStringAsync().Result. I've never written async methods before and don't feel I understand the core concept or pattern yet. Here is the original method:
public ServiceResult<string> Send(string tabDelimited... |
I am the author of this code. It's from an actual project, and it returns the desired result. However, I am very concerned that I'm not defining my Model correctly.
The Model is instantiated in the Controller. The Controller calls the instance of that Model. The Model defines itself via .map(), then returns itself ... |
Here is some working code for converting an input string to an output string:
const list = [
{ text: "i~&__", code: "\u14f0", name: 'Nasal German i with extra low tone' },
{ text: "i~&_", code: "\u14e2", name: 'Nasal German i with low tone' },
{ text: "i~&^^", code: "\u14ee", name: 'Nasal German i with extra hi... |
This is a follow-up question for Android APP connect to FTP server in Java and Android APP FTP uploading file implementation in Java. I am attempting to perform the download operation to specified FTP server in Android APP. The public class FTPconnection has been implemented for performing the download details and due ... |
I am given a file named profile1.data that looks like this:
zone luminosity
1 1 1359.019
2 2 1359.030
3 3 1359.009
4 4 1358.988
5 5 1358.969
6 6 1358.951
There are thousands of profiles in my working directory (named profileNUMBER.data). Every one of them has a unique value called a pha... |
I currently have a few "worker services" that wrap existing code to automate incredibly repetitive code. A few examples are:
Method analytics.
Iteration support.
Exception logging.
My current setup requires me to wrap my code in layers:
AnalyticsService.Run((analyticsContext) => {
IterationService.Run((iterationC... |
The below class implementing a simple way to create emails with attachments, including the option to create in-memory zip files and attach them to the email.
Because I am not a professional programmer but like to write good code I will be glad to get comments. Two main questions do I create proper email headers and pro... |
The most nauseous problem with pagination is the fact that you have to write two almost identical queries. For the various reasons I am not inclined to use the SQL-only way (such as select count(*) from (original query goes here)). Hence I am trying to modify the original query. Being aware that this method is not full... |
I wrote a python script to scrape google maps for my app. I really want my code to be readable and have tried to follow PEP-8 wherever I could, so I have come to you all for guidance.
It uses selenium webdriver to visit the google maps website in headless chrome. Then, it retrieves the page source and parses it with be... |
As someone that started to learn basic python programming, I decided to make a Python tic-tac-toe game for the terminal, to develop my OOP skills.
I would like to know if my code has a lot of repetition and if it could have been done in a shorter, cleaner, faster, more efficient and more elegant way.
import re
import n... |
I designed a phonebook application using JavaFX (trying to follow Material Design by Google, as you can see in the screenshot).
The code below is the code that handles the ButtonBar next to the search bar, but I'm new to JavaFX and I want to know if this is really poorly written and organized.
package gui;
import data... |
I created some code to represent a graph. There are two functions to operate on the graph. The first which uses a list of nodes, determines if there is a key in a graph. The second which uses an adjacency matrix finds the weight of the graph given two keys. As an optimization, the first function swaps closer to the sta... |
I wrote a network driver and I would like a review of my code. The code generally works, albeit with some performance issues. The purpose of my code is to have a Network driver that uses the USART and then the pin is there to enable the enable on the hardware so it starts to send and when is is not sending it needs to ... |
if __name__ == '__main__':
url='http://pokemondb.net/pokedex/all'
#Create a handle, page, to handle the contents of the website
page = requests.get(url)
#Store the contents of the website under doc
doc = lh.fromstring(page.content)
#Parse data that are stored between <tr>..</tr> of HTML
tr_e... |
Back in 2016, I wrote a simple C# script that exploits a generic command injection vulnerability on PHP webapps, just for the sake of demonstrating that exploits can be written in .NET languages (due to the perceived lack of exploits written in C#). The script is a bit buggy, but works for PoC purposes. I wrote a blog ... |
My code passes all the given test cases.
I would like to know a better way to to write the code.
Such as a more efficient algorithm for checking if two strings are anagrams.
import java.io.* ;
import java.util.* ;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str... |
The problem:
There are n cities connected by some number of flights. You are given
an array flights where flights[i] = [fromi, toi, pricei] indicates
that there is a flight from city fromi to city toi with cost pricei.
You are also given three integers src, dst, and k, return the
cheapest price from src to dst with at... |
I want to move all markdown (.md) files from one folder to another. The folder structure I have:
.
|-- Root11
| |-- FolderOne
| | |-- file1.md
| | |-- file1.txt
| | |-- file2.md
| | |-- file2.txt
| | |-- file3.md
| | |-- file3.txt
| | |-- file4.md
| | |-- file4.txt
| | |-- file5.md... |
I have class CellGroup that contains List of cell lists
That class has creation of list inside and transforming it to list of lists.
public class CellGroup {
private List<List<Cell>> cells;
public CellGroup(int predatorNumber, int preyNumber, int obstaclesNumber, int rowNum, int colNum){
if (rowNum > 2... |
I am working on writing code for find difference between two text files that should be ideally same.
the format of file is
docid_{num}\t{num}\t{num0},{f0} {num1},{f1} ..... {numN},{fN}\n
eg:
docid_0\t300\t5,2 4,3 9,2\n
adding link to relative big file that can be used to test:
https://gist.github.com/Lightyagami1/a539a... |
I'm learning about how full nodes can send a Merkle root + a list of hashes, so that a light client can verify a transaction.
I couldn't find any good resources on how to implement it. I just knew what nodes I needed in order to verify a leaf, so I just found those nodes using DFS.
I'm sure there is a better way to con... |
I'm trying to make a CNN in python using numpy. I have a finished product but it seems that it can be improved. On testing the convolutional layer is the biggest bottleneck
def forward(self, a_prev, training):
batch_size = a_prev.shape[0]
a_prev_padded = Conv.zero_pad(a_prev, self.pad)
out =... |
I'm working on a code snippet that generates a network graph.
def create_network(df, node, column_edge, column_edge1=None, column_edge2=None):
# select columns, remove NaN
df_edge1 = df[[node, column_edge]].dropna(subset=[column_edge]).drop_duplicates()
# To create connections between "node" who have the... |
all
This script's purpose is to check whatever the acceleration component s in order.
The IMU data sampled represent 2 samples of the imu measurements.
I'd love to hear your comments regarding readability and best practices.
import logging
import math
import sys
IMU_data_samples = [([-1.4120378002684528, -10.210593634... |
For Django sites with URLs structured in a hierarchical way I found it helpful to have an app to quickly transform an URL like https://example.com/reference/instrument/guitar/ into Home > Reference > Instrument > Guitar with links to each path part.
The following code does that:
A context processor analyze the URL req... |
I'm trying to separate the fetch logic from the component, but, due to the nature of async/await functions I have to write an async function to call other async function and I wanted to know if that's ok, if it decreases performance and what are the good practices on this.
Here's an example of a fetch function in the p... |
I think I went overkill with trying to learn new ways to do the same thing, and this is as most as I could replicate the website from freecodecamp. I'd like advice on ways to do the same things in much easier ways and better overall.
html {
font-size: 10px;
font-family: 'sans-serif';
--bg-color: #EEEEEE;
... |
This is my first program that I wrote on my own. Is there something I can improve upon?
There are a few things that still need to be added, such as:
Confirm password while registering
Adding a way to get the forgotten password using the email ID
But its functionality is minimally complete. Are there any things which ... |
I have written a C function that finds the shortest substring that can be repeated to produce the entire string.
input: abcdeabcde
result: abcde
input: abababab
result: ab
#include <stdio.h>
#include <string.h>
int
getr_seq(char *arr, int n, int mid, char *array, int length)
{
int temp = mid;
int i = 0;
int ... |
Here is a blit function for a graphics library I made.
I've built a small graphics library that uses an palette-indexed spritesheet to hold all of the game's sprites. The blit function copies parts of the spritesheet into the screen buffer, according to the sprite position on the screen.
Everything works very well, and... |
My goal is to write more idiomatic ruby when working with nested data structures. More specifically, I need to break my habit of looping through everything with .each and nested .eaches. Here's a simple example that illustrates this:
I have the following data structure which cannot be changed:
structure_hash = {
"we... |
Introduction
I wrote a proof-of-concept Flask server that accepts responses from a contact form and converts the data submitted to an email. I have added a rudimentary honeypot field that causes the form's response to discarded when the field is full. Additionally, I have integrated Google's reCAPTCHAv2 (intentionally ... |
Description
This script takes any domain input from STDIN and converts unicode domains into punycode.
Features
Any domains that throw an error get ignored.
When fed any ASCII domains, they just pass through.
convert.pl
#!/usr/bin/perl -Wn
use strict;
use Try::Tiny;
use Net::IDN::Encode ':all';
use open ':std', ':enco... |
This is a follow-up question for Two dimensional gaussian image generator in C++. Thanks for Cris Luengo's answer and JDługosz's answer. I am attempting to update the implementation of Image template class, including its constructor definitions and the check of size info. A private member function checkBoundary is adde... |
I have started learning Java last week and made this simple program to practice making conditional statements and using scanners. The program, as the name suggests, takes the input of a temperature and a weather condition to give you a suggestion for what type of clothes to wear and what equipment to carry (if needed).... |
I just converted procedural code to OOP code. Is there any performance or security issue with this code or what should I consider further?
interface
interface IContactform {
public function validate();
public function addcontact();
public function getcontact();
}
Implementing class
class customercon... |
The following implementation seems to pass all initial requirements.
Which were as follows:
Store all components in the root class allowing for any scope with a reference to the class
the ability to find or lookup active components
One reference to all components, all others would be weakref's
Ability to create a new ... |
In an Arduino project, I'm using some code which is a slightly modified version of a public library. I made several modifications to it:
I performed some minor changes I needed to make the code work.
Instead of relying on Arduino library, it makes use of the wrappers, which can be mocked in the tests.
I started adding... |
this is some function:
RequestResult MenuRequestHandler::joinRoom(RequestInfo requestInfo)
{
RequestResult requestResult;
JoinRoomRequest joinRoomReq;
joinRoomReq = JsonRequestPacketDeserializer::deserializeJoinRoomRequest(requestInfo.buffer);
JoinRoomResponse joinRoomRes;
if (this->m_roomManager.i... |
import java.io.* ;
import java.util.* ;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str1 = input.nextLine().toLowerCase();
String str2 = input.nextLine().toLowerCase();
char[] temp = str1.toCharArray(); Arrays.sort(temp);
str1 = new String(temp... |
I was able to make an implementation to detect the OS.
I'm not sure if it works the way it should, so I asked this question
TargetOS.hpp
#ifndef TARGET_OS_HPP
#define TARGET_OS_HPP
#if defined(__unix__) \
|| defined(linux) \
|| defined(__unix) \
|| defined(__linux__) \
|| defined(__APPLE__) \
|| def... |
I'm new in python and I want to know the way to improve this code with best practices.
I'm using PyQT5 to create new thread
In that thread I'm using scapy to sniff traffic and filter ARP traffic to find devices which are broadcasting the network.
In the complete code I'm filtering IP traffic too, but now I'm working on... |
I'm solving this challenge:
Given a positive integer number, you have to find the smallest good number greater than or equal to the given number.
The positive integer is called good if it can be represented as a sum of distinct powers of 3 (i.e. no duplicates of powers of 3 are allowed).
The code passes all the test ... |
Sorry for my poor English. I want to decouple receiving data and processing data, this is the demo code:
#include<memory>
#include<iostream>
#include<functional>
using message_handler=std::function<void(const std::string&)>;
class Session: public std::enable_shared_from_this<Session>
{
class PacketProc
{
public:
... |
I did this kata from codewars:
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
Examples:
"the-stealth-... |
A problem from leetcode:
https://leetcode.com/problems/process-tasks-using-servers.
I had a simple solution for it, that's using min heap to store all servers and dictionary to check whether there're free servers at a time. But it cannot pass all testcases (26/36).
Could anyone help to point out my faults?
Problem:
Yo... |
I currently this code working, but its performance is very poor — 1.45 seconds seems a bit too much for a simple recursive if statement that only checks attribute values.
def _check_delete_status(self, obj) -> bool:
obj_name = obj._sa_class_manager.class_.__name__
self.visited.append(obj_name)
if geta... |
This is a follow-up question for A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++ and A recursive_print Function For Various Type Arbitrary Nested Iterable Implementation in C++. Besides the usage with single Ranges input like recursive_transform... |
Loop through a given array 7 times and print the following output:
int[] arr = { 9, 2, 7, 4, 6, 1, 3 };
92746
13927
46139
27461
39274
61392
74613
And this is my code so far:
static void Main(string[] args)
{
int[] arr = { 9, 2, 7, 4, 6, 1, 3 };
int rotate = 7;
int printsize = 5;
int addsize = 0;
... |
How to make a C recursive exponentiation (power) function better?
I developed a pretty simple (yet decent, imo) power function for the sake of learning. I'm not quite trying to compete with math.h's double pow(double __x, double __y)
double pwr(double _base, double _exp)
{
if (_exp == 0)
return 1;
... |
Context
PlayerHouse is a place where the Player (the game character) can refill its health, store its inventory, etc. like in a RPG-game. The user can upgrade it for example to refill player's health faster and store more inventory items.
Entity in question: PlayerHouse
class PlayerHouse {
private int moneyReq... |
I wrote this code as an answer to a question. But I'd like you to have a look at it. This post is basically a copy of the answer I posted.
The code does no error checking. It assumes that the output buffer exists and is big enough and that src, orig and new are valid strings. The headers needed:
#include <stdio.h>
#inc... |
UPDATED
I have a POCO class that is populated with _context.Categories.Load():
[Table("bma_ec_categories")]
public class Category
{
[Key]
[Column("category_id")]
public int CategoryId { get; set; }
[Column("parent_category_id")]
public int? ParentCategoryId { get; set; }
[Required]
[Colum... |
I have function decodeVals in NodeJS that decodes all of the values of the given object from Base64 to ASCII. This is achieved by traversing the values of said object then converting each element one at a time via a function call to the "homemade" atob function.
Though the results are fast on objects I've tested - whic... |
I have two strings (aggregatePath and pathFromParent), either of which might be null or an empty string. I want to concatenate the two strings with a separator only if neither is null or empty. This is what I've ended up with:
FullPath =
aggregatePath +
aggregatePath is not (null or "") && pathFromParent is not... |
This is a class that allows only limited number of requests to proceed per period of time.
This is designed for use with external APIs that require such rate limiting, e.g. 600 requests per 10 minutes. I have a multithreaded application where these requests can be queued by users with varying frequency, and the goal is... |
I have written some code to find the largest palindromic sub-strings in a string without repeating any character.
Example input
abappabaxhhh
output
abappaba
x
hhh
The code
#include <stdio.h>
#include <string.h>
int is_palendrome(char *arr,int n,int l,int r)
{
while(r>l)
{
if(arr[l++]!=arr[r... |
I have implemented a MatrixIt class to traverse a 2D array. Is it possible to make the code clearer and shorter?
public class MatrixIt implements Iterator<Integer> {
private final int[][] data;
private int row = 0;
private int column = 0;
public MatrixIt(int[][] data) {
this.data = data;
}
... |
I have made the tic-tac-toe game as part of The Odin Project course.
I think the code I have written just works but is not properly optimized for performance and it could be made simpler.
This is script.js file
const gameboard = () =>
{
//setting up the player and the array of board
let board = ['','','',''... |
this is my second program that I have made as a Java beginner (started out like two weeks ago). The program utilizes scanner and arraylist to create a to do list which the user can add to and print it at the end when they are done. I would like to know if there's anything I can improve or optimize in a more simple and ... |
My QA told me that I should not use IF SELECT before doing an UPDATE statement because it will breaks the atomicity of a transaction. I'm doing some research about this but cant find any article saying IF SELECT is not a good practice for TRANSACTION.
--setup example tables
DECLARE @tblCustomer TABLE(
CustomerId int id... |
As one step in a larger builder setup, I need to build a small collection of objects, each with a small number of required attributes, and each of those with a small set of possible values. The actual scenario can be analogized to building a short list of vehicle objects, selecting the color, make, and type for each fr... |
This is the question currently I am trying to solve of codechef and I am able to get the given test cases result but I am getting Time Limit Exceeded when I am trying to submit. Please let me know what can i do in my code given below to make it more optimized.
Chef and his friend Bharat have decided to play the game "... |
Example 1
input:3
output:0011
Example 2
input : 15
output: 1111
in the below example code 15 is input.
I have taken 8 4 2 1 as array for Binary coded decimal numbering
this code is working as expected however i want to know
how can i improve or optimize on this.
static void Main(string[] args)
{
int[... |
I created two programs (one with JAVA8) to calculate the total count of uppercase and lowercase characters in given String. After checking the execution time JAVA8 is taking longer execution time than expected. Is there any possible way to optimize any of these code more to reduce execution time and complexity?
Code:
i... |
I'm currently learning haskell, and I wanted a simple project to get started. This project uses the JuicyPixels package to handle image reading. The logic of the image to ascii art algorithm is quite simple:
quantize the image in a number of bins equal to the number of ASCII character we want to use
map each pixel to ... |
A member of SO who I immensely respect just told me that the code below makes him uncomfortable.
class GameData:
def __init__(self):
self.date = []
self.time = []
self.game = []
self.score = []
self.home_odds = []
self.draw_odds = []
self.away_odds = []
... |
This is a follow-up of my question over here.
Response to @Reinderien's answer:
I have corrected the more trivial issues highlighted in @Reinderien's answer below as follows. qinghua's search engine is perpetually down and fudan's server is super slow; so we use the other 2 for the test.
I would like to seek further ad... |
latest updated version in cross-post from SO
I'm testing performance regression of some code I wrote (this is not that code) by timing its execution in Unit tests. I would like to see if execution time equals some expected value within a given degree of accuracy, e.g. <1% change. VBA doesn't have this built in as far a... |
The goal of the function below is to generate all subsets of a given set, i.e. a collection of sets that contain all possible combinations of the elements in the set. Note that for my application I do not want the empty set to be part of the result.
Exemple:
input: (1,2,3)
output: ((1),(2),(3),(1,2),(1,3),(2,3),(1,2,3... |
I'm trying to create a relatively simple class that stores global configuration in some serializable struct, and reads/writes from/to a file.
My main goal is to make this class easy to use correctly. While it's not a public library, there will be a sizable team using it in many parts of the codebase and I want to make ... |
I have an HL7 MLLP message building class I'd like to refactor. The way HL7 over MLLP works is there are multiple fields, usually delimited by the | character. Within the field, there can be lists, delimited by ^, and within those lists there can be lists, delimited by &.
So for example, the following structure:
messag... |
Source code located here
I am trying to pass extra parameters from a container to the contained application. The following bash script is working to pass extra variables, but I'm not sure that it's optimal, or a standard method for running a containerized application. Any insight would be appreciated.
#!/bin/bash
# al... |
I have some code like this
ngOnInit(): void {
this.activatedRoute.url.subscribe(() => {
const token = this.activatedRoute.snapshot.queryParamMap.get('token');
const redirectPage = this.activatedRoute.snapshot.queryParamMap.get('redirectPage');
if (token) {
localStorage.setItem(Authentica... |
I wrote a code that given a string (txt), will print a histogram that contains the number of occurrences of each word in it and the word itself.
A word is defined to be a sequence of chars separated by one space or more.
The code is working, I just want to see if I can improve it.
def PrintWordsOccurence(txt):
lst ... |
map is a builtin function that takes one function func and one or more iterables, and maps the function to each element in the iterables. I wrote the following function that does the reverse, but it feels like this is such a basic operation that someone must have done this before, and hopefully given a better name to t... |
I started with the following module:
Module DemoStructure
@json_data = {...} # hash of json data, etc
def self.website_data
@json_data.map { |site_hash| hash.merge({ 'scope' => 'website' }) }
end
def self.find_field(source_data, key)
data = source_data.flat_map { |tmp_data| tmp_data[key] }
data.re... |
Warning: sound (not loud, and volume is set to 0.5 in the code)
My goal here is to get anyone who enters the webpage synchronized as well as possible.
Say there's some global clock. Since Javascript's Date.now() is based on the device's clock, relying on it isn't good enough.
So, I'm using worldtimeapi which returns th... |
I'm learning and looking for at least "not bad" quality of my code. Please let me know how should I improve.
#!/usr/bin/env python3
import subprocess
import re
battery_status = subprocess.run('upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep percentage:',
shell=True, capture_output=True, text=True)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.