instruction
stringlengths
71
95.1k
I've been working on a program that automates the painful task of downloading each file from a website for courses one by one and sorting them using python. This is my first python webscraping project on this scale, as such I would love some advice and lessons on how to make my code better! Here is the website I'm scra...
I write this program based on the algorithm of the word frequency counter program on the K&R book, page 139. I added some idioms of mine, some command-line options, and a dynamically allocable buffer. Use it on stdin or give one or more file as arguments. The option -k considers only keywords (beginning with _ or alph...
If you could rate my code, 1-10. What will it be and provide reasoning on why you gave that answer, i feel like i could of written this code better but i don't know what i am missing or what i could have done to make it better import random print('Lets play Rock Paper Scissors') user_point = 0 #To keep track of t...
Can this be made any simpler/shorter/more efficient? This function will compute paycheck amount according to hours worked and rate per hour. def compute_pay(hours: int, rate: float) -> float: """Computes pay according to hours worked and rate per hours. For every hour worked after the 40th hour the rate per ho...
I was trying to solve the following question: You are given 2 arrays: one representing the time people arrive at a door and other representing the direction they want to go (in or out) You have to find at what time each person will use the door provided no 2 people can use the door at the same time. Constraints: the d...
I have a code, which does the following: Get data from the HrAttLogs Table Input data from the HrAttLogs Table to the HrAttLogsFormatted Table I would like to know whether the query below, which I will provide, can be improved? In terms of Performance and Speed. SELECT FingerId, ShiftId, DateIn, D...
This is my code for a 15 puzzle. The basic gist is to get a grid of equal width and height (size) and number them in ascending order, with the exception of the last square getting a 0 value ('0' integer not shown on the tile so it looks like a blank tile). The grid is scrambled and then the user has to click tiles eith...
I'm a beginner in Java programming. At the start, I wanted to make something easy and then develope it more and more. I chose to do TicTacToe game. At this point I added some menu, playing with bot, bigger map. This is my first bigger OOP project, so I'm the most curious ,if I did it correctly. Could You tell me some...
So, I am trying to generate a web-page template with JavaScript according to user specified values. I tested it with just background-color and made it working. I wanted to add a bunch of new elements. Also I need to add style to each elements. I am able to do it with the current code. But the problem I am having is tha...
I have a API and the corresponding service method is like this: @Transactional public List<Object> getData(args) { databaseStatements; databaseStatementsOnOtherThread(); NetworkCallStatements; CPUBoundStatements(calculation, sorting, etc) } With this setup, each request holds a database connection as I...
As a beginner I wrote my first program (calculator) with Python and as far as functionality is concerned it just works fine but I have some concerns about one thing at the end of the code. Under CalculateAgain() in the if statement, Calculate() is without the return statement. If I used it, it would just run the functi...
I have implemented the integer residue ring \$ \mathbb{Z}/m\mathbb{Z} \$ and the integer multiplicative residue group \$ (\mathbb{Z}/m\mathbb{Z})^* \$. Functionalities include: In \$ \mathbb{Z}/m\mathbb{Z} \$ , you can do addition, subtraction, multiplication and raising elements to a nonnegative integral power. In \$...
My goal is to make a form builder class, that generates bootstrap 4 form inside a modal. My doubt is whether I should leave it as is or if I should crate a interface and then implement that interface for all types. Also is there a better way to write html inside php? Class to generate the form class BS4Form { prote...
I am trying to implement smart pointers for our project. We're using FreeRTOS which is written with a C API so it was quite a challenge to implement sending smart pointers around but somehow I managed it by combining casts, new calls (dont really like that..) move semantics and some other tricks. On the surface it beha...
I've been struggling with python OOP. I've gone through the basics but I'm struggling with implementing them. So I've decided to create something small everyday while in quarantine to get more comfortable with OOP. My code simulates a simple coffee machine that makes 4 types of coffee. This is the first one. What do y...
I have created a program but I feel the def common(friendships, person1, person2) function can be more efficient, if anyone has any good idea how I can improve it I would appreciate it. from My_graph import Graph def friends_of_friends(friendships, person): """Return the set of friends of the person's friends. ...
https://www.spoj.com/problems/ADDREV/ My answer to ADDREV challenge on SPOJ (link to the problem given above), written in JAVA, was accepted. However, the timing was 1.23 and memory used was 82M, which doesn't seem impressive/up-to-the-mark. I'm new to competitive programming and want to know - a. In what ways can ...
I was working on a project recently that had a good amount of business logic associated with status codes. To better understand the flow of logic in the domain layer, I created an enum representation of the statuses and overloaded the equality operator in the status domain model to check against the enum. Is this g...
I would like to ask you to point me some good direction with writing clean code with Spring framework and Java in general. I am creating a simple app, which has two main features: searching for beers and being able to comment on those beers. So on the page user is presented with search form: <div class="container"> ...
This is my first time using Boost and templates in general, so I'm mostly looking for a style critique on my C++. In particular, I'd like feedback on: state_type, is there a good way to do this such that consumers of the library and the private members of the class can use this type? Other than making two separate typ...
Best way to initialize rr and cc depending on cycle number to pre-defined values in r and c. int func(int cycle, int index, int i) { char *rr; char *cc; if (cycle % 2 == 0) { char r[4] = { 0, -1, 0, 1 }; char c[4] = { 1, 0, -1, 0 }; rr = r; cc = c; } else { char r[4] = { -1, -1,...
I have a StudentSchedule class that contains schedules of a student, the student may switch between rooms over time. There's no overlap with the date ranges so if a student stops at 2020-01-01 the next record would be 2020-01-02. Given the StudentSchedule, I want a ProgramEnrollment which disregards room changes and c...
Today I learnt the basics of OOP. I have tried to apply them to this Rock-Paper-Scissors project. However I'm still a beginner, and so I feel my code can be improved. Are there any tips, trick or other other advice I can follow to improve the look, runtime, readability or take full advantage of OOP? The program is a fl...
I tried to make a password generator and at first it works as intended, generating a password with lowercase, uppercase and special characters but I can only generate passwords of up to 19 characters any more and the script sends an error about a string being too big or something. import random generator = "qwertyuiop...
Add 2 strings representing 2 doubles, return the sum of the 2 doubles in string format. Please review my code. Is there a cleaner way of writing the code where we have to add the 2 doubles digit by digit? for example, s1 is '9.9' and s2 is '8.8', we need to return '18.7'. The requirement is that we cannot pad zeros f...
Mu solution to Leetcode problem Cousins in Binary Tree works, but the code feels bulky. Is there a better way to solve this problem, particularly to use less additional variables? I will appreciate any suggestions on how to improve this code. Problem: In a binary tree, the root node is at depth 0, and children of each...
Any comments, critiques or questions about this? I'm using this as the base for a few rectangular board based toy programs like Conway's life and snake. Usage includes configuration of board size at runtime, hence the type doesn't carry size info, only the instances. #include <utility> template<typename type> class Ar...
Below is my function to solve the Minion Game problem on HackerRank along with the problem description. It works wonderfully with regular-length strings, like 'banana', but when it comes to really long ones (ones that produce output counter in the vicinity of 7501500, result in a runtime error (or memory error, dependi...
I have a string "abbbbccdddd" and the function should return "a1b4c2d4". This is what I have written in Scala. Iterative-version def compress(str: String) = { val chars = List(str).flatten.map(_.toString) ++ List(null) var result: String = "" var lookBack: String = chars.head var occurance: Int = 0 chars.fo...
I wanted to open source some code to scrape and analyze publicly-filed stock buys and sells from U.S. senators. I'm not familiar with code style for Jupyter notebooks or pandas in general. Would it be possible for you to review my short notebook? The original can be found here. Ideally I would get the scraping code rev...
I made some code about solar system stimulation in C. It is working, but it looks too long. So, Are there some ways to shorten my code? Also this website told me your code is too full to upload this. #include <Windows.h> #include <stdio.h> #include <math.h> #define solar_size 20 #define PI 3.141592654 #define rad angl...
I'm very new to the JavaScript, and hence I would like to get a feel on the language by writing some of the basic programs. One of those is the following visualization of the Bubble Sort: Code: <!DOCTYPE html> <html> <body style="background: pink"> <p id="word" style="color: black">Bubble sort: visualization</...
I was given a API project by my co-worker to work on half created a system in slim PHP. The project consists of the Models and controllers. When the route is called it calls the Controller with the necessary function in the Controller, then query data from the database in Model functions and get back the response. I wa...
I am new to Python. Amateur, enthusiast and learner. I have developed code which visits one particular website. Crawls through it to reach a certain repository, downloads the records from there to the local disk. It has too many while- and for-loops nested inside one another. It has nested functions too. How can I refa...
I am implementing a few Celery background tasks (e.g sending an email, subscribing someone to an Audience via Mailchimp API, etc.) and my project relies on a Flask application factory. Now, I am trying to understand if the way I've used application contexts makes sense at all or if it can be improved (I've quite a few...
I've created something that I called System, where you can login, create the files and delete the files. It's not any kind of big project, but it's the biggest project I made in PHP OOP so far. It uses MySQL PDO database connection. Passwords are not hashed since there's no registration page. The thing I'm not sure abo...
Here is the code for balance retrieval from EMPLOYEES record. Please simplify and improve it accordingly. It is working fine and I have no problem with it but I believe that's not the correct way to do it. Public Sub GET_BALANCE_VALUE(EMPLOYEE_ID As Integer, EMPLOYEE_NAME As String, ByRef BALANCE As Integer) Dim co...
I am having a small piece of code in my project. There are too many if condition. How can I rewrite it better to make it more readable, remove any redundancy etc and cleaner way? I am using Java 8. private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) { ...
New to python. I am converting multiple html files to csv. Developed a full code. It can easily convert 50+ files at a time but after 200+ files, the code takes too much time and with 1000s to convert, it seems that I should look for some other solution all together. Hope to receive some suggestion to speed up the pro...
we have homework in Java to do some users, contracts, and some API. We should create a user with some information about him and one of that information should be address (one where he live and one where post should come) But I am not sure if I did it correctly. I create a package called user inside which i created User...
I'm working in swift and I've got a custom class Array2D to handle fixed-width, two-dimensional arrays of integers. What I'm trying to do is write a simple, ideally-elegant function max() -> Int? to behave the same way as for a 1-D array: return nil if the array is empty, or else the maximum value in the array. I make ...
I am trying to build a 12-column CSS grid system very similar to Bootstrap. 4 breakpoints are supported: normal, sm, md, and lg. Anyway, here is the code: .row { position: relative; width: 100%; } .row [class^="col-"] { float: left; } .row::after { content: ""; display: table; clear: both; } [cl...
I am creating a c++ library implementing Java Functional Programming alike interface. In short, the code will look like this: vector<string> buffer = ... ; // A buffer contains some strings new IntStream(0, 100).map([](int a){ return (a * 0x2344DDEF) & 0xF; }).map([=](int a) { return buffer[a]; }).foreach([](st...
I came across in a code base # TODO this seems very clumsy to duplicate the loop code like this? so I figured I'd give it a shot as a learning exercise. I'd like some feedback on what I came up with, particularly: Is this proper idiomatic Julia, or close? Or am I just writing Python in Julia? What explains the differe...
In the past I have made programs that have generate a buddhabrot with mostly success however all of them were on the CPU and single threaded. As a result they were all slow so I wanted to remake the program but this time I wanted it to be fast and I decided to make it in CUDA. However I had never made a program in CUDA...
I wrote a socket library in C++, to wrap Winsock. I found it a bit tiring using winsock2 - I'd say it's a bit complex, compared to, for instance, the Python socket library. My code, header file: #pragma once #pragma comment(lib,"WS2_32.lib") #include <winsock2.h> #include <Ws2tcpip.h> #include <windows.h> #include <str...
Multiple forms make use of the autocomplete of material, which gives a resulting code that is repetitive and difficult to maintain. The controller is left with pairs of repeated methods [for each controller]. displayFn(option?: Interface): string | undefined { return option ? option.Property : undefined; } filterAut...
Application Summary I received a call from a client asking for a "simple app" that notified him via text message whenever a "Jeep Wrangler" is posted to Facebook Marketplace. It sounded simple enough, so I took the gig. I figured I would leverage FB's Graph API or possibly simply set up a filter in his account, or some...
This class represents a single entry in a log file of the Common Log Format. Can this be improved? I think I might be able to use delegation to pluck values from the matcher. Ideally I would be able to set these values at declaration time. Kotlin code data class CommonLogEntry(private val entry: String) { ...
I am currently backing up remote OS' while preserving the permissions using rsync: rsync -aAX --numeric-ids --delete ... root@X.X.X.X:/ /backup/server/ Now I want to backup the backup to a third party. I currently have: tar --xattrs -czpf - "/backup/server/" | openssl enc -aes-256-cbc -a -salt -pass pass:"$KEY" -out "...
This is a small script to update an external HDD, every night at 23:00, in the background. Can you tell me how I can improve it? What section in this code can be written as a class? Maybe the log function? This line -> from distutils import dir_util. How can I write this to follow the same format as my other imports?...
I created a simple bank program. The program asks for the user’s name and a starting balance. From there, the user can do 4 things, Check Balance, Add Funds, Transfer Funds and Exit the program. Check Balance simply returns the name of the user along with the remaining amount of funds in his account. Add Funds asks the...
This Flask app, which makes use of SQLAlchemy, a MySQL server which is only reachable via SSH and Flask-Login, is the base on which I want to write an application which has login protected pages. Registering users is a feature that I still have to write in a better way, but it works for now and testing purposes. I'm po...
I have a stored procedure the every 5 min run in sqlserver high cost iO/cpu do you have any idea to tune this query ALTER PROCEDURE [dbo].[doc_Letters_SyncBulkUpdate] @TrackerStatusSync BIT AS UPDATE doc_Letters SET [CentralDeptNo] = tempLetters.[CentralDeptNo], [IncomingNo] = tempLetters.[Incomi...
I'm beginner in rust. I would ask code review of my finite state machine. Main feature : static (event, state and transition) support pushdown It is the first step, second step is to use macro for generate section. In my example i have 3 events (e1, e2, e3), 4 states (red, green, blue , rainbow). There are 4 type ...
I recently had a need to convert a TrueType font to a Game Boy tileset, so I wrote a program to do it. This correctly aligns the characters on an 8x8 plane and outputs in the form of RGBDS-style GBZ80 assembly. Needs the FreeType library installed; use the Makefile (or copy the commands) to compile it. drawtile.c: /* ...
I'm newly exploring time series databases, and trying to wrap my head around what data I'll store and how I'll query it. Also, I'm relatively new to TypeScript. This prototype exercises my current understanding of how it will work. What I most want feedback on is: TypeScript idioms: am I following them? Does anythin...
I am calculating the log-likelihood of data that have some observations censored. For uncensored "a" clusters, the likelihood calculates P(Y=y). For censored "b" clusters, it calculates that Y is at least size Y, P(Y≥y). So the likelihood is L=mult[P(Y=y)P(Y≥y)]. The below code is my working, actual-in-use code that c...
My code passes 11 out of 12 test cases. I was wondering where I can improve my code. NOTE: This code needs performance improvement, as it is working for most of the cases. To mu knowledge it would work for all the test cases where the size of arrays is smaller than 200. Here is the question: Alice is playing an arcade...
Let me preface this with saying that it's probably not necessary to understand all the math behind this to review my code. Unless you have a lot of spare time or a very strong interest I also wouldn't try too hard to understand the background if you don't already know some of the basics, like what a symmetric polynomia...
I had just put together my first public project: simple(sane) new-handler for c++. It allocates some reserved memory on start up, then releases it piece by piece. It may also raise a signal when each piece is released. It allows to monitor approaching of low memory conditions and gracefully handle them at the system l...
the following tutorial uses an interceptor to show/hide a loading bar: https://www.freakyjolly.com/http-global-loader-progress-bar-using-angular-interceptors/ export class LoaderInterceptor implements HttpInterceptor { private requests: HttpRequest<any>[] = []; constructor(private loaderService: LoaderService) { }...
So I'm on level 5 of Google Foobar, and the Question is Expanding Nebula. It goes as follows : Expanding Nebula You've escaped Commander Lambda's exploding space station along with numerous escape pods full of bunnies. But - oh no! - one of the escape pods has flown into a nearby nebula, causing you to lose track of ...
So I was investigating overflow safe division for a class that uses an int64 member with a given RESOLUTION ( 10000 ) for the fractional part. To preserve precision in the fractional part during an easy division you would multiply by the resolution first, which if the number is large enough results in an overflow. I ca...
I'm learning python (started about 30 hours ago) and my son asked if I could make a hangman game. Well, okay, I'll give that a try. I'm sure this code is crap, but I'll never learn if I don't ask how I could have done this better. Anything that's poor practice or doesn't scale? (I won't ask what's sloppy - it's all...
This is a mix of data structure and multi threading concept based question. (This is only for understanding and learning purpose) The language for the solution : Java A Queue with FIFO behavior needs to be implemented by having underlying data structure as Stack. Enqueue and Dequeue need to be parallel and need not blo...
I have made a linear interpolation functions as a side project of mine. It assumes everything is sorted before hand - x and f(x) are the same length. I would like to ask for: general recommendations if I can improve the design (generalize it to all iterables like std::array etc...) and for further performance optimiza...
I've just learned about custom wrapper classes and I'm a bit confused about a couple of things. First, what's the utility of such tool? From what I understand you can mimic the copied class behaviour but with slight modifications. Is this tool used often? Also, could you please have a look at my code? I know I'm suppo...
The rules of John Conway's Game of Life are simple: An OFF pixel that has 3 live neighbours is turned ON. An ON pixel that has anything other than 2 or 3 live neighbours is turned OFF. Many people that program this game select the easiest of video modes: the 320x200 256-color mode. To satisfy my desire for a smoot...
Could you please tear my code apart? It's an exercise from CodeGym. Recently I changed a few things within my coding practices, namely: Not writing all my solutions on main. Instead, trying to create methods to make the code more organised. Instantiating the class on main to call the methods. Using try with resources...
So I have just started to work with SQL and I have tested my script and is working very well when it comes to my database. The database is used for shopping. What I mean by that is that I scrape a website that I love (Flowers etc) and then I collect each item that has been updated on the website and add it to my datab...
Firstly, have a good day to all, I've been trying to learn PyQt5 nowadays. I wrote a code about check box state changing depends on other check box. It looks work. I wonder your feed back. Thank you for your time. from PyQt5.QtWidgets import * from PyQt5.QtCore import * import sys class CheckBox(QWidget): def __...
Here is a "Roman Numerals" kata implementation. Given a decimal number one has to return a corresponding roman number. I have following questions: Is memory management correct? Here I assume that the caller is responsible for freeing memory. Does this code conform to c code style? Does it look like idiomatic c? Thank...
I have rewritten the Vector2 class that I usually use in my projects. The code looks as follows: #pragma once #include <type_traits> #include <utility> #include <iostream> namespace ae { // Does T support constexpr? template <Literal T> concept Literal = std::is_fundamental_v<T>; template <Literal T>...
In a bash 3 script for OSX machines, I needed the functional equivalent of the realpath command, complete with support for the --relative-to and --relative-base options. I would normally just install the homebrew coreutils formula, but I need this script to work when bootstrapping a new machine with no network or XCode...
I want to read a vector of eight bytes, convert them into hexadecimal, store them in a std::string and finally write them into a binary file. I am looking for suggestions and recommendations to improve the efficiency and readability of the code. #include <vector> #include <string_view> #include <iostream> #include <fst...
I am brand new to writing my own code. I just started the CS50x intro class and have so far made it to pset 2 readability. It's getting easier to understand what's going on. I just wanted to get some opinions on the code that I wrote to see if there were possible improvements/changes that I could make. #include <stdio....
To practice Object-Oriented Python and learning how to write tests, I found an exercise and solved it as below(all classes are put in one block of code to make the question a little bit more readable): import sys import random from typing import List, Tuple, Dict, Optional from abc import ABC, abstractmethod class Car...
I've been learning Python now for 3 months as I find it really interesting to code. I want to be able to apply for junior dev positions and as I have no formal education I thought I'd make a project to feature what I know. The project is still to be compeltely finsihed but it's got the meat of it done. I created a scri...
I find myself often encountering a use case where I need to fetch paginated data, where I need all of the data. Currently I use something similar to below to handle these cases: def fetch_paginated_data(api_base, query, good_citizen_rate): encoded = urllib.parse.quote(query.encode('utf-8')) initial = f'{api...
Goal: Goal of this application is to sign in using MySQL database and across the forms access the username and access id. Reason I am sharing the username is for only reason at the moment, is to display a welcome message for the user. For the access id, depending on what number id, different dashboard buttons will rest...
My code: https://ideone.com/DZeIZv #include <atomic> template <class T> class Seqlock { std::atomic<int> seq_; T val_; public: Seqlock(T value = T()) : val_(value) { } // concurrent calls are NOT allowed void store(T value) { const int seq0 = seq_.load(std::memory_order_relaxe...
Find a bitwise XOR for a range for.e.g (5,8) --> 5 bitXOR 6 | 7 bitXOR 8 3 bitXOR 15 12 Expected worst time Complexity - O(log(n)) Expected worst space Complexity - O(1) I have written the below code, could you please help me to improve it? static List<Integer> list; public static void main(String[] args) { ...
Introduction I've created a typed Promise implementation in Java for Android, borrowing ideas from this article for a JavaScript implementation, by Forbes Lindesay. To allow for "asynchronicity", my implementation posts callbacks (Promise.Callback) to the message queue of main thread (Looper.getMainLooper()). I don't k...
Here's a dynamic loopable string array that doesn't require a count to be maintained at the caller level. Definition char **getList() { char **items = (char *[]) {"John", "Jane", NULL}; // dynamic/variable hard coded list int size = 0; for (char **ptr = items; *ptr; ptr++) { // count items size++;...
I would like to convert a string like "1 2 3-5" to an array of numbers [1, 2, 3, 4, 5]. Following the robustness principle, the list doesn't need to be separated by spaces, comma on any other separator is accepted. The only mandatory syntax is A-B to represent range from A to B (inclusive). Also, it's ok to ignore malf...
I have written a series of functions to solve kenkens. The general strategy is to eliminate possibilities until only one remains for each cell. This first function eliminates all possibilities that can't be used to satisfy the operation and target constraints. I'm interested in any feedback concerning style and effici...
So, I've tried to make a simple math library in Rust. What do you think about it? const PRECISION: f64=512.; //Balance between speed and precision here. fn ln(x:f64) -> f64 { let mut sum=0.; let epsilon=(x-1.)/(5.*PRECISION); let mut i=1.; while (epsilon>0. && i<x) || (epsilon<0. && i>x) { sum+...
I am busy on a protected page with login and I want know if there is more protection needed. It is a very simple system without database etc... authentication.php <?php session_start(); if($_SERVER['REQUEST_METHOD'] == 'POST'){ $account = array ( 'sebas' => '$2y$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruX...
I wanted to use an external global state to a React.js application with a redux-like sort of pattern (with reducers, actions, etc). However, I don't want to use redux itself, as it's just a small project and redux might be too much boilerplate. Below is a sort of imitation of Redux with React.js Hooks and State. It's a...
I wanted to write a simple implementation for a high card game. Basically two cards are drawn and the higher one wins. Additional rules: support for multiple decks, if same suits drawn then the higher colour wins, if same colour and suit (possible as there's multiple decks) then resolve a tie by dealing a further card...
The Problem I have a module with several sibling classes that share a method with a similar name. These methods receive the same basic arguments, however, for a number of the sibling classes the method in question can take different arguments that are irrelevant to the methods defined in its siblings. For example: clas...
I'm in the process of creating my first web app using node with mongodb on the backend. I could use some opinions on the schemas/models I've set up. I have three schemas: User, Pet, Food. Here's the general relationship of them: Users have pets -> Pets have a list of ingredients and list of favorite foods -> Food has l...
I have a class Main that uses fn(cls, ...) methods from several modules; they're used exclusively by Main. Each module is 500-1000 lines long (without docstrings); the idea is to "break up" various Main methods to ease debugging and readability, instead of packing them all into one class and make a 9000+ lines file. E...
i try to make an app for a mobile store class Mobile(models.Model): model= models.CharField(max_length=30,unique=True) created_at = models.DateTimeField(auto_now_add=True) edited_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Storage(models.Model): mod...
When keeping track of various pieces of information in a variable when using a dispatch group, I've fallen into a pattern of protecting the variable using a serial queue, and then ultimately notifying on that queue to do something with the final value. Is there a more idiomatic way to protect things? Here's an example ...
This is a simple command line interface program that just keeps track of duration spent on multiple tasks. Any areas of improvements are welcomed to be pointed out. import json import datetime dt = datetime.datetime td = datetime.timedelta def encode_time(t): if isinstance(t, dt): return { '_...
A common use for Keras LSTM layers is to generate text. There are many examples showing you how to do it. The usual method is to convert the text into a sequence of tokens and then slice up the sequence into overlapping windows which is used as inputs and the windows following tokens are the outputs. So if your token s...
Goal: extract methods/functions defined in module. This excludes: Imports Lambda methods Magic methods Builtin methods Class methods Classes Non-original definitions (i.e. function assignments, alt_name = orig_fn) My approach + test below. Any room for improvement, or false positives/negatives? (In particular I wonde...
Hello, I'm a C++ beginner, learning the language while trying to code Project Euler problems. I'm having trouble coding problem 14, which I'll copy here: The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, ...