Most efficient way to insert into ordered sequence I have a dashboard like interface, that can have many tabs. There can be as many or as few tabs as the user likes, with the user being allowed to re order them as they wish. Exactly like browsers do.

My problem is moving the tabs position, for example, look at these tabs:

[Sales] [Admin] [Finance] [Development]

If the user wants to move the [Development](index 3) tag to be after [Sales], giving it a new index of 1, how should I bump Finance and Development along to 2 and 3 respectively?

I am using JSON to store it so data.dashboard[0].sequence merely means the sequence value for the first dashboard.

At the moment I am using the following bit of code, which seems a bit hacky and not as efficient as it could be. The function is called with the start index(3 in this case) and the desired or end index (1 in this case). I've tried my best to explain with the comments, but feel free to ask anything you don't understand:

function changeSequence(start, end){
  var newVal = 999;
  for(d=0;d<data.dashboards.length;d++){
    if(data.dashboards[d].sequence == start){    // set [Development] to 999 temporarily
      data.dashboards[d].sequence = newVal;
    }
  }
  if(start > end){
    for(i=start; i>end; i--){
      var d = i;
      d--;
      for(j=0;j<data.dashboards.length;j++){     // if [Development] (index3) is after
        if(data.dashboards[j].sequence == d){    // [Admin] (index1), bump indexes
          data.dashboards[j].sequence = i;       // 1 and 2 along one (to 2 and 3)
        }
      }
    }
  } else {
    for(i=start; i<end; i++){
      var d = i;
      d++;
      for(j=0;j<data.dashboards.length;j++){     // else if [Development] (index3) is
        if(data.dashboards[j].sequence == d){    // before [Admin] (index1), which it
          data.dashboards[j].sequence = i;       // isn't in this case, bump them all
        }                                        // down one
      }
    }
  }
  for(d=0;d<data.dashboards.length;d++){
    if(data.dashboards[d].sequence == newVal){   // then set [Development]'s new
      data.dashboards[d].sequence = end;         // index to what its meant to be
    }
  }
}

This code works, but I feel like I've gone the long way and simply going from

[Sales] [Admin] [Finance] [Development]

to

[Sales] [Development] [Admin] [Finance]

Should be that hard

Edit: Still learning, so even unrelated ways to improve my code would be great

Fundamentally, you should probably use the array's own ordering. It'd remove the need for a sequence number that you manually have to track and update. Instead, you can simply pluck index 3 out of the array, and splice it in at index 1, and not worry about sequence numbers at all.

But if you can't/won't get the data.dashboards array to behave like that, you can take a detour.

Now, I highly, highly doubt this is the most efficient way of doing things - it's certainly not elegant - but it's straightforward to follow.

Say you have this:

var data = {
    dashboards: [ // random ordering
        {name: "Development", sequence: 3},
        {name: "Sales", sequence: 0},
        {name: "Finance", sequence: 2},
        {name: "Admin", sequence: 1}
    ]
};

Get everything sorted first:

var sorted = data.dashboards.sort(function(a, b) {
    return a.sequence - b.sequence;
});

So now we have an array where the objects are ordered according to their sequence

seq | name
------------------
0   | Sales
1   | Admin
2   | Finance
3   | Development

Then, if we can assume that the sequence numbers are indeed sequential with no gaps or repeats, we could (again) just splice & splice to get the right order.
But let's say we can be sure that index equals sequence number. In that case, loop until we find it, pluck it, and reinsert it:

var currSequence = 3, // the target's current number
    newSequence  = 1, // the target's desired number
    dashboard;

// find and move the target
for( var i = 0, l = sorted.length ; i < l ; i++ ) {
    if( sorted[i].sequence === currSequence ) {
        dashboard = sorted[i];
        sorted.splice(i, 1); // remove the target
        sorted.splice(newSequence, 0, dashboard); // re-insert it at its new position
        break;
    }
}

Now, we have the right order, but not the right sequence numbers:

seq | name
------------------
0   | Sales
3   | Development
1   | Admin
2   | Finance

Finally, reset the sequence numbers

for( i = 0, l = sorted.length ; i < l ; i++ ) {
    sorted[i].sequence = i;
}

And we get

seq | name
------------------
0   | Sales
1   | Development
2   | Admin
3   | Finance

Neatly sequential numbering and ordering, regardless of the original array's order and sequence values. The original data.dashboards array is still in the same scrambled order as before, but the sequence number of each object is now correct.

Here a jsfiddle

Actually, here's a simpler one that I believe works in all cases, regardless of array ordering, as long as the sequence numbers are sequential already:

var currSequence = 3, // the target's current number
    newSequence  = 1, // the target's desired number
    correction = currSequence > newSequence ? 1 : -1,
    lower = Math.min(currSequence, newSequence),
    upper = Math.max(currSequence, newSequence),
    dashboard;

for( var i = 0, l = data.dashboards.length ; i < l ; i++ ) {
    dashboard = data.dashboards[i];
    if( dashboard.sequence == currSequence ) {
        dashboard.sequence = newSequence;
    } else if( dashboard.sequence >= lower && dashboard.sequence <= upper ) {
        dashboard.sequence += correction;
    }
}

Here's a demo


Finding the longest substring in a string I am writing Python code to find the longest substring in a string which is an alphabetical order. I tried to minimize the number of loops to a single for loop.

Any improvements would be appreciated. Any details about the complexity of this algorithm would also be welcome, because I don't know Big-O notation all too well.

substr = '';
final_substr = '';

for index, char in enumerate(s):
    if index < len(s) - 1:
        #print('Comparing %s and %s'% (char, s[index+1]));
        if ord(char) <= ord(s[index + 1]):
            substr += char;
            print(substr);
        else:
            substr += char;
            if len(final_substr) < len(substr):
                final_substr = substr;
            substr = '';

print('Longest substring in alphabetical order is: '+final_substr);

The algorithm has linear (\$O(n)\$) time complexity, which is good; you can't do better. It also has a linear space complexity, which is not so good; only a constant space is really required. Notice that you don't need to build substr (substr consumes memory!). It suffices to keep track of the start and end indices.
The test for index < len(s) - 1 is un-pythonic. Don't ask permission, ask forgiveness.
The intention to

  minimize the number of loops

is dubious. Does it improve run time? Most likely, no (if you doubt, measure). Does it improve readability? Most likely, no. Consider the pseudocode

  while start_index < string_length:
      length = scan_ordered_substring(string, start_index)
      do_business_logic
      start_index += length

I don't think that

    print(substr);

was intended.


Updating entries in a JSON file I have the following Data.json file and I would like to update some of the  values.

{
"A0_Water":"-306.3",
"A1_Water":"0.0",
"A2_Water":"0.0",
"A3_Water":"0.0",
"Barometer":"100.8",
"Bar_Offset":"0",
"Temp":"29.95",
"ip":"192.168.2.47",
"serial":"02:42:52:bf:82:27",
"A0_Sensor":"PS30A",
"A1_Sensor":"None",
"A2_Sensor":"None",
"A3_Sensor":"None",
"A0_Offset":"0",
"A1_Offset":"0",
"A2_Offset":"0",
"A3_Offset":"0"
}

I am new to coding so any help will be much appriciated.
This is the code that I have working: The var data object that I created contains the entries that I want to update in the Data.json file but I was not sure how to use it. The remainder of the code is what I was able to get working but I am sure there is a better way to update the entries in the Data.json file

var data = {
'A0_Water': c_inh2o_A0,
'A1_Water': c_inh2o_A1,
'A2_Water': c_inh2o_A2,
'A3_Water': c_inh2o_A3,
'Barometer': b_mbar_corrected,
'Temp': b_temp
};

var fileName = '/home/admin/reactwatertracker/src/var/Data.json';
var file4 = require(fileName);
var file5 = file4;
var file6 = file4;
var file7 = file4;
var file8 = file4;
var file9 = file4;

file4['A0_Water'] = c_inh2o_A0;
file5['A1_Water'] = c_inh2o_A1;
file6['A2_Water'] = c_inh2o_A2;
file7['A3_Water'] = c_inh2o_A3;
file8['Temp'] =   b_temp;
file9['Barometer'] = b_mbar_corrected;

console.log('Writing to' + fileName);
fs.writeFile(fileName, JSON.stringify(file4,file5,file6,file7,file8,file9, null, 2),  function (err) {
 if (err) return console.log(err);
 console.log (JSON.stringify(file4));
});

const fs = require('fs');
// Read data from JSON file and parse it as a JSON object
const dataFromFile = JSON.parse(fs.readFileSync('./Data.json', 'utf8'));

const data = {
  'A0_Water': 'c_inh2o_A0',
  'A1_Water': 'c_inh2o_A1',
  'A2_Water': 'c_inh2o_A2',
  'A3_Water': 'c_inh2o_A3',
  'Barometer': 'b_mbar_corrected',
  'Temp': 'b_temp'
};

// Now for every 'property' in your 'data' object here,
// you need to update the 'dataFromFile' object

for(let property in data) {
  if(data.hasOwnProperty(property)) {
    dataFromFile[property] = data[property];
  }
}

// Write the updated data in the JSON file
fs.writeFileSync('./Data.json', JSON.stringify(dataFromFile));

NOTE: The above code will add a new value in the JSON file if a corresponding key is not found in your data object. You may want to add a check as:

for(let property in data) {
  if(data.hasOwnProperty(property)) {
    if(dataFromFile[property]) {
      dataFromFile[property] = data[property];
    }
  }
}

Now, the update will be preformed only when a corresponding key has been found.


Supplying parameterless callback to function expecting void * param I have to register different callback functions to a scheduler. The callback signature defines a void * parameter. Some callbacks don't use a parameter. This works, but is it clean?
I expected at least an incompatible pointer type warning for the missing cast on the parameterless call which I actually get when using a function to register the callback but the compiler doesn't complain about this example.
#include <stdio.h>

typedef void (* cb)(void *);

void noparams(void) {
    printf("noparams\n");
}

void params(void * param) {
    char * s = param;
    printf(s);
}

void call(cb cbk, void * ctx) {
    cbk(ctx);
}

int main(void) {
    void * context = 0;
    call(noparams, context); // warning expected

    char str[] = "params\n";
    call(params, str);

    return 0;
}

ideone

When I compile your code with gcc (9.1.1 ) and use the command line option -Wall, I get a warning:
cb.c:20:10: warning: passing argument 1 of ‘call’ from incompatible pointer type [-Wincompatible-pointer-types]
   20 |     call(noparams, context); // warning expected
      |          ^~~~~~~~
      |          |
      |          void (*)(void)

So you might want to up the warning level on the compilation. You could suppress this warning with a cast -- it is ok to cast function pointers.
However the real problem is that it is, I believe, undefined behaviour to call a function (either directly or through a function pointer) with a different number of arguments from those given in its definition. (You might want to check this by asking a stack overflow question with tags C and language lawyer).
If it is indeed UB then you have to avoid it. It might appear to work with a particular compiler, but fail arbitrarily with a different compiler, or even with the same compiler on a different platform.
What you have to do, I think, is to provide a callback with the demanded arguments. You could do this, for example, by adding
void noparams_wrap(void* p) {
    noparams();
}

and passing noparams_wrap to call() rather than noparams() itself.


More efficient solution for Project Euler #2 (sum of Fibonacci numbers under 4 million) I would like to get some feedback on my code. I am starting to program after doing a few online Python courses.

Would you be able to help me by following my track of thinking and then pinpointing where I could be more efficient? (I have seen other answers but they seem to be more complicated than they need to be, albeit shorter; but perhaps that is the point).

Question:

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

fibValue = 0
valuesList = []

a = 0
b = 1

#create list

while fibValue <= 4000000:
    fibValue = a + b
    if fibValue % 2 == 0:
        valuesList.append(fibValue)
    a = b
    b = fibValue

print (valuesList) #just so that I can see what my list looks like after fully compiled

print() #added for command line neatness

print() #added for command line neatness

newTot = 0

for i in valuesList:
    newTot += i
print (newTot)

A hint that I always offer people with this specific question. Take a look at the first few numbers of the sequence - I have set the even ones in bold:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...

Can you see a pattern in the spacing? Can you explain (ideally, prove) it?

Given that, can you think of a way to generate even Fibonacci numbers directly, instead of filtering through for them? (Hint: start with (1,2), and try to generate (5,8) in one step, then (21, 34) etc. Do some algebra and figure out how to apply multiple iterations of the generation rule at once.)

Anyway, in terms of doing the actual calculation with the numbers, there are more elegant approaches. Instead of asking Python to build a list directly, we can write a generator:

def even_fibonacci_up_to(n):
    a, b = 1, 2
    while b <= n:
        yield b # since 2 qualifies, after all.
        # Now calculate the next value.
        # math from the first step goes here when you figure it out!

Notice the use of the yield keyword. This lets us treat our expression even_fibonacci_up_to(4000000) as a special sort of sequence whose elements are generated on-demand. Unlike with ordinary functions which can only return once. :) (Using return inside a generator terminates the whole process of yielding values when it is reached.)

And instead of looping through this sequence to add up the numbers, we can use the built-in sum function:

sum(even_fibonacci_up_to(4000000))


Displaying JSON data from a server in a UICollectionView This code pulls JSON from a server and delivers some data like imageURL, titleString and videoURL. Then it places them in a UICollectionView and displays them.

import UIKit
import Alamofire

class vcWatch: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var myCollectionView: UICollectionView!

var images:[String] = []
var videos:[String] = []
var lableTitles:[String] = []

let link = "http://alifetouched.com/lib/videos.json.php"

override func viewDidLoad() {
    super.viewDidLoad()

    myActivityIndicator.isHidden = false
    myActivityIndicator.startAnimating()
    loadImages()
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell:cvCell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as! cvCell

    // Videos
    let requestURL = URL(string:self.videos[indexPath.row])
    let request = URLRequest(url: requestURL!)

    // Images
    let imageString = self.images[indexPath.row]
    let imageUrl = NSURL(string: imageString)
    let imageData = NSData(contentsOf: imageUrl! as URL)

    cell.videoCell.loadRequest(request)
    cell.labelCell.text = self.lableTitles[indexPath.row]

    if(imageData != nil){
        cell.imageCell.image = UIImage(data: imageData! as Data)
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath){
    print("User Tapped: \(indexPath.row)")
}

func loadImages() {

    Alamofire.request(link)
        .validate()
        .responseJSON { (response) in

            guard response.result.isSuccess else {
                print("Error with response: \(response.result.error)")
                return
            }

            guard let dict = response.result.value as? Dictionary <String,AnyObject> else {
                print("Error with dictionary: \(response.result.error)")
                return
            }

            guard let dictData = dict["VideoJSON"] as? [Dictionary <String,AnyObject>] else {
                print("Error with dictionary data: \(response.result.error)")
                return
            }

            for data in dictData {
                self.videos.append(data["media_url"] as! String)
                self.images.append(data["icon_url"] as! String)
                self.lableTitles.append(data["title"] as! String)
            }

            self.myCollectionView.reloadData()
            self.myActivityIndicator.stopAnimating()
            self.myActivityIndicator.isHidden = true

            return

    }
}

I will address a few points that are the most important in my opinion.

Be consistent.

You're using URL but right after that you're also using NSURL. You're using NSData but later have to cast it to Data. Etc.

The right way would be, instead, to only use URL and Data, and forget the other types.

let requestURL = URL(string:self.videos[indexPath.row])
let request = URLRequest(url: requestURL!)
let imageUrl = URL(string: imageString)
let imageData = try! Data(contentsOf: imageUrl!)

cell.imageCell.image = UIImage(data: imageData)

Don't force unwrap.

You should not force unwrap your Optionals but use safe unwrapping instead, with if let or guard let.

A classic solution in your case is to have a ready-made placeholder image in your project - that way, if the download of an image fails, you can use the placeholder instead.

if let imageUrl = URL(string: imageString),
    let imageData = try? Data(contentsOf: imageUrl)
{
    cell.imageCell.image = UIImage(data: imageData)
} else {
    cell.imageCell.image = placeholder
}

Download asynchronously

You are downloading your list of images URLs with Alamofire but you're downloading the images themselves with NSData(contentsOf: imageUrl! as URL).

The problem is that this method is synchronous and blocks the main thread. If the network is suddenly slow or stops working, your app will lag or freeze.

Instead, download asynchronously with Alamofire, URLSession, etc.

Since you already know how to use Alamofire, I'm showing it with URLSession as an alternative:

if let imageUrl = URL(string: imageString) {
    URLSession.shared.dataTask(with: URLRequest(url: imageUrl)) { (data, response, error) in
        if let data = data {
            DispatchQueue.main.async {
                cell.imageCell.image = UIImage(data: data)
            }
        } else {
            DispatchQueue.main.async {
                cell.imageCell.image = placeholder
            }
        }
    }.resume()
}

Note that because .dataTask is asynchronous, and because we have to do all UI operations on the main thread, we have to set the image using DispatchQueue.main.async once it's downloaded.

This way, the UI won't freeze if there's network issues.
Style

This one is rather subjective, but in Swift there's a few common style guides you should follow:

Classes should start with an uppercase letter:

class VCWatch

class CVCell

Type declaration should have a space after the colon:

var images: [String] = []
var videos: [String] = []
var lableTitles: [String] = []

Parenthesis are not necessary for a boolean condition:

if imageData != nil {
    cell.imageCell.image = UIImage(data: imageData)
}

You can omit the type declaration when the compiler already knows the type:

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as! cvCell

You can use short syntax for arrays and dictionaries:

[String: AnyObject] // instead of Dictionary<String,AnyObject>


Translating Dijkstra's Algorithm from Python to C++ I'm going through the book Grokking Algorithms which is in Python but wanted to write everything in C++. Up to this point everything's been pretty straightforward translation but the code for Dijkstra's algorithm really exploits nested dictionaries and weak typing which I used as an excuse to try out std::optional. I also am playing around with std::set, std::unordered_map, and using typedef to alias ugly types for the first time.

I've retained the original script-like functionality of the original code and have thrown everything into main, and know that a real implementation would be nicely put into a separate function. I am also aware that a real implementation would use a priority queue for finding the minimum cost edge rather than a linear search and wasn't really interested in Dijkstra's but moreso in the C++.

What to Review

Primarily interested in knowing about my usage of typedef in this way, as well as if there was a better way than using std::optional and std::nullopt to handle translating from Python's None type.

C++17 Code

Translated from Python from Grokking Algorithms book.

#include <algorithm>
#include <iostream>
#include <limits>
#include <optional>
#include <set>
#include <unordered_map>

using namespace std;

typedef unordered_map<string, double> CostGraph;
typedef unordered_map<string, optional<string>> ParentGraph;
typedef unordered_map<string, unordered_map<string, double>> WeightedGraph;

auto find_lowest_cost_node(CostGraph costs, const set<string>& processed) {
  auto lowest_cost = numeric_limits<double>::max();
  optional<string> lowest_cost_node = nullopt;
  for (const auto [node, cost] : costs) {
    if (cost < lowest_cost && find(processed.begin(), processed.end(), node) == processed.end()) {
      lowest_cost = cost;
      lowest_cost_node = node;
    }
  }
  return lowest_cost_node;
}

int main() {
  WeightedGraph graph;
  graph["start"] = {};
  graph["start"]["a"] = 6;
  graph["start"]["b"] = 2;

  graph["a"] = {};
  graph["a"]["fin"] = 1;

  graph["b"] = {};
  graph["b"]["a"] = 3;
  graph["b"]["fin"] = 5;

  graph["fin"] = {};

  CostGraph costs;
  costs["a"] = 6;
  costs["b"] = 2;
  costs["fin"] = numeric_limits<double>::max();

  ParentGraph parents;
  parents["a"] = "start";
  parents["b"] = "start";
  parents["fin"] = {};

  auto processed = set<string>{};

  while (const auto node = find_lowest_cost_node(costs, processed)) {
    const auto cost = costs[node.value()];
    const auto neighbours = graph[node.value()];

    for (const auto [n, c] : neighbours) {
      const auto new_cost = cost + c;
      if (costs[n] > new_cost) {
          costs[n] = new_cost;
          parents[n] = node;
        }
    }
    processed.insert(node.value());
  }

  cout << "Costs\n";
  for (const auto [k, v] : costs) {
    cout << k << ": " << v << "\n";
  }

  cout << "Parents\n";
  for (const auto [k, v] : parents) {
    if (v) {
      cout << k << ": " << v.value() << "\n";
    } else {
      cout << k << ": None\n";
    }
  }
}

Avoid translating Pythonisms

  Dijkstra's algorithm really exploits nested dictionaries and weak typing which I used as an excuse to try out std::optional.

No, Dijkstra's algorithm does not require nested dictionaries nor weak typing. Maybe the Python implementation you are translating used these things, but maybe just because it was convenient in Python.

I strongly advise you to try to write idiomatic C++ code, not idiomatic Python translated to C++. What is convenient in Python might not be the best fit for C++, especially not when it comes to performance. I recommend you try to implement Dijkstra's using a priority queue.

Furthermore, putting everything into main() is bad practice. It's better to organize your code into functions and classes as appropriate, and that's true even in Python.

Use of typedefs

It's always a good idea to give a name to things, including types, that you use in multiple places in your code. However, in this case I think it would be better to create a class WeightedGraph that contains all the information about a graph with weighted edges. Then you can add member functions to this graph to add and remove vertices and edges, and a member function get_shortest_path() that uses Dijkstra's to calculate the shortest path between two given vertices and returns the list of vertices.

Use of std::optional

While it's possible to use std::optional here to represent the parent of a vertex, it might not be necessary. If you represent vertices by their name, then an empty string for the name might be used as the equivalent of None. And a more idiomatic C++ implementation of this algorithm would probably store each vertex's parent vertex using a pointer, in which case the nullptr would be the equivalent of None.


Is there a better way of making an NSString with many argument values? I have a form that I'm turning into a string value for an email, but the string value that I turn it into seems very complicated, plus I believe this way takes up a lot of memory and is somewhat slow as well. Is there any other way to make a NSString with many arguments besides using [NSString stringWithFormat:]?

Here is what I'm doing now:

strMessage = [NSString stringWithFormat:@"%@\n\n%@\n\n%@\n%@\n%@, Il\n%@\nPhone: %@\nEmail: %@", detailsText.text, nameText.text, addrLn1Text.text, addrLn2Text.text, cityAddrText.text, zipAddrText.text, phoneNumberText.text, emailText.text];

You could use NSMutableString. It has appendString method which you could use to create string by appending other strings.
For example:

NSMutableString *mutableString = [NSMutableString stringWithFormat:@"%@", someString];
[mutableString appendString:otherString];
// and so on...

NSMutableString also has the stringByAppendingString method, but appendString method is more memory friendly.

You can also do this:

NSString *exampleString = @"Multiple " @"string " @"example";

NSString can even be built using NSArray:

NSArray *stringArray = [NSArray arrayWithObjects:@"Another", @"string", @"example", nil];
NSLog(@"%@",[pathArray componentsJoinedByString:@"\n"]);
// Log wold look like
// Another
// string
// example


Is it possible to DRY these 2 methods of a tailrec Node Tree? I have a Tree structure composed by Node class.

I have to @tailrec method that are visiting up to the root.

Those 2 methods are completely similar, but 1 of those is manipulated a "stats" variable to check the visit and return the root, the other just return the root node.

Here the code sample:

class Node(parent: Option[Node], var visited: Int)
@tailrec
def asc(): Node = {
  parent match {
    case None => this
    case Some(x) => x.asc()
  }
}

@tailrec
def ascVisited(deltaInc: Inc): Node = {
  visited += deltaInc

  parent match {
    case None => this
    case Some(x) => x.ascVisited(deltaInc)
  }
}

Is there any way to reuse the logic of the parent checking and then call recursively the method? I thought with a higher-order function should be possible, but I am not sure is possible with different input argument in the functions.

Any suggestion?

Is it possible somehow to DRY out these 2 bits :

parent match {
  case None => this
  case Some(x) => x.asc()
 }
// and
parent match {
  case None => this
  case Some(x) => x.ascVisited(deltaInc)
}

I defined a Higher-Order function:

@tailrec
def foldAsc(op: Node => Node): Node = {
  op(this)       // <= still this statemnt when x=>x is useless..
  parent match {
    case None => this
    case Some(x) => x.foldAsc(op)
  }
}

def asc(): Node = foldAsc(x => x)

def ascVisited(deltaInc: Inc): Node = foldAsc { x =>
  visited += deltaInc
  x
}

It is not still optimal but DRYed out a little.


Rounding a number up to the nearest multiple of a power of 2 I'm doing some programming challenges over at CodeEval and came across a pretty straight forward simple one:

  Given numbers x and n, where n is a power of 2, print out the smallest multiple of n which is greater than or equal to x. Do not use division or modulo operator.

So the input looks something like this: 13, 8 first number being x second number being n. My first instinct was to use a while loop and return the result of multiplying the number once the loop hits the correct result, so:

 8 * 0 = 0
 8 * 1 = 8
 8 * 2 = 16; break because it's greater then 13

My question is, is it considered bad form to use float("inf") instead of a set number to multiply up to?

import sys

def multiply(x, y):
    max_multiple_try = 0
    while max_multiple_try != float("inf"):
        res = x * max_multiple_try
        if res != x and res >= y:
            return res
        else:
            max_multiple_try += 1

if __name__ == '__main__':
    with open(sys.argv[1]) as data:
        for line in data.readlines():
            numbers = line.rstrip().split(",")
            print(multiply(int(numbers[1]), int(numbers[0])))

Function interface

First of all, it is good that you used a function to contain the code solving the problem!

However, there are some shortcomings:

It is very confusing that the function parameter representing \$n\$ from the problem description is named x, and the one representing \$x\$ is named y.
The function is badly named, as it doesn't multiply the two arguments. A better name would be smallest_multiple or similar.
The function lacks a docstring which describes what it does. It is therefore hard to check if it is implemented correctly. The first sentence of the problem description would make a good docstring (replacing "print out" with "return").

Bug

The function returns the wrong result if both arguments are the same, for example:

>>> multiply(8, 8)
16

But the smallest multiple of 8 which is greater than or equal to 8 should be 8, not 16.

(Maybe you thought that 8 is not considered a multiple of 8?)

The bug is fixed by removing the res != x condition.

Loop exit condition

Let's ignore everything that doesn't affect the max_multiple_try variable:

max_multiple_try = 0
while max_multiple_try != float("inf"):
    …
    if …:
        …
    else:
        max_multiple_try += 1

We can see that it is always an integer (which has unlimited size in Python). Therefore it can never be equal to the special float('inf') value, and the loop could as well have been written using while True: ….

However, as max_multiple_try simply counts the loop iterations, this pattern would be better written as a for loop using itertools.count (and using a simpler and more descriptive name):

from itertools import count
…
for factor in count():  # factor = 0, 1, 2, …
    res = x * factor
    if res >= y:
        return res

Top-level code

Congratulations on using if __name__ == '__main__' and using with to open a file!

Here are some improvements:

Iterate directly over data instead of using readlines.
Use tuple assignment:

x, n = line.rstrip().split(",")
print(multiply(int(n), int(x)))

Alternative algorithm

The problem states that the value of \$n\$ is constrained to powers of two. While your solution actually solves the more general problem for any value of \$n\$, this description probably aims for a different algorithm which makes use of the constraint.

Hint: What does the binary representation of powers of two look like? How could you solve the problem if \$n\$ were constrained to powers of ten?


Extra parenthesis in if-clause vs. readability For a while now, our team has been doing peer code reviews of all submissions. As we've learned, everyone has different styles and going forward, all of us see a need to converge at some kind of tribal/team style so that the code looks consistent and we don't spend time in code reviews arguing one style vs. another.

For most part we've been able to come up with compromises but few, such as this one, are turning out to be sticky:

if ((bIsPaused) || (runState != LnrState_Running))
{
    ....
}

vs.

if (bIsPaused || runState != LnrState_Running)
{
    ....
}

One one side, the argument is less characters -> less information to process -> more readable code.

On the other side, the argument is that extra parenthesis help to read the code.

I'm curious if this is a purely personal thing and the entire community split 50/50 on this (in which case, I'm probably going to be bashed for asking this question), or if you guys think one way is actually more preferred than the other.

UPDATE: removed spaces in the example code so the answers/comments just focus on existence/absence of extra parenthesis pairs.

Compare this:

if ( ( bIsPaused ) || ( runState != LnrState_Running ) )

And this:

if ( [ bIsPaused ] || [ runState != LnrState_Running ] )

You'll find, I think, that the second is much easier to read. This is because I'm using multiple types of braces (illegal, but bear me with here). As humans we can identify the different symbols very quickly, but we can't really line up matching symbols all that quickly.

This technique:

if ( ( bIsPaused ) || ( runState != LnrState_Running ) )

Depends on pairing up symbols, something we aren't actually all that good at.

However, this technique:

if ( bIsPaused || runState != LnrState_Running )

Depends on our ability to distinguish symbols, which is really good, and not on pairing symbols. It does also depend on our ability to apply precedence rules. My experience has been that after years of practice coding that's second nature.

Also, consider math. Mathematics has been around a lot longer then CS and they've adopted precedence rules and get rid of the parenthesis whenever they can.

For those reason, I prefer to eliminate as many parenthesis as possible.


Deleting a linked list node This is a classic linked list problem.

Deleting a node from linked list given the data to be deleted.
Inserting a node in a sorted linked list.

I saw various versions of this and here is my version. Could you check and let me know if this code is efficient?

void deletenode(struct node *&first, int data)
{
    struct node * current = first;// first will have the node after deletion

    struct node * prev = (node *)malloc(sizeof(node));
    while(current!=NULL)
    {
        if(current->data!=data)
        {
            prev=current;
            current = current->next;
        }
        else
        {
            prev->next = current->next;
            delete current;
            break;
        }
    }
}

void insertinsortedlist(struct node *& first, int data)
{
    struct node * current = first;// first will have the node after insertion
    struct node * newnode = (node *)malloc(sizeof(node));
    newnode->data = data;
    struct node * temp = (node *)malloc(sizeof(node));
    while(current)
    {
        if((current->data < data) && (current->next->data > data))
        {
            temp = current->next;
            current->next = newnode;
            newnode->next = temp;
            break;
        }
        current = current->next;
    }
}

The efficiency of your algorithm is fine, however there are a couple of other things you should take care of:

First of all do not free memory, which was allocated with malloc, using delete. delete is for freeing memory which was allocated with new. To free malloced memory use free. Using delete on malloced memory is wrong and leads to undefined behavior.

Also there is almost never a good reason to use malloc in C++ code. If in doubt use new and delete.

Another serious bug in your code is that you allocate memory for prev in deletenode, but never free it.

I also don't see why you pass in first as a reference to a pointer. Since you never change first, I see no reason not to pass it in as a plain pointer (or a plain reference which you then take the address of to assign to current).

Another thing is that you don't need to add the struct keyword when declaring variables or parameters containing structs in C++ - that's a C thing. You should remove it as it only adds noise.


Dispatching SOAP function calls I'm receiving a certain string value over the network and I need to call a function based on that value.

So this is more or less what I have at the moment:

String methodName = soapObj.getMethodName();

switch(methodName) {
    case "getTemperature":
        getDeviceTemp();
        break;
    case "getBrightness":
        getScreenBrightness();
        break;
    ...
}

And.. there are about 60 to 70 methods supported like that.

What's the most elegant way of handling above situation without using reflection? (The app is moderately constrained performance-wise).

I would suggest to:

Define an interface with a method that will be called inside every case, e.g.

public interface ServiceMethod {
    public void execute();
}

Create a map that will contain contain instances of ServiceMethod findable by the a String key, e.g.:

Map<String, ServiceMethod> serviceMethodMap = new HashMap<>();

Fill up the serviceMethodMap map with ServiceMethod instances (this is to avoid the switch), e.g.:

serviceMethodMap.put("getTemperature", new ServiceMethod() {
    public void execute() {
        getDeviceTemp();
    });
serviceMethodMap.put("getBrightness", new ServiceMethod() {
    public void execute() {
        getBrightness();
    });

Finally replace the switch with:

final ServiceMethod serviceMethod = serviceMethodMap.get(methodName);
if(serviceMethod != null) {
    serviceMethod.execute();
}

Update 2/18/2015, added Java 8 support

Define an interface with a method that will be called inside every case, e.g.

@FunctionalInterface
public interface ServiceMethod {
    public void execute();
}

Create a map that will contain contain instances of ServiceMethod findable by the a String key, e.g.:

Map<String, ServiceMethod> serviceMethodMap = new HashMap<>();

Fill up the serviceMethodMap map with ServiceMethod instances (this is to avoid the switch), e.g.:

serviceMethodMap.put("getTemperature", () -> getDeviceTemp());
serviceMethodMap.put("getBrightness", () -> getBrightness());

Finally replace the switch with:

final ServiceMethod serviceMethod = serviceMethodMap.get(methodName);
if(serviceMethod != null) {
    serviceMethod.execute();
}


Using a base class but defining a property I have designed a Python TreeNodeBase class, so all tree nodes I implement can inherit from this. However, due to the laziness inherent in a lot of trees, I would like some fields to be properties (using the @property decorator) instead.

But doing so, the base class will raise AttributeError whenever it tries to set a field, when I call super().__init__(). The way I'm resolving this now is to ignore the AttributeError. Is this a good idea, and is there a standard approach to this problem?

from contextlib import suppress

class TreeNodeBase:
    def __init__(self, value, edge_value=None, children=None, parent=None, tree=None):
        with suppress(AttributeError):
            self.value = value
        with suppress(AttributeError):
            self.edge_value = edge_value
        with suppress(AttributeError):
            self.children = children
        with suppress(AttributeError):
            self.parent = parent
        self.tree = tree

    def get_child(self, edge_value):
        raise NotImplementedError

You solution does look a bit fragile, but I can't help that without seeing more of the hierarchy. The way I'd approach this is to add value=None to your argument function header, and then do this for each attribute:

if value is not None:
    self.value = value

That way the inheriting classes can signal that they don't want the attribute initialised by just leaving the attribute out of the __init__ args, or passing None (this won't work if you actually want None as a value. You'd have to find another placeholder). That way, the system will be a bit more flexible, and there will not be any bad consequences caused by trying to initialise an attribute which is not meant to be initialised.


Simple Bubble Sort swap counter C++ This is the solution for a simple challenge from Hackerrank.I am just trying to solve Sorting: Bubble Sort Problem on HackerRank.

We are asked to count the number of swaps performed during a bubble sort and to print the first and last item of the ordered vector.

Sample input

3
3 2 1

First line is the number of elements in the vector, the second line is the vector

Expected output

Array is sorted in 3 swaps.
First Element: 1
Last Element: 3

Code

I've implemented my solution in C++ and would love to hear what your feedback and what could I have done cleaner

#include <iostream>
#include <vector>
#include <algorithm>

using big_int = long long;

struct answer {
    std::size_t count;
    big_int first_element;
    big_int last_element;
};

template<class T>
answer bubble_sort(std::vector<T> &v) {
    std::size_t swap_count = 0;
    for (int i = 0; i < v.size(); i++) {
        for (int j = 0; j < v.size() - 1; j++) {
            if (v[j] > v[j + 1]) {
                std::swap(v[j], v[j + 1]);
                swap_count++;
            }
        }
    }
    return answer{swap_count, v[0], v[v.size()-1]};
}

int main(int argc, char** argv) {
    int n;
    std::cin >> n;
    std::vector<big_int> v(n);
    for (int i=0; i<n; i++) {
        std::cin >> v[i];
    }

    auto answer = bubble_sort(v);
    std::cout << "Array is sorted in " << answer.count         << " swaps.\n"
              << "First Element: "     << answer.first_element << "\n"
              << "Last Element: "      << answer.last_element;

}

Your answer should also be a template struct. It contains first and last element of type big_int but in the bubble _sort function it is constructed with template argument type T.

template<class T>
struct answer {
    std::size_t count;
    T first_element;
    T last_element;
};

But actually maybe the structure Is redundant because first And last element can Always easily be accessed inside the sorted container. Or it could at least contain just references to those elements instead of their copies in case the template argument T is something more complex then long long.

auto count = bubble_sort(v);
auto & first = v[0];
auto & last = v[v.size - 1];

Further instead of accepting vector<T>, you could accept two iterators of template argument type as Is common with many standard functions and allows to work not only for any type of container but also for just a range within a container.

template<class Iterator>
std::size_t bubble_sort(Iterator from, Iterator to);

// ...

auto count = bubble_sort(v.begin(), v.end());


Number of interesting numbers between two given numbers Please have a look into this problem:

  Little Dipu is a small kid and like all the other kids, he likes to
  play, but he plays with numbers (he is extraordinary you know).
  Nowadays Dipu has some extra interest in odd numbers. So, he says that
  a number N is interesting if it has odd number of divisors. Now Dipu
  turns to you and asks you to tell him how many interesting numbers are
  there between two given numbers, L and R (both inclusive).

  Input:

  First line of input contains the number of test cases T. Each of the
  next T lines contains two space separated integers L and R.

  Output:

  For each test case, output an integer, denoting the count of
  interesting numbers between L and R (both inclusive).

  Constraints:

  \$1 \le T \le 100000\$
  \$1 \le L \le R \le 1018\$

  Sample input:

2
1 3
6 10

  Sample output:

1
1

Below is a solution that I have come up with:

#include<stdio.h>
int main()
{

  long long int max,testcase,count,l,r;
  scanf("%lld",&testcase);

  while(testcase-->0)
  {
    max=0;
    scanf("%lld %lld",&l,&r);

    for(int i=l;i<=r;i++)
    {
      count=0;
      for(int j=1;j<=i;j++)
      {
        if(i%j==0)
        {
        count++;
        }
      }

      if(count%2!=0)
      {

          max=max+1;

      }
    }
    printf("%lld\n",max);

  }
}

The problem is the input constraint which is very large indeed, so my program will give the right outputs for some test cases but for larger inputs it will exceed the time allocated. Please help me to come up with another logic if possible which will make sure that the time allocated is not exceeded.

My program produces the right output but for larger inputs it takes more time than it should.

In that kind of problems, there is a solution a bit more interesting than a straight forward implementation of the logic described.

In your case, you could write a programme to generate the first numbers with the property you are looking for. You'll probably see a pattern that you could reuse (square numbers).

Update as this answer seems to be ignored so far.

Style

It's a good habit to move variable declaration as close as possible to where they are used.

Also, your code probably deserves a bit more spacing (this is how you avoid questions like this one) while a few things can be written in a slightly more concise way.

At this stage, my code looks like :

#include<stdio.h>

int main()
{
    long long int testcase;
    scanf("%lld",&testcase);

    while (testcase--)
    {
        long long int max = 0;
        long long int l, r;
        scanf("%lld %lld",&l,&r);

        for (int i = l ; i <= r; i++)
        {
            long long int count = 0;
            for (int j = 1; j <= i; j++)
            {
                if (i%j == 0)
                {
                    count++;
                }
            }

            if (count % 2)
            {
                max++;
            }
        }
        printf("%lld\n",max);
    }
}

Naming

max is a pretty poor name as it does not convey the right meaning. nb is probably better.

Types

Assuming 1≤L≤R≤10^18 (and not 1018), you will need a long type for i. However you don't need it for testcase.

Code organisation and tests

At the moment, all your code is in the main which makes things hard to test (and thus, to optimise). Let's decompose the code in small functions we'll be able to test and optimise.

At this stage, the code looks like :

#include<stdio.h>
#include<assert.h>

long long int nb_divisors(long long int i)
{
    long long int count = 0;
    for (int j = 1; j <= i; j++)
        if (i%j == 0)
            count++;
    return count;
}

int is_interesting(long long int i)
{
    return nb_divisors(i) % 2;
}

long long int nb_interesting(long long int l, long long int r)
{
    long long int nb = 0;
    for (long long int i = l ; i <= r; i++)
        if (is_interesting(i))
            nb++;
    return nb;
}

int main()
{
    if (0)
    {
        // stdio tests
        long long int testcase;
        scanf("%lld",&testcase);

        while (testcase--)
        {
            long long int l, r;
            scanf("%lld %lld",&l,&r);
            printf("%lld\n", nb_interesting(l, r));
        }
    }
    else
    {
        // automatic tests
        assert(nb_interesting(1, 3) == 1);
        assert(nb_interesting(6, 10) == 1);
    }
}

Algorithm

Here starts the interesting part. Your current algorithm considers all numbers from l to r and when checking if i is interesting or not, iterates all the way from 0 to i. For huge values of r, you'll have many calls to is_interesting and each of these calls will be slow.

A faster nb_divisors (from 0(n) to 0(sqrt(n)))

Let's try to see if we can make nb_divisors faster.

While trying to find divisors of i, you iterate from 1 to i. When you find a divisor d, you can consider d2 = n/d as another divisor. Then you have 3 situations :
 - either d < d2
 - or d2 < d
 - or d == d2.
You can limit yourself to divisors smaller than sqrt(n) and count them twice, then check if we have divisors alone.

my_int nb_divisors2(my_int i)
{
    my_int count = 0;
    my_int j;
    for (j = 1; j*j < i; j++)
        if (i%j == 0)
            count+=2;
    if (j*j == i)
        count++;
    return count;
}

Testing with :

    for (my_int i = 0; i < 1000; i++)
        assert(nb_divisors(i) == nb_divisors2(i));

This seems promising.

nb_divisors went from 0(n) to 0(sqrt(n)). This is particularly brilliant for big values of n.

A faster is_interesting (from 0(sqrt(n)) to 0(1))

Although making nb_divisors faster already makes is_interesting faster, we can make it even faster by re-using the insight we used : most divisors will be counted twice and a divisor will be counted once if and only if the number is a perfect square.

Reusing previous code, we can simply write :

int is_interesting2(my_int i)
{
    my_int j;
    for (j = 1; j*j < i; j++);
    return (j*j == i);
}

but it is still O(sqrt(n)). Using sqrt from math.h, you can write a 0(1) solution (solution taking a constant time):

int is_interesting2(my_int i)
{
    my_int root = sqrt(i);
    return (root && root*root == i);
}

A faster nb_interesting (from super-slow to O(1))

Altough making is_interesting faster already makes nb_interesting much faster, we can re-use what we've found to make it even faster.

First idea is just to count the number of perfect square between l and r. This is easy to write :

my_int nb_interesting2(my_int l, my_int r)
{
    my_int j;
    my_int nb = 0;
    for (j = 1; j*j < l; j++);
    for (     ; j*j <= r; j++)
            nb++;
    return nb;
}

(As usually, it comes along with unit tests to ensure we didn't break anything too badly).

This solution is O(sqrt(r)) as we go through all numbers up to sqrt(r).

We can go faster : let's assume we can compute the number of interesting up to a given number included nb_interesting_from_0(int i), then, we have nb_interesting_between(l, r) = nb_interesting_from_0(r) - nb_interesting_from_0(l - 1).

This fact only becomes interesting when we have a way to compute : nb_interesting_from_0(int i) and we have one, it is simply sqrt(i).

my_int nb_interesting2(my_int l, my_int r)
{
    return sqrt(r) - (my_int)sqrt(l-1);
}

This is 0(1) and pretty simple. Funny thing is that if you were to give me a simple calculator, I'd be able to provide you the number of interesting numbers between two limits very easily.


Modifying the affine transform origin in graphics2D As a project I have written a graphics library for educational use to allow kids at my high school to make Java games without directly dealing with to the Java graphics API. I'm in the final stages, tweaking mainly for performance and readability, and I would like some input on how I handle transformations.

The idea of the origin mode is to improve usabilty, making the drawn objects transform (and be drawn) about the most logical point, that being the specified origin point.

My main concern is that every time the origin modification runs, it creates a new AffineTransformation object, which means it quickly eats an unnecessary amount of memory, as it runs every time an object is drawn. Other than that, if you see any issues, or have any stylistic suggestions, they would be appreciated.

The relevant code to the transformation modifications, and the drawing pipeline is as follows. For sanity's sake I have omitted the set-up code and any setters and getters.

private Rectangle2D bounds = new Rectangle2D.Double();
private AffineTransform postTransform = new AffineTransform();

private boolean correct; // these are all user-set in provided setters
private int origin;
protected int plane; // protected because mouse detection needs access
private AffineTransform transform;

private void applyOrigin(Shape shape) {
    applyOrigin(shape.getBounds2D());
}

private void applyOrigin(RectangularShape shape) {
    bounds.setRect(shape.getX(), shape.getY(), shape.getWidth(), shape.getHeight());
    applyOrigin();
}

private void applyOrigin() {
    double x = -bounds.getX();
    double y = -bounds.getY();
    double p = (plane == DCanvas.PLANE_DEFAULT)? bounds.getY(): getHeight()-bounds.getY(); // getHeight = get height of drawing surface

    switch (origin) {
    case ORIGIN_LEFT:
    case ORIGIN_CENTER:
    case ORIGIN_RIGHT:
        y -= bounds.getHeight()/2;
        break;
    case ORIGIN_BOTTOM_LEFT:
    case ORIGIN_BOTTOM:
    case ORIGIN_BOTTOM_RIGHT:
        y -= bounds.getHeight();
        break;
    }

    switch (origin) {
    case ORIGIN_TOP:
    case ORIGIN_CENTER:
    case ORIGIN_BOTTOM:
        x -= bounds.getWidth()/2;
        break;
    case ORIGIN_TOP_RIGHT:
    case ORIGIN_RIGHT:
    case ORIGIN_BOTTOM_RIGHT:
        x -= bounds.getWidth();
        break;
    }

    if (plane == DCanvas.PLANE_CARTESIAN) switch (origin) {
    case ORIGIN_TOP_LEFT:
    case ORIGIN_TOP:
    case ORIGIN_TOP_RIGHT:
        y -= bounds.getHeight();
        break;
    case ORIGIN_BOTTOM_LEFT:
    case ORIGIN_BOTTOM:
    case ORIGIN_BOTTOM_RIGHT:
        y += bounds.getHeight();
        break;
    }

    if (correct) {
        x += 0.5;
        y += 0.5;
        if (plane == DCanvas.PLANE_CARTESIAN) y -= 1;
    }

    postTransform.setToTranslation(x, y);
    postTransform.preConcatenate(transform);
    postTransform.preConcatenate(AffineTransform.getTranslateInstance(bounds.getX(), p)); // this is the line I am most concerened with
    graphics.setTransform(postTransform); // graphics object to draw on surface
}

public synchronized void draw(Shape shape) {
    applyOrigin(shape);
    graphics.draw(shape); // graphics object to draw on surface
}

private int origin;
...
switch (origin) {
case ORIGIN_LEFT:
case ORIGIN_CENTER:
case ORIGIN_RIGHT:
    y -= bounds.getHeight()/2;
    break;
case ORIGIN_BOTTOM_LEFT:
case ORIGIN_BOTTOM:
case ORIGIN_BOTTOM_RIGHT:
    y -= bounds.getHeight();
    break;
}

You should turn origin into an enum for compile time type safety.

double x = -bounds.getX();
double y = -bounds.getY();

switch (origin) {
case ORIGIN_LEFT:
case ORIGIN_CENTER:
case ORIGIN_RIGHT:
    y -= bounds.getHeight()/2;
    break;
case ORIGIN_BOTTOM_LEFT:
case ORIGIN_BOTTOM:
case ORIGIN_BOTTOM_RIGHT:
    y -= bounds.getHeight();
    break;
}

switch (origin) {
case ORIGIN_TOP:
case ORIGIN_CENTER:
case ORIGIN_BOTTOM:
    x -= bounds.getWidth()/2;
    break;
case ORIGIN_TOP_RIGHT:
case ORIGIN_RIGHT:
case ORIGIN_BOTTOM_RIGHT:
    x -= bounds.getWidth();
    break;
}

This entire section of code looks like you could get rid of it if you made proper use of enums.

You could store an offset multiplier in them; Origin.LEFT would have a -0.5 multiplier to height and a 0 multiplier to width, whereas Origin.BOTTOM_RIGHT would have -1 and -1 respectively.

Then you could just write a function applyOffset, which would work like this:

public Point getOriginPoint(Rectangle2D shape){
    double x = (offsetMultiplierX * shape.getWidth()) - shape.getX();
    double y = (offsetMultiplierY * shape.getHeight()) - shape.getY();
    return new Point(x, y);
}

Although maybe it'd be better to just calculate the offset; in that case you could invert y to get the cartesian view.


Stanford developing calculator iOS app assignment I'm currently learning Swift by following the Stanford developing iOS app 2015 lecture series. I have completed assignment 1 but am wondering if there is any improvement can be made to my code.

Also, I have not been able to complete extra credit no. 4, so I would appreciate if someone could offer me a hint.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var display: UILabel!

    @IBOutlet weak var history: UILabel!

    var userIsInTheMiddleOfTyping = false

    @IBAction func appendDigit(sender: UIButton) {
        let digit = sender.currentTitle!

        if digit == "." && display.text!.rangeOfString(".") != nil {
            return
        }

        if userIsInTheMiddleOfTyping {
            display.text = display.text! + digit
        } else {
            display.text = digit
            userIsInTheMiddleOfTyping = true
        }

    }

    @IBAction func operate(sender: UIButton) {
        if userIsInTheMiddleOfTyping {
            enter()
        }

        let symbol = sender.currentTitle!

        appendToEntryRecord(symbol)
        appendToEntryRecord("  =  ")

        switch symbol {
        case "×": performOperation {$0 * $1}
        case "÷": performOperation { $1 / $0}
        case "+": performOperation {$0 + $1}
        case "−": performOperation {$1 - $0}
        case "√": performOperation {sqrt($0)}
        case "sin": performOperation {sin($0)}
        case "cos": performOperation {cos($0)}
        case "tan": performOperation {tan($0)}
        case "π": performOperation {M_PI}

        default: break
        }

    }

    func performOperation(operation: (Double, Double) -> Double){
        if operandStack.count >= 2 {
            displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
            enter()
        }
    }

    @nonobjc
    func performOperation(operation: (Double) -> Double){
        if operandStack.count >= 1{
            displayValue = operation(operandStack.removeLast())
            enter()
        }
    }

    @nonobjc
    func performOperation(operation: () -> Double){
        displayValue = operation()
        enter()
    }

    var operandStack = [Double]()

    @IBAction func enter() {
        userIsInTheMiddleOfTyping = false
        appendToEntryRecord("\(displayValue)")

        operandStack.append(displayValue)

        print("operandStack = \(operandStack)")
    }

    var displayValue: Double {
        get {
            return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
        }
        set {
            display.text = "\(newValue)"
            userIsInTheMiddleOfTyping = false

        }
    }

    func appendToEntryRecord(value: String){
        history.text = history.text! + "  " + value
    }

    @IBAction func clear() {
        display.text = "0"
        history.text = "0"
        operandStack = [Double]()
    }

    @IBAction func backspace() {
        if display.text!.characters.count > 0 {
            display.text = String(display.text!.characters.dropLast())
        }
    }

    @IBAction func changeSign() {
        if userIsInTheMiddleOfTyping {
            display.text = "-\(display.text!)"
        } else {
            performOperation {-$0}
        }

    }
}

I have never seen the Stanford class or this example before, so I might be mentioning stuff that hasn't been covered yet in the class...

Inappropriate use of IBActions:

Much like viewDidLoad() and family, @IBActions are for telling your class that something has happened, not for telling it to do things. As such, you should name such functions to remind yourself of this fact. Also, that's why you don't call them directly in code.

For example, your appendDigit function doesn't actually append a digit. Sometimes it ignores the value (if the "digit" is "." and the text already has a dot in it,) and sometimes it wipes out the text and replaces it with the digit. This method exists to let your class know that one of the number keys was tapped, so a better name would be something like @IBAction func tappedNumberButton(sender: UIButton)

All your code is in the view controller, there is no Model:

You are writing a calculator app, but there isn't any expressed concept of a Calculator in your code. I would expect to see some sort of calculator class that deals with numbers and manipulating them. Something that exists independent of the view controller and could be used as a component in other apps that need to handle calculation.

Having a separate Calculator class would also make your code amiable to automated tests.

You seem to have two distinct states in your system as evidenced by your userIsInTheMiddleOfTyping variable. It would be interesting if you actually expressed that in two different classes, but that might be overkill for this particular project.

Your indentation seems consistent, but your use of carnage return isn't. Sometimes you use two CRs.


Using recursion to count nodes in a binary tree, test equality of linked lists, and find extrema of a linked list I am working with a some small functions to test recursion. I am fairly new to Python and am wondering if there is a cleaner way to get the job done.

def count(t,p):

    ''' recursive function when passed a binary tree (it doesn’t matter if it is a
    binary search tree) and a predicate as arguments; it returns a count of all the
    values in the tree for which the predicate returns True. '''
    if t == None or t.value == None:
        return 0
    elif p(t.value):
        return 1 + count(t.right, p) + count(t.left, p)
    else:
        return count(t.right, p) + count(t.left, p)

def equal(ll1,ll2):

    ''' recursive function when passed two linked lists; it returns whether or not
    the linked lists contain exactly the same values in the same order. '''
    if ll1 == None and ll2 == None:
        return True
    if (ll1 != None and ll2 == None) or\
        (ll2 != None and ll1 == None):
        return False
    elif ll1.value == ll2.value:
        return equal(ll1.next, ll2.next)
    else:
        return False

def min_max(ll):

    ''' a recursive when passed a linked list; it returns a 2-tuple containing the
    minimum value followed by the maximum value. If the linked list is empty, return
    (None, None) '''
    if ll == None:
        return None, None
    maybe_min, maybe_max  = min_max(ll.next)
    if maybe_min == None or ll.value < maybe_min:
        least = ll.value
    if maybe_min != None and ll.value > maybe_min:
        least = maybe_min
    if maybe_max == None or ll.value >= maybe_max:
        most = ll.value
    if maybe_max != None and ll.value < maybe_max:
        most = maybe_max
    return least, most

It is better to test for x is None rather than x == None.

Avoid using single-letter variable names — they may make sense to you, but not to anyone else.

I don't see any reason why a node should be automatically not counted if its value is None.  Shouldn't it be up to the predicate to decide whether nodes with None as a value are counted or not?

You can eliminate a case by taking advantage of the fact that int(False) is 0 and int(True) is 1.

def count(tree_node, predicate):
    """Counts the tree_node and its descendants whose value satisfies the predicate."""
    if tree_node is None:
        return 0
    else:
        return int(predicate(tree_node.value)) + \
               count(tree_node.left, predicate) + \
               count(tree_node.right, predicate)

Stylistically, it would be better to consistently use either one long if… elif chain or just ifs with early returns.  I also suggest putting the recursive case at the end of the function.

(ll1 != None and ll2 == None) or (ll2 != None and ll1 == None) can be simplified.

def equal(ll1, ll2):
    """Recursively checks whether two linked lists contain the same values
    in the same order."""
    if ll1 is None and ll2 is None:
        return True
    if ll1 is None or ll2 is None:
        return False
    if ll1.value != ll2.value:
        return False
    return equal(ll1.next, ll2.next)

Assuming that the linked list contains no None data values, the logic can be simplified.

def min_max(ll):
    """Returns a 2-tuple of the minimum and maximum values.
    If ll is empty, returns (None, None)."""
    if ll is None:
        return None, None
    if ll.next is None:
        return ll.value, ll.value
    least, greatest = min_max(ll.next)
    return min(ll.value, least), max(ll.value, greatest)


Tic Tac Toe / Noughts and Crosses - First Program This is my first program. Its a two player noughts and crosses game. I would really appreciate any comments on how to improve my code or make it more efficient. Many Thanks.

It is written in Python 3.6.

#Noughts and Crosses Game

#Grid
grid = [0, 1, 2, 3, 4, 5, 6, 7, 8]

#Welcome
print("Welcome to Noughts and Crosses Game")

#Player name inputs
p1_name = input("What is name of Player 1? Player 1 is 'x': ")
p2_name = input("What is name of Player 2? Player 2 is 'o': ")

#Draw Grid
def draw_grid():
    print("-------------")
    print('|', grid[0], '|', grid[1], '|', grid[2], '|')
    print("-------------")
    print('|', grid[3], '|', grid[4], '|', grid[5], '|')
    print("-------------")
    print('|', grid[6], '|', grid[7], '|', grid[8], '|')
    print("-------------")

#Move input for player 1
def p1():
        try:
            p1_input = int(input(p1_name + " select a space on the grid by entering a \
number to place an 'x': "))
        except ValueError:
            print("Error: Please enter a number, not a letter or symbol")
            p1()
        else:
            if p1_input not in range(9):
                print("Error: Please select a number on the grid 0-8 to place an 'x'")
                p1()
            elif grid[p1_input] == "x" or grid[p1_input] == "o":
                print("Error: This spot has been taken.")
                p1()
            else:
                grid[p1_input] = "x"
                draw_grid()

#Move input for player 2
def p2():
        try:
            p2_input = int(input(p2_name + " select a space on the grid by entering a \
number to place an 'o': "))
        except ValueError:
            print("Error: Please enter a number, not a letter or symbol")
            p2()
        else:
            if p2_input not in range(9):
                print("Error: Please select a number on the grid 0-8 to place an 'o'")
                p2()
            elif grid[p2_input] == "x" or grid[p2_input] == "o":
                print("Error: This spot has been taken.")
                p2()
            else:
                grid[p2_input] = "o"
                draw_grid()

#Check for three x in a row
def p1_check():
    if grid[0] == "x" and grid[1] == "x" and grid[2] == "x" or \
        grid[3] == "x" and grid[4] == "x" and grid[5] == "x" or \
        grid[6] == "x" and grid[7] == "x" and grid[8] == "x" or \
        grid[0] == "x" and grid[3] == "x" and grid[6] == "x" or \
        grid[1] == "x" and grid[4] == "x" and grid[7] == "x" or \
        grid[2] == "x" and grid[5] == "x" and grid[8] == "x" or \
        grid[6] == "x" and grid[4] == "x" and grid[2] == "x" or \
        grid[0] == "x" and grid[4] == "x" and grid[8] == "x":
            print(p1_name + " Wins!")
            return "End Game"

#Check for three o in a row
def p2_check():
    if grid[0] == "o" and grid[1] == "o" and grid[2] == "o" or \
         grid[3] == "o" and grid[4] == "o" and grid[5] == "o" or \
         grid[6] == "o" and grid[7] == "o" and grid[8] == "o" or \
         grid[0] == "o" and grid[3] == "o" and grid[6] == "o" or \
         grid[1] == "o" and grid[4] == "o" and grid[7] == "o" or \
         grid[2] == "o" and grid[5] == "o" and grid[8] == "o" or \
         grid[6] == "o" and grid[4] == "o" and grid[2] == "o" or \
         grid[0] == "o" and grid[4] == "o" and grid[8] == "o":
            print(p2_name + " Wins!")
            return "End Game"

#Check for a tie
def tie_check():
    if grid.count("x") + grid.count("o") == len(grid):
        print("Game is a tie")
        return "End Game"

#Play the game
def play():
    draw_grid()
    while True:
        p1()
        if p1_check() == "End Game":
            break
        if tie_check() == "End Game":
            break
        p2()
        if p2_check() == "End Game":
            break
        if tie_check() == "End Game":
            break

play()

Seems pretty nicely done. Most of the following are minor improvements, but if in case you do not get any of the following parts, do let me know. COnsidering the beginner tag, I have written a small appendix at the end. Suggestions for improvements:

The Format method: Instead of using the print() as you have written, it is better to use a format() method in general. For your purposes, it might be overkill, but in case you are incorporating some of the points below (especially 5), it might come in handy for a pretty output.
Alternative for if-elif-else: The entire block from try to the final else can be replaced by regexsearch (or any equivalent string search) to look for correct responses and club the not a number and incorrect number error messages into one. One suggestion for that is below.

Suggestion code:

# initialize with grid = ["0","1","2","3","4","5","6","7","8"]
if (p1_input not in grid) or (p1_input in ['x','o']):
    print('Combined Error Message')
else:
    grid[int(p1_input)]='x'
    draw_grid()

Checking for victory: Instead of listing down all possible victory positions, the bulky code can be avoided. Although I am currently unable to come up with anything simpler than the following code which uses numpy, you can at least contract the current code in a single function that can be called for both p1 and p2, reducing the bulk of that code by half. The benefit of using the numpy variant is, it is size-independent. You can update a for a 4x4 game and it should be directly usable.

Numpy Variant:

def p1_check():
    # a defines a list of all winning positions
    a = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
    # <= is the subset operator for sets. Additionally, the where statement finds the indices for all 'x'
    l = list(numpy.where(numpy.array(grid) == 'x')[0])
    if True in list(map(lambda x: (set(x) <= set(l)),a)):
        print('Victory')
        return "End Game"

Contraction of your code:

def check(player):
   a = ['x','o'][player-1]
   if grid[0] == a and grid[1] == a and grid[2] == a or \
         grid[3] == a and grid[4] == a and grid[5] == a or \
         grid[6] == a and grid[7] == a and grid[8] == a or \
         grid[0] == a and grid[3] == a and grid[6] == a or \
         grid[1] == a and grid[4] == a and grid[7] == a or \
         grid[2] == a and grid[5] == a and grid[8] == a or \
         grid[6] == a and grid[4] == a and grid[2] == a or \
         grid[0] == a and grid[4] == a and grid[8] == a:
            print([p1_name,p2_name][player-1] + " Wins!")
            return "End Game"
#call check(1) and check(2) appropriately

Earlier Ties: In order to account for configurations where a tie is definite, without all the boxes having been filled, you can work out if there is any winning chance considering only all the 'x' and the empty boxes (same for 'o'). To do this, one way is to use the numpy variant above with a slight modification. This matters very little in a 3x3 game but ismore relevant for larger games.

Suggestion code:

# a defines a list of all winning positions
def tie_check():
    a = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
    # using != instead of ==, 'or' combining the lists
    canwin = (True in list(map(lambda x: set(x) <= set(list(numpy.where(numpy.array(grid) != 'x')[0])),a))) or \
          (True in list(map( lambda x: set(x) <= set(list(numpy.where(numpy.array(grid) != 'o')[0])),a)))
    if not canwin:
        print("Game is a tie")
        return "End Game"

Multiple Games and statistics: To just improve the usability of the code, you can allow for specifying at the end whether to play another game or not. Provision for a best of 3/best of 5 can easily be incorporated in the play() function with an additional option of storing and printing the statistics for the game.

APPENDIX

Numpy is basically used for its arrays and array-methods which are very fast and convenient. For our purposes, only two of these are relevant. numpy.where just returns an array of indices corresponding to True. Whenever a numpy array is equated (==) to any value, an array of booleans is returned corresponding to element-wise matching. I urge you to try out with self-made arrays and it is very easy to get hang of, for 1-D case, which is the one used above.

Map is just a way to apply a function element-wise to a list and return a list of values returned for every such application. I assume you are familiar with lambda(a way to make functions on the fly) and set which are very similar to the mathematical entity.


Webapp Substrate script for WordPress on Debian-Nginx The following script creates a webapp substrate for WordPress webapps/websites on Ubunu-Nginx with PHP-FPM and Mysql environments, with Certbot, while all software is uncustomized.

Such substrate includes, based on the 1 or more domains given as an argument (
/opt/nwsm.sh domain1.tld domain2.tld):

/etc/nginx/sites-available/example.com.conf.
etc/nginx/sites-enabled/ symlink.
Appropriate DB user and instance, named example.com.
Suitable wp-config.php file.

I especially hope to learn how I could shorten this code in at least 10 rows, if at all.

Installing the script

Just copy and paste in Bash and it willl be created under /opt/nwsm.sh.

cat <<-"NWSM" > /opt/nwsm.sh
    #!/bin/sh
    for domain; do
        cat <<-WEBAPPCONF > "/etc/nginx/sites-available/${domain}.conf"
            server {
                root /var/www/html/${domain};
                server_name ${domain} www.${domain};
                location ~*  \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ {
                    expires 365d;
                }
                location / {
                    index index.php index.html index.htm fastcgi_index;
                    try_files $uri $uri =404 $uri/ /index.php?$args;
                }
                location ~ \.php$ {
                    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
                    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                    include fastcgi_params;
                }
            }
        WEBAPPCONF
        ln -s /etc/nginx/sites-available/${domain}.conf /etc/nginx/sites-enabled/

        echo "Please enter database user password for user ${domain}: "
        read -s waps
        echo "Please enter database root password"
        mysql -u root -p <<-MYSQL
            create user "${domain}"@"localhost" identified by "${waps}";
            create database ${domain};
            GRANT ALL PRIVILEGES ON ${domain}.* TO ${domain}@localhost;
        MYSQL

        certbot --nginx -d ${domain} -d www.${domain}
    done

    cd /var/www/html/
    wget http://wordpress.org/latest.tar.gz
    tar xzvf latest.tar.gz && rm latest.tar.gz
    mv wordpress ${domain}

    cp /var/www/html/${domain}/wp-config-sample.php /var/www/html/${domain}/wp-config.php
    echo "1/1: Please enter the password of the site's DB user." && read -s dbup
    sed -i "s/database_name_here/${domain}"/g /var/www/html/${domain}/wp-config.php
    sed -i "s/username_here/${domain}"/g /var/www/html/${domain}/wp-config.php
    sed -i "s/password_here/${dbup}"/g /var/www/html/${domain}/wp-config.php

    chown www-data:www-data /var/www/html/* -R
    find /var/www/html/* -type d -exec chmod 755 {} \;
    find /var/www/html/* -type f -exec chmod 644 {} \;
    systemctl restart nginx.service
NWSM
chmod +x /opt/nwsm.sh

Using the script

Call the script with a domain and tld as an argument, say:

/opt/nwsm.sh example.com

The outer heredoc construct isn't really required.
You do not verify that you have command line arguments.
You do not assign your command line arguments to the variable domain.
You use the variable domain when it is uninitialised.

You make a number of assumptions, any one of which could bite you hard.

You assume that the nginx package has been installed and that it has created the paths and other things you require.
You assume that the MySQL packages have been installed.
You assume that the certbot package has been installed.
You assume that the /var/www/html directory exists.
You assume that the www-data user exists.
You assume that this is the first time that the script has been run for domain. It will have unexpected results if domain already exists.

Think about those assumptions and what would happen if they were incorrect and things didn't exist as you expect.

Your variable names are not good - why, for example, is the database user's password assigned to waps and not something like dbpassword?

It's not clear if you are planning on passing more than one domain to the script per invocation. If you only plan one domain per invocation you do not need the for loop.

You assume that all of your commands will complete correctly. You really should check the exit status of those that could reasonably be expected to fail. For example the wget could fail for many reasons. If it does then everything after it should not be run. What happens if certbot fails or mysql or tar or ...

Your chown -R... command assumes that nothing else is installed in /var/www/html or that everything installed there should be owned by www-data, this may not be the case, use /var/www/html/${domain}. Your find commands are the same.

Your find commands will exec chmod for every file found. It is more efficient to use find ... -exec {} + which optimises the size of the command line and reduces the number of execs.

  I especially hope to learn how I could shorten this code in at least 10 rows, if at all.

How sweet, I can see it being considerably larger.


Find Square root of number only with addition or/and subtraction My problem is following: I want to Find Square root of a number (which is the square of integer) only with addition or subtraction (or together). I wrote the algorithm which works, but I am really interested in what will be better solution to solve this problem.

static void FindSquareRoot(int S)
{
    int i = 1;

    for (; i <= S; i++)
    {
        int k = S;
        int j = i;

        while (j>0)
        {
            k = k - i;
            j--;
        }

        if (k == 0)
        {
            Console.WriteLine("Square root of {0} is {1}", S, i);
            break;
        }
        else if (k < 0)
        {
            Console.WriteLine("Not found");
            break;
        }
    }
}

The basic idea of this algorithm is to choose one number(i) and subtract it from S (i) times. if the result will be 0, then it means that this(i) is the number I was looking for..

static void FindSquareRoot(int S)

Why void? The method would be more useful if it returned the value rather than printing it, and throw an exception if the input was invalid rather than printing an error message.

    int i = 1;

    for (; i <= S; i++)

The scope of i is the loop, so why not restrict it to that scope?

        int k = S;
        int j = i;

        while (j>0)
        {
            k = k - i;
            j--;
        }

i and j as loop variables are fairly conventional, but what does k mean? It's not a loop variable. A comment indicating that after the inner loop k = S - i * i would help, and might suggest a name like surplus.

Again, restrict the scope of the loop variable to the loop unless there's good reason not to.

Finally, on scope, by pulling k out of the loop you should be able to figure out a way to update its value without using an inner loop...


Downloading a page in Android I tried to create a class which downloads the HTML source from a link and saves it. I'm a newbie to all this Android stuff, even new to Java, but this is what I have so far.

It seems to work at least, although I cannot see the file since it is hidden.

package com.example.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class PageDownloader {

    String Filename;
    String urlString;
    Context context;

    public PageDownloader( Context ctx) {
        Filename = "tmpPage.html";
        context = ctx;
    }

    public void download( String _url ){
        urlString = _url;
        testClass t = new testClass();
        t.execute();

    }
    public void _download(){
        /*
         * First Download content
         * Then Save File
         *
         */
        String result = null;

        //DOWNLOAD
        try {
            URL url = new URL( urlString );
            URLConnection con = url.openConnection();
            con.connect();
            InputStream in = con.getInputStream();
            byte[] data = new byte[ in.available() ];

            while( in.read(data) != -1 ){
                result += new String(data);
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //SAVE
        saveFile( result );
    }

    private void saveFile( String r )
    {
        try {
            File f = new File( context.getFilesDir(), "myfile" );
            if( !f.exists() )
                f.createNewFile();

            FileOutputStream fos = new FileOutputStream(f);//context.openFileOutput(Filename, context.MODE_PRIVATE);
            fos.write( r.getBytes() );
            fos.close();

            Log.w( "PageDownloader", "got it!" );
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.w("PageDownloader", e.getMessage());
        }

    }

    public class testClass extends AsyncTask<Void, Integer, Void>
    {

        @Override
        protected Void doInBackground(Void... params) {
            _download();
            return null;
        }

    }
}

I call it from my onCreate method in my MainActivity.java :

PageDownloader p = new PageDownloader(this);
String url = "www.google.com/";
p.download( url );

How is this class written? Anything wrong or to improve?

I want to use this code to download several (maybe 5 up to 20) pages when I click on something. After I downloaded the source I want to extract information out of it. Maybe there is a way to make it faster.

Don't leak Context

It's not good to leak Context out of an Activity/Service. Your class needs just the output of context.getFilesDir(), so store just that:

private final File parentDir;

public PageDownloader(Context context) {
    parentDir = context.getFilesDir();
}

Hardcoded strings

It would be better if the filename was a parameter, not a hardcoded string. If you must hardcode, then at least make it a constant:

private static final String FILENAME = "tmpPage.html";

Hide internal methods

It's good to make everything private by default, and change to less strict access only when there is a good reason to do so. For example the _download method will only be called from your inner class, so there's no need to make it public, so change it to private.

Reading from a stream

The way you read from the input stream has many problems:

It's inefficient to build long strings by appending to a String with +=. Use a StringBuilder instead.
Since you initialized String result = null, as you append the input to it your end result will start with the literal string "null". You probably meant to initialize with String result = "".
The available method of InputStream is not very useful in practice, and it can be misleading. I would recommend using a constant instead.
You are not closing the input stream after reading from it, which can lead to a resource leak.
You should not use e.printStackTrace(), but log instead
The comments //DOWNLOAD and //SAVE are completely pointless

Variable and method naming violations

You're not following common naming practices: variable and method names should be camelCase and not start with _. Class names should be CamelCase (starting with capital letter). For example:

download instead of _download
TestClass instead of testClass

Of course, an even bigger issue with your names is that they are not descriptive. For example the variable r, the class TestClass, and many others. You should review ALL your variables/methods/classes and give them more descriptive names so your code reads like a story.

Suggested implementation

private static final String TAG = "PageDownloader";
private static final int BUFSIZE = 1024;

private void download(String urlString) {
    StringBuilder builder = new StringBuilder();
    InputStream in = null;
    try {
        URL url = new URL(urlString);
        URLConnection con = url.openConnection();
        con.connect();
        in = con.getInputStream();
        byte[] data = new byte[BUFSIZE];
        while (in.read(data) != -1) {
            builder.append(new String(data));
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage(), e);
        return;
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }
    saveFile(builder.toString());
}


A countdown numbers game solver Please feel free to review my countdown numbers game solver. Posted here too for people working on the same problem. For clarity the print statement
"Eval..." means the program has used BODMAS on an entire mathematical statement
(e.g: 1*3+10 = 31)

"Running total" means the program recalculates the total after each move (e.g: 1*3+10 = 13 because 1*3 = 3, 3+10 = 13)

import re
def unpack(method):
    string = method
    special = ["*","+","-","/"]
    list_sum = []
    list_special = []
    numbers = (re.findall(r"[\w']+", string))
    for char in string:
        if char in special:
            list_special.append(char)

    for index in range (len(numbers)-1):
        to_eval = numbers[index] + list_special[index] + numbers[index+1]
        list_sum.append(f'{to_eval} = {eval(to_eval)}')
        numbers[index+1] = str(eval(to_eval))

    return list_sum

def evaluate (method,running_sum):
    global clear_status
    if eval(method) == target:
        if method not in list_methods:
            list_methods.append(method)
            print (f'Eval: {method}')
            clear_status = True
        return True
    if running_sum == target:
        if method not in list_methods:
            list_methods.append(method)
            print (f'Running sum: {unpack(method)}')
            clear_status = True
        return True
    clear_status = False
    return False

def new_total (total,item,operation):
    if operation == "+": return total + item
    if operation == "-": return total - item
    if operation == "*": return total * item
    if operation == "/" and item != 0: return total / item
    return ""

def solve (array,total=0,method="",list_method=[]):
    if len(array) == 0:
        return

    for (index,item) in enumerate(array):
        #Set methods and totals to "":
        add_method, sub_method, mul_method, div_method = "", "", "", ""
        add_total, sub_total, mul_total, div_total = 0, 0, 0,0

        #Assign methods and totals to a list:
        methods = [add_method, sub_method, mul_method, div_method]
        totals = [add_total, sub_total, mul_total, div_total]
        str_func = ["+", "-", "*", "/"]

        #Create new array
        remaining = array[:index] + array[index+1:]

        #Sets new totals and new "methods"
        for index_1 in range (len(methods)):
            if method =="":
                if str_func[index_1] != "/" and str_func[index_1] != "*" and str_func[index_1] != "-":
                    methods[index_1] = str(array[index])
                    totals[index_1] = new_total(total, item, str_func[index_1])
            else:
                methods[index_1] = method + str_func[index_1] + str(array[index])
                totals[index_1] = new_total(total, item, str_func[index_1])

        #Evaluates each total and method
        for index_2 in range (len(methods)):
            try:
                if evaluate(methods[index_2], totals[index_2]):
                    if clear_status == True:
                        methods[index_2]=""
                        totals[index_2]=0
                    return
            except Exception as e:
                pass

        #Recursively calculates next move
        for index_3 in range (len(methods)):
            try:
                solve(remaining, total= totals[index_3],method= methods[index_3])
            except Exception as e:
                pass

str_array = input("Please enter the starting numbers, separated by commas: ")
array = array=[int(item.strip()) for item in str_array.split(",")]
target = int(input("Please enter a target value: "))
print (f'Solutions for {array} to reach {target}')
list_methods = []
solve(array)
if list_methods == []:
    print ("Unsolvable countdown problem")
to_close = input("Press any key to exit...")

Docstrings: You should include a docstring at the beginning of every method/class/module you write. This will help any documentation indentify what your code is supposed to do.
solve(): My biggest problem with this method was the beginning. You create eight different variables for your methods and total, then put them into a list. Instead of having these eight one time use variables, just set the default values inside the list. Since you don't work with any of the eight variables after putting them into the list, they are obsolete, so can be removed.
Variable/Parameter/Method Spacing: There shouldn't be spaces between the method name and the opening parentheses.
Parameter Reassignment: In unpack you have a passed parameter method. You then reassign that parameter to a variable string. This is very unnecessary. You have simply have the parameter string, so you're working directly with what is passed, instead of taking the time and trouble to reassign to a variable.
Use of global: It's not recommended to use global variables in python, or any language. This StackOverflow answer provides more insight.
Boolean Comparison: Instead of checking if variable == True, you can simply check the variable itself, like so: if variable:.
Unused Exceptions (as e): If you don't intend to work with an exception that you catch, it is unnecessary to have the extra code as e, since that will be a variable you never use. You can simply remove that code.
Unused Parameters: In solve, you never use the list_method=[] that is passed. You should remove any parameters you don't use, you risk adding complexity and reducing readability.
Constants Naming: Any constants in your code should be UPPERCASE, so make it clear to anyone reading your code, including yourself, that they are constant variables.
in list vs in [...]: You create a list of operators for the sole purpose of checking if an operator is in that list of operators. This is unnecessary. You can simplify your code by creating an anonymous list to check containment. This reduces the amount of variables in your code, increasing readability and reducing complexity.
if name == main guard: Any code that isn't contained in a method or class should be contained in a if __name__ == '__main__' guard. This will prevent any of that code from being executed if you decide to import the file, for other uses.
_ for unused variables: Your last line of code is a variable that allows the user to exit when they want, by pressing any key. You create a variable for this purpose alone. Since you never use this variable, and it's only used to exit the program, you can use a _, to make it clear that that variable is to be, essentially, ignored.

Updated Code

"""
Module Docstring:
Explanation of your code goes here
"""

import re

def unpack(string):
    """ Unpacks the passed `string` """
    list_sum = []
    list_special = []
    numbers = (re.findall(r"[\w']+", string))
    for char in string:
        if char in ["*", "+", "-", "/"]:
            list_special.append(char)

    for index in range(len(numbers) - 1):
        to_eval = numbers[index] + list_special[index] + numbers[index + 1]
        list_sum.append(f'{to_eval} = {eval(to_eval)}')
        numbers[index + 1] = str(eval(to_eval))

    return list_sum

def evaluate(method, running_sum):
    """ Evaluates the passed `method` """
    if eval(method) == TARGET:
        if method not in LIST_METHODS:
            LIST_METHODS.append(method)
            print(f'Eval: {method}')
            clear_status = True
        return True
    if running_sum == TARGET:
        if method not in LIST_METHODS:
            LIST_METHODS.append(method)
            print(f'Running sum: {unpack(method)}')
            clear_status = True
        return True
    clear_status = False
    return False

def new_total(total, item, operation):
    """ Determines the operator and returns the new total """
    if operation == "+":
        return total + item
    if operation == "-":
        return total - item
    if operation == "*":
        return total * item
    if operation == "/" and item != 0:
        return total / item
    return ""

def solve(array, total=0, method=""):
    """ Solves the passed numbers and target """
    if not array:
        return

    for index, item in enumerate(array):

        #Assign methods and totals to a list:
        methods = ["", "", "", ""]
        totals = [0, 0, 0, 0]
        str_func = ["+", "-", "*", "/"]

        #Create new array
        remaining = array[:index] + array[index+1:]

        #Sets new totals and new "methods"
        for index_1 in range(len(methods)):
            if method == "":
                if str_func[index_1] != "/" and str_func[index_1] != "*" and str_func[index_1] != "-":
                    methods[index_1] = str(array[index])
                    totals[index_1] = new_total(total, item, str_func[index_1])
            else:
                methods[index_1] = method + str_func[index_1] + str(array[index])
                totals[index_1] = new_total(total, item, str_func[index_1])

        #Evaluates each total and method
        for index_2, value_2 in enumerate(methods):
            try:
                if evaluate(value_2, totals[index_2]):
                    if clear_status:
                        methods[index_2] = ""
                        totals[index_2] = 0
                    return
            except Exception:
                pass

        #Recursively calculates next move
        for index_3, value_3 in enumerate(methods):
            try:
                solve(remaining, total=totals[index_3], method=value_3)
            except Exception:
                pass

if __name__ == '__main__':
    clear_status = None
    STR_ARRAY = input("Please enter the starting numbers, separated by commas: ")
    ARRAY = ARRAY = [int(item.strip()) for item in STR_ARRAY.split(",")]
    TARGET = int(input("Please enter a target value: "))
    print(f'Solutions for {ARRAY} to reach {TARGET}')
    LIST_METHODS = []
    solve(ARRAY)
    if LIST_METHODS == []:
        print("Unsolvable countdown problem")
    _ = input("Press any key to exit...")


c++ array. Looking for better solution So i got an task from school.
Which ask's me to write a program tad creates an 2d array with 11 rows and 5 columns.
In which the first column starts with 2.0 and increments by 0.1 all the way up to 3.0.
Then in next column it should be devided by 1 so if x is 2.0 then 1 / x and goes trough all 11 rows.
then in next column it has to multiply by 2 so x^2 and repeat in every column up to x^4.
So so far i got it to do what i need , but i know there should be a better way to achieve this. as if there would be a task to go up to x^50 for example i imagine it would be pain to do with my way. as its hardcoded.
So here is my code:
#include<iostream>
#include<iomanip>
#include<array>

using namespace std;

int main()
{
 const int rows = 11;
 const int columns = 5;
 double x = 2.0;

 array<array<double, columns>,rows> A{};
 cout << setprecision(2);
 cout << fixed;
 cout << setw(2) <<"x" << setw(10) << "1/x" << setw(7) << "x^2" << setw(7) << "x^3" << setw(8)<< "x^4\n";
 cout << "------ ------ ------ ------ ------\n";
 A[0][0] = x;
 for(int i = 0; i < A.size(); i++)
 {
     A[i+1][0] = A[i][0] + 0.1;
     A[i][1] = 1 / A[i][0];
     A[i][2] = A[i][0] * A[i][0] * A[i][0];
     A[i][3] = A[i][0] * A[i][0] * A[i][0]* A[i][0];
     A[i][4] = A[i][0] * A[i][0] * A[i][0]* A[i][0] * A[i][0] ;
     for(int j = 0; j < A[0].size(); j++)
     {
         cout << A[i][j] << setw(4)  << " ";
     }
     cout << endl;
 }

 return 0;
 }

and here is how it's supposed to look:

Looking for suggestions or tips. I am strugling here.
And sorry for my english it's not my native.

You're almost there, you just need to use std::pow() to raise a value to an arbitrary power, and add another for-loop to handle the repetetive work of filling in all the remaining columns:
for(int i = 0; i < A.size(); i++)
{
     A[i][0] = 2.0 + 0.1 * i;
     A[i][1] = 1 / A[i][0];

     for(int j = 2; j < A[i].size(); j++)
     {
         A[i][j] = std::pow(A[i][0], j);
     }
     ...
}