instruction
stringlengths
71
95.1k
Python has itertools.chain(), but C++ has nothing. This is my attempt to implement such a thing. Looking mainly for comments about potentially smarter ways of doing things or potential pitfalls this code falls into based on its current implementation. Currently, the objects that chain() will give back will be a referen...
I have the following code which returned the solution I was wanting after running for 1 hour. Are there any techniques I could use to improve run-time? If I were using imperative programming I would just more aggressively cache the partial results, but that's less appropriate for this approach. How should I transform t...
This is a class to encode and decode SGTIN96 product identifiers, typically used to write EPC on RFID tags. Refer to EPC(TM) Generation 1 Tag Data Standards Version 1.1 Rev.1.27. import java.math.BigInteger; import java.util.HashMap; import java.util.Map; // Refer to EPCTM Generation 1 Tag Data Standards Version 1.1 R...
I've created a recursive depth-first search implementation in Java as an example for an article I am writing on my website. It needs to be concise in order to fit on the page easily (independent of screen sizes), hence the lack of extra spacing. public static boolean depthFirstSearch(TreeNode find, TreeNode top){ if...
I have built RESTful web services. The services endpoints have a similar logic: If the input validation succeeds, do a database operation and return the result. If the db operation fails, return the db error. If the validation fails, return a response with information on the failed validation. My code was explicit in...
I'm learning Scala (and functional programming). Is there a better way to solve Euler problem 4 than either of these two solutions. Euler 4 I like this array comprehension solution, but it wastes so much space. def isPal(n: Int): Boolean = { val sN = n + "" sN == sN.reverse } def euler4Iter: Int = { var largestPa...
This code interprets an abstract syntax tree generated by a recursive descent parser for a dynamic scripting language called Hassium. The syntax of this language looks like this # Recursion functions func fibonacci(n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } return fib...
I have made a basic stack class utilizing a linked list for data storage and \$O(1)\$ push and pop and just want some basic feedback on the class to see if there is anything basic I missed. It seems to be working perfectly and I know there are no memory leaks. I'm just being cautious and wondering if there is one or tw...
Root to leaf path sum equal to a given number Given a binary tree and a number, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given number. Return false if no such path can be found. I have written 3 solutions: one recursive, one using 2 stacks (DFS), and...
I completed a sample programming challenge and wanted to find out how I could make it more efficient. I'm trying to get better at writing more efficient code, so I would be interested in hearing ideas on how I can make the code more efficient. I ran it, and it works, just curious if there are inefficiencies that some o...
This following code executes correctly.I was wondering if there are better ways to write this code instead of using while(true) and break.For example using expressions,flags, do-while,etc. import java.util.ArrayList; import java.util.Scanner; public class Words { public static void main(String[] args) { Scanner re...
I have created a simple system to get hands on experience with OOPS design and some features in Java: The system is: A ClassOfStudents contains Students A Student contains a list of scores A Student can be a PartTimeStudent or FullTimeStudent A score is valid only if it is between 20 and 100 I have: Used enum for ge...
This finds a peak element in an array. Please consider I want only one peak element. Also, my code should follow only C++11/14 and not C++03. #include <iostream> int peak(int * arr, size_t size) { auto start = 0; auto end = size - 1; //empty array if(arr == nullptr || size <= 0) { return -...
I would love my component to be reviewed. I am looking forward to responses mainly answering the questions: Is my code violating the SOLID principals? If so, where and how? Does my component contain any flaws? Does my code contain any security issues? Does my code follow the OOP principals? Can my code be optimised? I...
I have a JSON array or literal (passes through JSON.parse). Requirement: an array of tasks which contains operations which are key/value pairs. Array of tasks > Array of operations (array of operations at times will contain duplicate key/value pairs) [ [ { resize: [1200, 1200] }, { ...
In the Wikipedia article about the binary search algorithm, a small paragraph in particular got my attention: Midpoint and width A different variation involves abandoning the L and R pointers and using a current position p and a width w. At each iteration, the position p is adjusted and the width is halved. Knuth stat...
I've a working function. But it feels complicated and doesn't look too good, I would like to improve it. function Modes(arrays) { var frequency = {}; // array of frequency. var maxFreq = 0; // holds the max frequency. var modes = []; for (var j in arrays) { frequency[arrays[j]] = (frequency[ar...
I wrote a class that can convert to and fro from Roman Numerals and Decimals. I would appreciate critical points on everything, especially: Shortening my code. Choosing a better approach. Using better/new features of Java 8. And so on... I didn't add JavaDoc because I am expecting suggestions for a better approach. I...
Problem here. It's not exactly the brute force approach but I'm not using any sort of pre-calculated primes table, and I'm definitely not using the coprimality trick shown in the PE pdf. I'm finding the divisor count for each triangle number via its representation as a product of primes. More on it here. I've written a...
I've been working on this elevator program for quite some time now and finally finished it and made it work and I'm pretty proud of myself, but I'd like to see ways how to optimize my code so I can learn for the future. By optimizing I mean, making the code look better, maybe by using less lines of codes. public class ...
Is this a good use of the decorator pattern? If not, why not? Is this a good idea to use for example when we have objects communicating with MVC through PHP or via ASP? To send data through the model to a decorator class that extends so ; and also using this data to extend to other classes. For example, in theory one c...
The object is to notify if a plane was found or not. The aircraft_identifier variable is a must. cpl_id and target_no are optional, only either of them can be applied at time not both, they are used for further identification if aircraft_identifier is not unique. qo = 'squawk' or 'callsign' # only these variants are p...
I'm currently working on reincarnation of the Cactus project, Cactus Reborn, and I've gotten the basic implementation so far. At this point, you can create simple, playable games. There are currently three usable classes/functions: Location - This class describes data about a location in a GameFlowchart class, like a ...
I wrote this simple key-value interface on top of Sqlite3 to use in my Android app. I am using this to persist Java objects as strings converted using Gson. The public API has 3 methods. get(Context context, String key, String defaultValue) set(Context context, String key, String value, Integer persist) clearCacheByL...
Just to reiterate my prev. post, as I think it helps structure my weaknesses. Coding methodology: Is the algorithm I used feasible or mostly correct? If not, how do I correct it and why won't it work or scale? I realize in some cases there are always going to be optimal solutions that will be over my head mathematica...
I'm writing a bash plugin to help people create books in a specific way. It's an ordinary shell script to setup the project and create its subresources. I'm using a loop to create barebones assets and then seek to checks-in the project into a repository as well. The plugin will eventually provide simple commands such a...
For our first assignment in our algorithm class we are suppose to solve several different questions using information from a 2D array. We are also suppose to optimize our code to get more marks on our assignment. We also are only allowed to use 1D and 2D arrays as the only data structure. The problem was find the uniqu...
I'm fairly new to C++ programming. To help I've been writing my own data structures for practice. I'd liked this to be judged as if it was written by a professional, and receive honest feedback. I already have a few concerns. Am I managing memory correctly? I don't believe I have any leaks. A lot of advice I get when ...
I have this number returned from an Ajax request: 015-0011-00001. I want to increment the last part of the number (00001) on document load. What I did was get the last number and increment it then combine the numbers again. Is there a cleaner way of incrementing this number without slicing the number into many parts? D...
Can this extension method be improved? public static string GetAvatar(this System.Security.Principal.IIdentity user) { var service = SmObjectFactory.Container.GetInstance<IApplicationUserManager>(); return service.FindByIdAsync(int.Parse(user.GetUserId())).Result.Avatar; } Now in my view I...
I was asked to change code that I maintain (but didn't write) for a learning management system that previously listed an examed course both under examed courses and other courses and now my task was to exclude the examed course from other courses. The following is the bugfix that I would like you to review: for ter...
Currently I am assigned to a project which has a standard view-flow, yet this flow is determined by whether settings are set to either true or false. So, for example, let the standard flow be View1 > View2 > View3. When the customer has no need for View2, the application should be adjusting this to View1 > View3. It i...
I made this method for a better Toast function. But I have doubts about it because this Toast forced me to make two methods while using two types of contexts. Now I would like to improve it by shortening my code and choosing a better and more professional approach (overall structure, splitting onto logical units, accor...
I got rejected for a junior Ruby job entry where I had to solve a 2D matrix as a maze with walls. This is the main class: solver.rb require 'json' class MazeSolver def initialize(file) @file = file @data = "" @table = Array.new @table_reversed = Array.new @table_merged = Array.new @table_con...
Scenario: I need to insert a record in a database and use the id resulting from that operation for every other operation needed. So I've created a class that contains all details of the object that needs to be persisted in the database and added an Id field to store the record id returned by the database operation. pub...
I am new to Qt and am trying to understand object destruction and where I need to explicitly destroy objects using delete. class MainDialog: public QWidget { Q_OBJECT public: MainDialog(QWidget *parent=0); private: QPushButton *m_newClick; QPushButton *m_editClick; MainContact...
Given You are given a square matrix of size \$N×N\$. Calculate the absolute difference of the sums across the two main diagonals. Input Format The first line contains a single integer N. The next N lines contain N integers (each) describing the matrix. Constraints \$1\leq N \leq 100\$ \$−100 \leq A_{i} \leq 100\...
To expand from the changes supplied by the answer of my previous question: #include <condition_variable> #include <iostream> #include <random> #include <mutex> #include <thread> #include <vector> // global variables std::condition_variable cv; std::mutex mtx; std::vector<char> data; int count = 0, buff_size = 0; cha...
I've created a second 'calculator-like' program, this time using the JOptionPane rather than typing in the console. At the moment the code looks to have a lot of repetition so I'm looking to simplify it; any advice and suggestions would be great! import javax.swing.JOptionPane; public class SaveCalc { public sta...
I am going to run a private Node.js app in a local network which will take user code submissions and evaluate them. Since it is a trusted environment (just friends), I have not bothered at all about any kind of security. I am new to Node.js and this is only my third app. I am seeking review of the function that actuall...
Inspired by an earlier question I've made a temperature converter that can convert from one temperature to another and optionally output a series of conversions. This was made in Visual Studio 2015 but it also compiles with g++ and clang++ on Debian with no warnings. Usage tc.exe -40 c f Celcius | Fahrenheit...
I was reading Wikipedia about maze-algorithms, and I decided to write my own maze-solver. It uses dead-end-filling as it seemed simple to implement (it seemed, I said). The code I wrote is pretty massive, 179 lines including documentation and tests, but I like that it solves my easy examples. I included some ASCII-anim...
I'm at the point where I am happy with the functionality of my code but I dislike how its written. It seems like I can be more modular with it but I can't seem to figure out how to improve on it without changing to much. I understand that I can probably merge both getMed Methods but they are end points in a URL which I...
See the next iteration. I wrote this simple C program for writing computer generated music to a WAV file over three years ago. I refactored it a little, but it does not look good to me. Any suggestions? #include <stdbool.h> #include <stdio.h> #include <stdlib.h> /****************************** * Magic file format str...
I am trying to create a two player Chess game. To do this I want to generate a list of legal moves. I am having trouble with the brevity of the code to generate the moves for the rooks and bishops. The code I have pasted below works (i.e. shows legal bishop moves) but there is a lot of repetition, which is not ideal. T...
So, here's a program in python to get the count of digits that divide the number. If you give the program a list like [24,10245], you get an output of: 2 2 This is the code: def count_div_digits(l): for number in l: count=0 digits=str(number) for digit in digits: if digit=='0': ...
I wanted to learn how to use python to replace bash, and found this old post from 2008 or 2009. The output of git has changed a bit, though, so I decided to remake it. I also decided to try out docopt and sh. Everything from sh I guess can be replaced with subprocess or os, but I thought it looked like an extremely con...
I wrote a word splitting function. It splits a word into random characters. For example if input is 'runtime' one of each below output possible: ['runtime'] ['r','untime'] ['r','u','n','t','i','m','e'] .... But it's runtime is very high when I want to split 100k words do you have any suggestions to optimize or write...
I did InfiniteStream by implementing Stream and Consumer. You can initiate the stream then consume an object using it. I've added queueing for it to handle storing more than one value from accept. Please provide feedback. public class InfiniteStream<T> implements Consumer<T>, Stream<T> { private static final int LE...
Given a number, for example, \$6\$, this Python function should print hashes in the following format: # ## ### #### ##### ###### This is the function used to accomplish this: def hash_print(number): for i in range(number): hashes='#' *(i+1) spaces=' '*(number -(i+1)) print(...
I have a web page containing n pages of paged data, showing 20 records at a time. The front end has a link to another page that opens the same data, but without the paging and calls window.print on document.ready. On my paged content view I have a link: <a href="printallthisstuff.php" target="blank">Print all items</a>...
I have a config file stored in a java properties file: output_path=/some/path/somewhere num_threads=42 # ad infinitum I have an singleton enum which controls the building of the config: public enum ConfigFactory { INSTANCE; public static final String OUTPUT_PATH = "output_path"; public static final String...
Started as to make a stream splitter to split stream based on condition, but finally found that I did ConsumingRouter, to consume based on condition and while have to provide consumers before using this router not as splited stream can provide consumers then , and use this router inside forEach of stream, please check ...
I have a single class which converts an image's colors into greyscale (except one given color, which will be left as it was before): class OneColorFocus { private let redMultiplier = 0.2126 private let greenMultiplier = 0.7152 private let blueMultiplier = 0.0722 private let cLinearThreshold = 0.0031308...
The problem statement is to write code that returns the sum of the K largest elements in a given array. The array is not sorted already. My solution is based on the idea of quicksort, by finding pivot elements until the pivot is actually the kth element. Thus, all elements left of the pivot will be larger than the pivo...
All the services I run on my server are based on Unix accounts. Since most web services have their own users and perform all the account management separate from the actual system accounts, I created a CGI script that handles: Changing passwords (requires old password) Assigning contact info (requires password) Reques...
For my internship I have to perform certain analysis to determine residuals and outliers. The table I'm currently using has over 12 million records with 130+ columns. My first tests take approx. 5398 seconds or 1.5 hours to apply the module and establish outliers and put them into a plot. The goal of my project is perf...
I should say that the code I have works. I feel like there has to be a much more efficient way to do it (especially when I just crashed my server with it). Relevant schema: create_table "item_total_stats", force: :cascade do |t| t.integer "item_id" t.integer "item_stat_type_id" t.integer "stat_amount" ...
I'm trying to improve my Angular directive. I'm pretty new to CoffeeScript, so I think there may be inconsistent code. 'use strict' class Main extends Directive constructor: (VerifyService) -> return { restrict : 'M' link : (scope) -> scope.watch 'events', -> ACTION = boo...
std::chrono::duration is a great example of how to create "units" using std::ratio. std::ratio by itself is not very useful for a "units" library, and the two choices are either something like Boost.Unit (which can be very complicated to use) or to write it yourself (why reinvent the wheel?) Therefore I'm trying to wri...
Given the Free Monad, and my Eq, Show, and Functor instances, I attempted to verify the first Functor law using QuickCheck: data Free f a = Var a | Node (f (Free f a)) I defined the following Eq and Show instances (credit to duplode for helping me out on the Eq instance: instance (Eq (f (Free f a)), Eq...
I am using the following code to lazy load some social buttons in my personal blog. Before continue, I would like to enumerate some dependencies first: jQuery 2.1.4; Using Font Awesome 4.1.0 (but should work with any icon/font); Tested on the most recent Firefox, Chrome, Iceweasel and Safari; So, the following HTML i...
I want to convert these loops into simple loop. I want the code to look neat and short. I saw answers related to LINQ but couldn't make out from that. Are there any other possible ways for this snippet? XmlDocument manifestXmlFile = new XmlDocument(); manifestXmlFile.Load(manifestFileName); foreach (XmlNode rules in m...
You're given an array containing integer values. You need to print the fraction of count of positive numbers, negative numbers and zeroes to the total numbers. Print the value of the fractions correct to 3 decimal places. Input Format First line contains \$N\$, which is the size of the array. Next line contai...
See the previous and initial iteration. See the next iteration. Now I have refactored the code according to many suggestions made in the first iteration. What's new: I attempted to deal with endianness. I have zero chance of running this on a big-endian machine. If you do, could you add a minicomment whether it works...
I am currently working on an eCommerce project in Laravel 5.1. I have implemented Repository Pattern by learning from this site only for 1 model, namely, Carousel just to test myself as I am still at the learning stage. Now I want my code to be reviewed, before moving on to the next part of my project. CarouselReposito...
int bin_search(int* a, int key) { int lo = 0; int hi = sizeof(a)/sizeof(int) - 1; while(lo <=hi) { int mid = (lo + hi)/2; if(key < a[mid]) { hi = mid - 1;} else if (key > a[mid]) { lo = mid + 1;} else return mid; } return -1; } .... for(i = 0;...
I want to receive advice on my code. It is too slow... The problem I am trying to solve is: What is the value of the first triangle number to have over five hundred divisors? import math import numpy as np import copy from operator import add memoi_table = {} #check whether the x is prime or not #to do a prime facto...
A function mycommand which runs command and: Gives me three log-files which are: *.stdout.log: everything from stdout *.stderr.log: everything from stderr *.full.log: everything (i.e., both stderr and stdout) Prints all output to screen The idea is that I can quickly see through the errors, skim for additional inf...
We are using the Thread of a common base class but using its handler in all its sub classes. The code is working fine but is it the right way to go about? Our base class looks like this: public class BaseActivity extends AppCompatActivity { public Handler mHandler; protected void onCreate(Bundle savedInstanceS...
Is it possible to shorten the following jQuery code into one single block? At the moment, the current code is 2 blocks, but it is practically identical. I tried adding .break-row to the first selector but this then results in the incorrect value of k. $(div).find('.overtime-row').each(function(k, subRow) { // get...
I am having a problem describing what the following code does. Below is my attempt at its javadoc. /** * Convert an integer so that the notion of its size fits within a certain number digits. * e.g. * Fit 123 to 2 digits -> 99+ * @param in The integer * @param order The order of magnitude to fit it in. * @return ...
So my web app requires JWT authentication and I decided to make a mockup wrapper class for php-jwt before implementing it into my web app: class JWTWrapper{ public function newToken($issuedAt, $notBefore, $expire, $server, $sessionData){ $tokenId = base64_encode(mcrypt_create_iv(32)); $notBefore = $...
This is my function to procedural generate an infinite random map of 1's and 0's it only calculates what you can see at the time and when the view moves it calculates the next rows. Complexity is the size of the view that is on the screen e.g. if complexity = 7 then the view on the screen is a grid 7x7. It works fine b...
I have a table post with a many-to-many relationship with the tag and product tables. post \$\rightarrow\$ tag post \$\rightarrow\$ product How can I make this faster? For example, if I have post, I can get similar posts similar by tags and products: Post.php <?php namespace Ranger\AppBundle\Entity; use Doctrine\OR...
Problem : source Which starting number, under one million, produces the longest chain? n → n/2 (n is even) n → 3n + 1 (n is odd) I want to receive advice on my code. It is too slow... It takes 514 seconds import math from functools import reduce import time start_time = time.time() target = int(math.pow(10,6)...
Was hoping someone could sanity-check this SQL statement. I need to find the owner (schema), table, and column on both sides of a foreign key: SELECT s1.name AS FK_schema, o1.name AS FK_table, c1.name AS FK_column, fk.name AS FK_name, s2.name AS PK_schema, o2.name AS PK_table, c2.name AS PK...
I was trying to solve this problem. Problem Statement You are given a pointer to the root of a binary tree. Print the top view of the binary tree. You only have to complete the function. For example : 3 / \ 5 2 / \ / \ 1 4 6 7 \ / 9 8 Top View : 1 -> 5 -> 3 -> 2 -> 7 I figured...
Here is a code I'm working on that alters a individual letters.Each letter is pumped up x amount of letters. This alteration is dependent on the length of the word. So for instance "hi" becomes "jk", "there" becomes "ymjwj", and thus "hi there" is "jk ymjwj". I want to this code to not encrypt put to also decrypt messa...
I tried to calculate the following problem by brute force using R (under the assumption that a single pair of parenthesis would suffice). Make 10 from the numbers 1, 1, 5, 8. You can use the operations + – * / (). You have to use all the numbers, and use each number exactly once. The operations can be repeated (l...
I am delving into trying to write some JavaScript code. I understand the basics, (the very basics...) enough that I have been able to write the following and it works. However, my knowledge doesn't stretch enough to be able to work out if this was the "best" way to write what I am trying to achieve. I don't want to j...
I know that this code would look a lot better if I made it so that checking the current prices against the open prices were in a function. This would avoid rewriting it for every stock I want to check. But I'm not sure how to get started on doing that properly. Do any of you have some tips to get me started? from yahoo...
I have written a program to convert a decimal to a Roman numeral. I am wondering if my algorithm is okay or not. If it's not okay, I want suggestions on improving my code. This code only works for inputs up to 5000. I found this question in a code cracker competition at my college. #include <iostream> using namespace s...
This is a (fairly) simple IRC bot. The whole idea of it was similar to Duga, except that it will post to an IRC server instead. The bot takes messages from a SQL table and posts them in the IRC server. It supports a few (basic) commands which are sent as private messages to the user who requested the command. The bot i...
Is there a way to write this code more efficiently so that it is easier to read, maybe using loops and lists? import random total = 0 sixes = 0 fives = 0 fours = 0 threes = 0 twos = 0 ones = 0 limit = 50 throws = 0 Total = 0 play = input("Do you want to play, 'Y' or 'N'") if play.upper() == "Y" : play = True else ...
I would like to properly raise an error if self._header was not created when I initialize a NewFile object. This is working now, but perhaps there is more formal way of catching the error below: class NewFile(object): """ Docstring """ def __init__(self, filename): self.localdir = 'C:\\Users\\User\\Doc...
The other day, I started thinking of a new personal project to start that I wanted to do in Java. As I started to do it, I realized that I was constantly deleting classes, creating new ones, merging them, etc. I finally have come to the conclusion that my understanding of OOP is not very strong. To practice, I thought ...
I've written a simple program in C++ to practice OpenGL. It takes a set of numbers through stdin and then plots it in Decartes coordinate system with x for position in input, and y for the value itself. Example Input: 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 Points to paint: (0, 1) (1, 4) (2...
There is method GetFull that should use OData return related entities. When I call GetFull(12, "entity1,entity2") then I will get to current object with id = 12 and related entity1 and entity2 (http://.../api/City/12?$expand=Region) When I call GetFull(12, "0") then I want to automatical find and get all related entiti...
As per a previous question here and answers I got, I used it to get a new implementation. I found that I have to make two implementations match once "to ignore other consumers after matching once" and match all "to execute all consumers its filter matching the input", and made a common interface to abstract usage of tw...
I have written the below program to write a Java stack implementation. I have added a method which returns the maximum value in the stack, e.g, a pop. The implementation for this is based on the Max Heap Sort algorithim. I have little doubt on the time complexity analysis - it's not \$O(\log n)\$ is it? public class St...
I've built the beginnings of a numerology calculator, and would like an experienced javascript developer to review this code. It works as expected, but I can't help but think there is a better way to write it instead of using multiple for loops. There are a few calculations that have to be made, so I can't see any way ...
As Optional have only ifPresent and not have another function to be run in false case so I did the below class for that, please check it and give me your feedback: public class OptionalConsumer<T> { private Optional<T> optional; private OptionalConsumer(Optional<T> optional) { this.optional = optional; } public s...
I'm teaching myself C++ by reading Stroupstrup's Programming Principles and Practice Using C++, and I'm working on an exercise in chapter 4. The exercise asks to convert input as a digit to the corresponding spelled-out value e.g. input of 1 gives the output "one". #include "std_lib_facilities.h" using namespace std; ...
Problem I want to receive advice on my code, which takes 0.012 seconds. import numpy as np import time start_time = time.time() raw_data= """ 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 2...
In order to exercise and learn Clojure, I decided to write a simple Minesweeper game from scratch. I'd consider myself as a Clojure novice and would be thankful if somebody could do a review or give me feedback on the code. The full repository can be found here but I'd be also happy if somebody could have a look on th...
I designed my repository class and I need some advice from you. Now I have a method GetByID that returns a generic type: public T GetById(object id) { return this.Entities.Find(id); } I'm going to use OData to filter data, and for that (when I'm using $expand for single row) I need to do something like this: Si...
Given Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.) After typing the sentenc...
I am learning OpenMP+MPI hybrid programming. As an example I have chosen Gauss-Seidel+SOR. My implementation uses MPI_THREAD_FUNNELED style hybrid programming, overlapping of communication and computation, neighbourhood collectives, MPI IO etc. Based on my analysis and running many executions it seems to be correct (ca...
I think the running time of this should be \$O(log_{2}(n))\$: def count_bits(num): assert num >= 0 count = 0 while (num != 0): num >>= 1 count += 1 return count print count_bits(0) #0 print count_bits(2) #2 print count_bits(pow(10, 2)) #7 print count_bits(pow(10, 9)) #30