texts:
This is a Leetcode problem -

  In a 1 million by 1 million grid, the coordinates of each grid square
  are (x, y) with \$0\$ \$<=\$ x\$,\$ y \$<\$ \$10^6\$.

  We start at the source square and want to reach the target square.
  Each move, we can walk to a 4-directionally adjacent square in the
  grid that isn't in the given list of blocked squares.

  Return True if and only if it is possible to reach the target square
  through a sequence of moves.

  Example 1 -

Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]
Output: False

# Explanation:
# The target square is inaccessible starting from the source square because we can't walk outside the grid.

  Example 2 -

Input: blocked = [], source = [0,0], target = [999999,999999]
Output: True
# Explanation:
# Because there are no blocked cells, it's possible to reach the target square.

  Note -

  0 <= blocked.length <= 200
  blocked[i].length == 2
  0 <= blocked[i][j] < \$10^6\$
  source.length == target.length == 2
  0 <= source[i][j], target[i][j] < \$10^6\$
  source != target

Here is my solution to this challenge -

from collections import deque

# Bidirectional BFS

def is_escape_possible(blocked: List[List[int]], source: List[int], target: List[int]) -> bool:

    if len(blocked) < 2:
        return True
    n = 10 ** 6
    block_set = set(map(tuple, blocked))

    #initialize two deque

    bfs_que_s = deque([tuple(source)])
    bfs_que_t = deque([tuple(target)])

    # visited sets for the two points

    visited_s = set([tuple(source)])
    visited_t = set([tuple(target)])

    # wave set means the outline of BFS

    wave_s = set([tuple(source)])
    wave_t = set([tuple(target)])

    # BFS into the next layer, if the current queue is empty, return False, which means this point is sealed by blocks

    def bfs_next(bfs_que, visited, wave):
        size = len(bfs_que)
        if not size:
            return False
        wave.clear()
        for _ in range(size):
            c_r, c_c = bfs_que.popleft()
            for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
                n_r = c_r + dx
                n_c = c_c + dy
                if 0 <= n_r < n and 0 <= n_c < n and (n_r, n_c) not in block_set and (n_r, n_c) not in visited:
                    bfs_que.append((n_r, n_c))
                    visited.add((n_r, n_c))
                    wave.add((n_r, n_c))
        return True

    # mark the points have escaped or not

    escape_s = False
    escape_t = False

    # when waves share some same values, they met in the search, return True

    while not wave_s & wave_t:
        if not escape_s:
            if not bfs_next(bfs_que_s, visited_s, wave_s):
                return False

            # when wave's length > blocks' length, the point must have escaped the blocks

            if len(wave_s) > len(blocked):
                escape_s = True
        if not escape_t:
            if not bfs_next(bfs_que_t, visited_t, wave_t):
                return False
            if len(wave_t) > len(blocked):
                escape_t = True

        #both of the points are escaped

        if escape_s and escape_t:
            return True
    return True

Here is my idea of the challenge -

If we conduct two independent searches to find out whether either of the two points is blocked or not, we may search for many duplicated and unnecessary points in the case that two points can reach each other. So we can start BFS from both directions simultaneously, one layer frontward and one layer backward; when they meet, we can return True.

Here is my Leetcode result -

So, I would like to know whether I could make this program shorter and more efficient.


texts: Add entities to and execute "ExecuteMultipleRequest"

texts:
I have a method which takes a list of Entity objects, loop through elements in that list and add them to a "ExecuteMultipleRequest" object. After that the ExecuteMultipleRequest will be executed.

However, according to Microsoft Dynamic CRM specs, I can only add at most 1000 entities to ExecuteMultipleRequest at one time, or else that request will throw an error when executed, and my list might have more than 1000 elements.

I have come up with the following solution to make sure that at least 1 request will be executed for every 1000 elements, but I find it to be inelegant. What can I improve here?

private readonly int MAXTOBEPROCESSED = 1000;

public void processEntities (List<Entity> entities)
{
    var toBeProcessed = 0;
    var createMultiple = new ExecuteMultipleRequest()
    {
        Settings = new ExecuteMultipleSettings()
        {
            ContinueOnError = false,
            ReturnResponses = true
        },
        Requests = new OrganizationRequestCollection()
    };

    foreach (var entity in entities)
    {
        var createRequest = new CreateRequest{ Target = entity };
        createMultiple.Requests.Add(createRequest);

        if (++toBeProcessed >= MAXTOBEPROCESSED)
        {
            var responseWithResults = (ExecuteMultipleResponse)service.Execute(createMultiple);

            createMultiple = new ExecuteMultipleRequest()
            {
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = false,
                    ReturnResponses = true
                },
                Requests = new OrganizationRequestCollection()
            };
            toBeProcessed = 0;
        }
    }

    if (toBeProcessed != 0)
    {
        var responseWithResults = (ExecuteMultipleResponse)service.Execute(createMultiple);
    }
}


texts: Print the elements of an array into a table

texts:
I am trying to print the elements of an array into a table, but I'm having trouble formatting the array elements itself.  Perhaps there is a better solution than what I'm currently using?

import java.util.Scanner;
public class RainFall{

  public static void main(String args[]) {
    //create rainfall array
    double[][]rainfall = new double[2][3];
    double sum = 0;
    double average = 0;
    int count = 0;

    Scanner in = new Scanner (System.in);

    System.out.println("Please enter rainfall for Region 1 and Region 2 one after the other");
    //Create For loop to read in data
    for(int i=0;i<rainfall.length;i++){
      for(int j=0;j<rainfall[0].length;j++){
        System.out.println("Enter rainfall:: ");
        rainfall[i][j]=in.nextDouble();
      }
    }
    //create for loop to sum rainfall
    for (int i=0; i < rainfall.length; i++){
      for (int j=0; j < rainfall[0].length; j++){
        sum += rainfall[i][j];
        count++;
      }//end nested for
     }//end outer for

    //calculate average
    average = sum/count;
    //Print table
    System.out.printf( "%5s %10s %15s %20s %25s %n", "Region 1"," Jan", "Feb", "Mar", "Avg Rainfall");
    System.out.printf( "%d", rainfall[0][0] );

    //Print average

    System.out.println("The average rainfall is: " + average);
  }
}


texts: Partitioning a list in F# based on whole group characteristics

texts:
I only started programming in F# yesterday, so I've not yet discovered what idiomatic F# actually looks like.

The first task I set myself required partitioning a list into smaller lists but where the partitioning is based on the characteristics of the whole group, rather than just being able to find split points based on the current element.

For example, given the list [1;2;3;4;5], I might want to group into sub-lists when the sum of the sub-list has reached at least 5. This would result in the output [[1;2;3]; [4;5]].

Any remaining elements that don't meet the criteria would be in a final sub-list.

My first attempt is below:

module Test

let rec partitionOn groupComplete list =
    let take list n = Seq.take n list

    // Take items from the front of the list until they form a complete group
    // or there are no more items
    let firstGroupAndRemainder itemsList =
        let firstGroup =
            [0 .. List.length itemsList]
            |> Seq.map (take itemsList)
            |> Seq.tryFind groupComplete
        match firstGroup with
        | Some g ->
            let groupList = g |> Seq.toList
            let remainingList = Seq.skip (List.length groupList) itemsList |> Seq.toList
            (groupList, remainingList)
        | None -> (itemsList, [])

    match list with
    | [] -> []
    | _ ->
        let group, rest = firstGroupAndRemainder list
        [group] @ partitionOn groupComplete rest

[<EntryPoint>]
let main argv =
    // Groups with sum greater than 5 (plus remaining elements)
    let result1 = partitionOn (fun l -> Seq.sum l > 5) [1;5;2;6;2]
    printfn "result1: %A" result1 // [[1;5]; [2;6]; [2]]

    // Groups with length 3 (plus remaining elements)
    let result2 = partitionOn (fun l -> Seq.length l = 3) [1;5;2;6;2]
    printfn "result2: %A" result2  // [[1;5;2]; [6;2]]

    0

It feels like there should be a simpler way to achieve this but I haven't yet thought of it.

Update

I've discovered the defaultArg function, so the firstGroupAndRemainder function might be slightly tidier as:

let firstGroupAndRemainder itemsList =
    let firstGroup =
        [0 .. List.length itemsList]
        |> Seq.map (take itemsList)
        |> Seq.tryFind groupComplete
    let groupList = (defaultArg firstGroup (List.toSeq itemsList)) |> Seq.toList
    let remainingList = Seq.skip (List.length groupList) itemsList |> Seq.toList
    (groupList, remainingList)


texts:
I want some recommendations or something I could add to the game. Please tell me what I could do better or what I did wrong. I made this during the time I learned Python.

import random
num = random.randint(1, 100)
while True:
    print('Guess a number between 1 and 100')
    guess = input()
    i = int(guess)
    if i == num:
        print('You won!!!')
        break
    elif i < num:
               print('Try Higher')
    elif i > num:
               print('Try Lower')
#any recommendations for the game end
print('if you gussed less than 6 times you won')


texts: Dynamically create a table with values from an object

texts:
I want to create a table that looks like this:

--------------------------------------------------
|                         | USD            |CAD   |
--------------------------------------------------
|Smallest Donation        | 100            |250   |
--------------------------------------------------
|Largest Donation         | 9200           |7600  |
--------------------------------------------------
|                                                 |
--------------------------------------------------
|Total Donation           | 12500          |11000 |
--------------------------------------------------

using the values from this object:

perCurrency: {USD:{0:100, 1:200, 2:9200, 3:1500, 4:1500}, PHP:{0:250, 1:7600, 2:150, 3:3000}}

I have this code and it actually works, though I believe there's an easier and shorter way to this using only one loop.

var numOfCurrency = Object.keys(perCurrency).length + 1;
var donation_table = '';
donation_table += '
';
donation_table += '
&nbsp;	';

$.each(perCurrency, function(index, value){
  donation_table += ''+index+'	';
});

donation_table += '

Smallest Donation	';
$.each(perCurrency, function(index, value){
  var lowest = Infinity;
  $.each(value, function(k, v){
    if (v < lowest) lowest = v;
  });
  donation_table  += ''+lowest+'	';
});

donation_table += '

Largest Donation	';
$.each(perCurrency, function(index, value){
  var highest = 0;
  $.each(value, function(k, v){
    if (v > highest) highest = v;
  });
  donation_table += ''+highest+'	';
});

donation_table += '

&nbsp;

Total Donation	';
$.each(perCurrency, function(index, value){
  var total = 0;
  $.each(value, function(k, v){
    total = total + v;
  });
  donation_table += ''+total+'	';
});

donation_table += '

';

$("#giving_capacity").html(donation_table);

I am trying to put this table in a div with an id #giving_capacity.


texts: Using std::chrono to make custom "SI unit" types

texts:
std::chrono::duration is a great example of how to create "units" using std::ratio. std::ratio by itself is not very useful for a "units" library, and the two choices are either something like Boost.Unit (which can be very complicated to use) or to write it yourself (why reinvent the wheel?) Therefore I'm trying to write a wrapper around std::chrono::duration for some very basic types, like meter, feet, inches and centimeters.

Right now I feel like the way I've constructed the types is sloppy. It took me a while to get it right (at least for the test cases.)

I also haven't figured out a good way to "rename" the types either. I've considered creating a templated struct that inherits from duration and then just renames the typedefs.

Another concern I have is whether I should use double instead of float and if there's a better way to avoid floating point errors.

#include <iostream>
#include <chrono>
#include <ratio>
#include <cmath>  /* for std::abs(double) */

// https://isocpp.org/wiki/faq/newbie#floating-point-arith
// "Why doesn’t my floating-point comparison work?"
constexpr inline bool isEqual(double x, double y)
{
  const double epsilon = 1e-5;
  return std::abs(x - y) <= epsilon * std::abs(x);
  // see Knuth section 4.2.2 pages 217-218
}

int main()
{
    using meters = std::chrono::seconds;

    // There are 100 centimeters per meter
    using centimeters = std::chrono::duration<float, std::ratio_divide<meters::period, std::ratio<100>>>;

    // There are 2.54 centimeters per inch
    // and 39.3701 inches per meter
    using inches = std::chrono::duration<float, std::ratio_divide<centimeters::period, std::ratio<100, 254>>>;

    // There are 12 inches per foot
    using feet = std::chrono::duration<float, std::ratio_multiply<std::ratio<12>, inches::period>>;

    static_assert(inches(1) * 12 == feet(1), "");
    static_assert(centimeters(2.54) == inches(1), "");

    /* Thanks to rounding, inches(1) / 2.54 is 0.393701.
     * To get 0.3937007874, we need to use inches(1 / 2.54)
     * instead.
     */
    static_assert(inches(1 / 2.54) == centimeters(1), "");
    static_assert(centimeters(100) == meters(1), "");

    static_assert(inches(centimeters(100)) == meters(1), "");
    static_assert(isEqual(inches(centimeters(100)).count(), 39.3701), "");
}


texts: Is this a good way to implement a tile map from a text file?

texts:
I'm working on a small final fantasy type game. I have this for a tile map. I was just wondering if this is a good way to do this or if anyone has any suggestions, I would love to read them.

import com.stardust.main.gfx.Assets;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TileMap
{
   //placeholder for each tile
   BufferedImage[] tiles = new BufferedImage[37];

   //array of tile types
   int[][] map = new int[32][32];
   //position coordinates
   public static int posX, posY;
   //Edge of map Cooridinates
   public static int sx, sy;
   public String fileName;

   public TileMap(int posX, int posY, String fileName) throws IOException
   {
       this.fileName = fileName;
       int x = 0, y = 0;
       this.posX = posX;
       this.posY = posY;
       this.sx = map.length * 32;
       this.sy = map.length * 32;
       BufferedReader in = new BufferedReader(new FileReader(fileName));

       String line;

       while((line = in.readLine()) != null)
       {
           String[] values = line.split(",");

           for(String str : values)
           {
               int str_int = Integer.parseInt(str);
               map[x][y] = str_int;
               y += 1;
           }
           x += 1;
           y = 0;
       }

       in.close();
   }

   public void update()
   {
   }

   //Game.mapX and Game.mapY are the position variables in the main Game class
   public void render(Graphics g)
   {
       for(int x = 0; x < 32; x++)
       {
           for(int y = 0; y < 32; y++)
           {
               int textureType = map[x][y];
               setTile();
               BufferedImage texture = tiles[textureType];
               g.drawImage(texture, posX, posY, null);
               posY += 32;
           }
           posX += 32;
           posY = Game.mapY;
       }
       posX = Game.mapX;
       posY = Game.mapY;

   }

   public void setTile()
   {
       tiles[0] = Assets.grass;
       tiles[1] = Assets.dirt;
       tiles[2] = Assets.water;
       tiles[3] = Assets.tree;
       tiles[4] = Assets.multiTree;
       tiles[5] = Assets.NSpath;
       tiles[6] = Assets.uprtPath;
       tiles[7] = Assets.EWpath;
       tiles[8] = Assets.upltPath;
       tiles[9] = Assets.dnltPath;
       tiles[10] = Assets.dnrtPath;
       tiles[11] = Assets.watgrsdn;
       tiles[12] = Assets.watgrslt;
       tiles[13] = Assets.watgrsup;
       tiles[14] = Assets.watgrsrt;
       tiles[15] = Assets.watgrsSE;
       tiles[16] = Assets.watgrsSW;
       tiles[17] = Assets.watgrsNW;
       tiles[18] = Assets.watgrsNE;
       tiles[19] = Assets.wallWood;
       tiles[20] = Assets.pointer;
       tiles[21] = Assets.pathOpRt;
       tiles[22] = Assets.pathOpLt;
       tiles[23] = Assets.pathOpDn;
       tiles[24] = Assets.pathOpUp;
       tiles[25] = Assets.pathOpAll;
       tiles[26] = Assets.roughWood;
       tiles[27] = Assets.pathOpen;
       tiles[28] = Assets.counter;
       tiles[29] = Assets.storeDude;
       tiles[30] = Assets.pot;
       tiles[31] = Assets.singleHouse;
       tiles[32] = Assets.doubleHouse;
       tiles[33] = Assets.wepBanner;
       tiles[34] = Assets.armBanner;
       tiles[35] = Assets.innBanner;
       tiles[36] = Assets.blankTile;
   }
}


texts: Delete engine for deeply nested linked structure

texts:
The background is the question at https://stackoverflow.com/questions/36634394/nested-shared-ptr-destruction-causes-stack-overflow. To summarize, for a data structure that looks like:

// A node in a singly linked list.
struct Node {
    int head;
    std::shared_ptr<Node> tail;
};

If the list grows too long, a stack overflow might occur in the destructor of Node due to recursive destructions of the shared_ptrs. I'm implementing a thread-safe version of the delete engine proposed in https://stackoverflow.com/a/36635668/3234803.

There are three simple classes involved: SpinLock, ConcurrentQueue, and DeleteEngine.

The SpinLock class implements the C++ Lockable interface with a std::atomic_flag:

class SpinLock {
public:
    void lock()
    { while (lock_.test_and_set(std::memory_order_acquire) {} }

    bool try_lock() // Not camel-case to be compatible with C++ Lockable interface
    { return !lock_.test_and_set(std::memory_order_acquire); }

    void unlock()
    { lock_.clear(std::memory_order_release); }

private:
    std::atomic_flag lock_ = ATOMIC_FLAG_INIT;
};

The ConcurrentQueue class implements a multiple-producer-single-consumer queue that supports thread-safe enqueue and tryDequeue:

template<typename T>
class ConcurrentQueue {
public:
    void enqueue(T item)
    {
        std::lock_guard<SpinLock> lk(lock_);
        queue_.emplace_back(std::move(item));
    }

    bool tryDequeue(T &item)
    {
        std::lock_guard<SpinLock> lk(lock_);
        if (queue_.empty()) {
            return false;
        }
        item = std::move(queue_.front());
        queue_.pop_front();
        return true;
    }

private:
    std::deque<T> queue_;
    SpinLock lock_;
};

The DeleteEngine class implements the delete engine proposed in the answer aforementioned:

template<typename T>
class DeleteEngine {
public:
    ~DeleteEngine()
    {
        std::lock_guard<SpinLock> lk(deleting_);
        deleteAll();
    }

    void enqueue(T *p)
    {
        queue_.enqueue(p);
        if (deleting_.try_lock()) {
            std::lock_guard<SpinLock> lk(deleting_, std::adopt_lock);
            deleteAll();
        }
    }

private:
    void deleteAll()
    {
        T *p = nullptr;
        while (queue_.tryDequeue(p)) {
            delete p;
        }
    }

    ConcurrentQueue<T *> queue_;
    SpinLock deleting_;
};

Now in the deleter of a shared_ptr<Node>, we will hand the raw pointer to a DeleteEngine<Node> instead of directly deleteing it. A recursive delete can handle up to about 10000 nodes, while this method can handle an arbitrarily large number of nodes.

The above code is only a prototype, but I'm particularly concerned about the performance of this implementation: (1) Most of the time the Node class would be used in a single-threaded environment; (2) Occasionally it might be used in highly concurrent applications, e.g. a web server that constantly creates and destroys objects.


texts: Bellman-Ford Implementation in Scala/Java

texts:
I think the part to get shortest path from the cost table got pretty messy. Also can use some tips on how to avoid the extra O(V+E) work checking all edges from source to dest after getting the cost table, or have a better optimized implementation in general.
DirectedGraph.scala
case class Vertex(id: String)
case class Edge(source: Vertex, dest: Vertex, weight: Int)

class DirectedGraph {
  val adjacencyTable: mutable.Map[Vertex, Array[Edge]] = new mutable.HashMap[Vertex, Array[Edge]]()

  def addVertex(vertex: Vertex): Unit = adjacencyTable.put(vertex, new Array[Edge](0))

  def addEdge(source: Vertex, dest: Vertex, weight: Int): Unit =
    adjacencyTable.put(source, adjacencyTable(source) :+ Edge(source, dest, weight))

  def getEdges: Array[Edge] = adjacencyTable.keys.flatMap(i => adjacencyTable(i)).toArray
}

BellmanFord.java
public class BellmanFord {

  private DirectedGraph graph;

  public BellmanFord(DirectedGraph graph) {
    this.graph = graph;
  }

  public List<Vertex> getShortestPath(Vertex source, Vertex dest) {
    Map<Vertex, Integer> costs = getCostMap(source);
    List<Vertex> retList = new ArrayList<>();
    Edge minEdge = null;

    retList.add(source);

    if (source == dest) return retList;
    if (graphHasNegativeCycle(costs))
      throw new IllegalStateException("Graph cannot have negative cycles");
    if (costs.get(dest) == Integer.MAX_VALUE)
      throw new IllegalArgumentException("There are no valid paths from source to destination");

    for (Edge e : graph.adjacencyTable().get(source).get())
      if (minEdge == null || e.weight() < minEdge.weight())
        minEdge = e;

    retList.addAll(getShortestPath(minEdge.dest(),dest));
    return retList;
  }

  private Map<Vertex, Integer> getCostMap(Vertex source) {
    Map<Vertex, Integer> ret = initCostMap(source);
    for (int i = 0; i < ret.size() - 1; i++) {
      relaxEdges(ret);
    }
    return ret;
  }

  private void relaxEdges(Map<Vertex, Integer> costMap) {
    for (Edge edge : graph.getEdges()) {
      if (costMap.get(edge.source()) + edge.weight() < costMap.get(edge.dest())) {
        costMap.put(edge.dest(), costMap.get(edge.source()) + edge.weight());
      }
    }
  }

  private boolean graphHasNegativeCycle(Map<Vertex, Integer> costMap) {
    for (Edge edge : graph.getEdges()) {
      if (costMap.get(edge.source()) + edge.weight() < costMap.get(edge.dest())) {
        return true;
      }
    }
    return false;
  }

  private Map<Vertex, Integer> initCostMap(Vertex source) {
    Map<Vertex, Integer> costMap = new HashMap<>();
    graph.adjacencyTable().foreach(
        kvp -> costMap.put(kvp._1, kvp._1 == source ? 0 : Integer.MAX_VALUE)
    );
    return costMap;
  }
}


texts: Terraform/HCL - First element (or any arbitrary element) from a list of sets, combined into a list

texts:
So I am working with Terraform and I feel like there must be a faster or, at the very least, a prettier way to perform the operation I'm attempting.

For some boilerplate, I have a data block that looks like the following:

data "aws_subnet_ids" "lambda_subnet_ids" {
  count  = length(var.lambda_subnet_tags)
  vpc_id = ...
}

From the results of this data block, I want to retrieve the first value from each set and combine it into another list. Here's how my team approached it before me. I wrapped it in a locals block to made it easier to see the use-case:

locals {
  lambda_subnet_ids = flatten(
    [
      for subnets in data.aws_subnet_ids.lambda_subnet_ids :
        [
          element(tolist(subnets.ids), 1)
        ]
    ]
  )
}

Now, this works. It just looks awful. I feel like there has to be a nicer way to perform this same operation, but I am not familiar with HCL well enough to know what to look for.

Side note, this really should have the tags HCL and Terraform, but I do not have the reputation required to create them.


texts:
I'm creating a Django project where users can decide to delete their account and everything we know about them (solved riddles, votes ...).
I think you can compress this code but I don't know how.

I have a User related to Comment, Report, Vote, .... And I've got a Userprofile with a user relation:

class UserProfile(models.Model):
    User = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Benutzer", unique=True, primary_key=True, default=None)
    # Some other fields

Comment-User relation:

class Comment(models.Model):
    User = models.ForeignKey(User, on_delete=models.CASCADE, default=None, verbose_name="Kommentierender")

Report, Vote, UserClicked, UserVoted, SolvedRiddle have the same relation like Comment.

Article-User relation:

class Article(models.Model):
    authors = models.ManyToManyField(User, verbose_name="Autor", blank=True, default=None)

that's my del method in userprofile to delete everything from a user:

def __del__(self):
    user = self.User
    if user is None:
        return False
    Comment.objects.filter(User=user).delete()
    Report.objects.filter(User=user).delete()
    Vote.objects.filter(User=user).delete()

    userclicked = UserClicked.objects.filter(User=user)
    if userclicked.exists():
        for object in userclicked:
            del object

    uservoted = UserVoted.objects.filter(User=user)
    if uservoted.exists():
        for object in uservoted:
            del object

    author_article = Article.objects.filter(authors__in=[user, ])
    if author_article.exists():
        for object in author_article:
            object.remove_author(user)

    solvedriddle_user = SolvedSolution.objects.filter(User=user)
    if solvedriddle_user.exists():
        for object in solvedriddle_user:
            del object

    self.User.delete()
    self.delete()
    return True


texts:
Model:

public class UserBean {
    @JsonProperty
    private String userId;
    @JsonProperty
    private int limit;
    @JsonProperty
    private int page;

    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public int getLimit() {
        return limit;
    }
    public void setLimit(int limit) {
        this.limit = limit;
    }
    public int getPage() {
        return page;
    }
    public void setPage(int page) {
        this.page = page;
    }
}

public class ResponseJSON {
    private Map<String, Object> response = new LinkedHashMap<String, Object>();
    public void setStatus(String status) {
        response.put("status", status);
    }
    public void setMessage(String message) {
        response.put("message", message);
    }
    public void add(String key, Object value) {
        response.put(key, value);
    }
    public Map<String, Object> get() {
        return this.response;
    }
}

Controller:

@ResponseBody
@RequestMapping(value = "/user/products", method = RequestMethod.POST)
public Object getProductListByUser(@RequestBody UserBean userBean) {
    ResponseJSON responseJSON = new ResponseJSON();
    try {
        List<Object> result = userRepository.getProductListByUser(userBean);
        int resultCount = result.size();

        List<Object> productList = new ArrayList<Object>();
        for (int i = 0; i < resultCount; i++) {
            ProductInfo product = (ProductInfo) result.get(i);

            Map<String, Object> productInfo = new LinkedHashMap<String, Object>();
            productInfo.put("id", product.getId());
            productInfo.put("title", product.getTitle());
            productInfo.put("description", product.getDescription());
            productInfo.put("iconImage", product.getIconImage());
            productInfo.put("updateDatetime", product.getUpdateDatetime());
            productInfo.put("createDatetime", product.getCreateDatetime());
            productList.add(productInfo);
        }

        responseJSON.setStatus(Constants.SUCCESS);
        responseJSON.add("items", productList);
    } catch (Exception e) {
        responseJSON.setStatus(Constants.FAIL);
        responseJSON.setMessage(e.getMessage());
        logger.error(e.getMessage());
    }

    return responseJSON.get();
}

Repository:

@SuppressWarnings("unchecked")
@Transactional
public List<Object> getProductListByUser(UserBean userBean) {
    Session session = sessionFactory.getCurrentSession();

    Criteria criteria = session.createCriteria(ProductInfo.class, "product")
        .createAlias("product.productOptions", "options", CriteriaSpecification.LEFT_JOIN)
        .add(Restrictions.eq("product.userId", userBean.getUserId()))
        .addOrder(Order.asc("productOptions.size"))
        .setFirstResult((userBean.getPage() - 1) * userBean.getLimit());
        .setMaxResults(userBean.getLimit());

    return criteria.list();
}

I'm developing some back-end APIs.
This API returns product lists of some user.
Purpose of this API is returning result of JSON data.
So, I get datas from repository and assign to ResponseJSON object in the controller.
Is this approach efficient or not? Which way is better?


texts: Cleaner Way to Structure Asynchronous Code

texts:
The purpose of the code is to allow the user to select directories that will be crawled recursively in order to find particular files or file types to analyze en masse. The thing to bear in mind is that if C:\ is already selected, then any child path of C:\ that the user tries to select will be discarded. The entire process of the script can be broken down into the following steps:

The user selects a directory or directories via a dialog box.
The script then compares the selection to whatever directories might already be stored in an array in the configuration file, which is a JSON object.
If the selection is invalid, the selection is discarded. / If the selection is valid, the configuration file is modified accordingly.

Obviously promises are ideal, so I'm using Node's fs.promises. However, the tricky bit is that, although they're asynchronous, parts of the code must behave synchronously. For example, it would be a waste of resources to retrieve the array from the configuration file if the dialog box is cancelled by the user.

I'm completely new to promises and everything else that entails, so I'm wondering whether or not there's an even better way to structure the asynchronous code or the code in general? The code works fine the way it is, but can its structure/readability and or efficiency be improved?

async function userSelectsArchives()
{
  try {
    const r1 = await dialog.showOpenDialog(remote.getCurrentWindow(), {
      title: 'Select Archives to Analyze',
      buttonLabel: 'Select Archives',
      defaultPath: 'c:\\',
      properties: [ 'openDirectory', 'multiSelections' ]
    })

    if (r1.canceled) throw new Error('Dialog cancelled.')

    const
      r2 = await fsp.readFile('./config.json', 'utf8'),
      config = JSON.parse(r2),
      archivesOG = config.archives

    for (const dir of r1.filePaths){
      // Disregard user input if parent path or exact match already exists.
      if (
        config.archives.reduce((a, v) => {
          return a || dir.indexOf(v.slice(-1) === '\\' ? v : (v + '\\')) === 0
        }, false)
        || config.archives.includes(dir)
      ) continue
      // Remove child paths of user input in config.
      config.archives = config.archives.filter(
        v => v.indexOf(dir.slice(-1) === '\\' ? dir : (dir + '\\')) !== 0
      )
      // Add user input to archive.
      config.archives.push(dir)
    }

    // Verify that changes have occurred or throw error.
    if (archivesOG === config.archives) throw new Error('Invalid selection.')

    await fsp.writeFile('./config.json', JSON.stringify(config, null, 2), 'utf8')

    displayDirs(config.archives)
  }
  catch (error) {
    console.error(error)
  }
}


texts:
I've come up with a very efficient way of finding if a number is prime, using TI-BASIC for use with TI-83/84/+/SE calculators. I am trying to optimize it however possible.

:Input "NUMBER: ",A
:If A<2 or fPart(A
:Then
:Disp "INVALID INPUT"
:Stop
:End
:0→B
:2→I
:While I<A and not(B
:If 0=fPart(A/I
:1→B
:I+2→I
:If I=4
:3→I
:End
:If B
:Disp "NOT"
:Disp "PRIME"

A few notes:

Lines 2-6 are for validating input, and don't affect the effectiveness of the program.
The closing "s on line 4 and the last two lines are not necessary, but I added them so the syntax would highlight nicely here.
Lines 12-14 are for speeding up the loop doubly; instead of incrementing by 1 each time, it is by 2, with the If to offset the 4 to 3 on the first run.
The not(B was very efficient, to end the loop whenever a match to identify the number as a composite number is found.


texts: First attempt at generating prime numbers

texts:
I had to look up some other solutions online because I could not figure it out on my own. I really wish I could have come up with it completely on my own, but that didn't happen. Nevertheless, please review my prime number program and let me know if there are any improvements I should make or advice your would like to give me about it.

     var primes = [];                    // will become a list of prime numbers

primes_loop:
for (var n = 2; n < 10; n++) {

    if (n === 2) {
        primes.push(n);              // first prime number is stored
        continue primes_loop;        // continue iteration of the loop
    }

    divisors_loop:
    for (var i = 2; i < n; i++) {

        if (n % i === 0) {
            break divisors_loop;     // n is not prime if condition is true
        }
        else {
            primes.push(n);          // update prime list with the prime number
        }

    }

}

for (var index = 0; index < primes.length; index++) {
    console.log(primes[index]);
}


texts:
I wrote a simple FIFO based on pieces of code I found online.
It's intended for embedded systems with very restricted RAM.
It's supposed to be very simple and efficient.
The size is always power of 2 (8, 16, 32, 64, 128 etc).
fifo.h
    #ifndef FIFO_H
    #define FIFO_H

    struct fifo
    {
        volatile uint8_t * data_ptr;
        volatile uint16_t size;
        volatile uint16_t write_index;
        volatile uint16_t read_index;
        volatile uint16_t elements;
    };

    #endif

fifo.c
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "fifo.h"

void fifo_init(struct fifo * fifo)
{
    memset(fifo->data_ptr, (uint8_t)0, fifo->size);
    fifo->write_index = 0;
    fifo->read_index = 0;
}

bool fifo_is_full(struct fifo * fifo)
{
    if (fifo->elements == fifo->size)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

bool fifo_is_empty(struct fifo * fifo)
{
    if (fifo->elements == 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

bool fifo_add_byte(struct fifo * fifo, uint8_t newbyte)
{
    if (fifo_is_full(fifo))
    {
        return 0;
    }
    else
    {
        if (fifo->data_ptr == NULL)
        {
            return 0;
        }
        const uint16_t MASK = fifo->size - 1;
        fifo->data_ptr[fifo->write_index] = newbyte;
        fifo->write_index = (++fifo->write_index) & MASK;
        fifo->elements++;
        return 1;
    }
}

bool fifo_get_byte(struct fifo * fifo, uint8_t * output)
{
    if (fifo_is_empty(fifo))
    {
        return 0;
    }
    else
    {
        if (fifo->data_ptr == NULL)
        {
            return 0;
        }
        const uint16_t MASK = fifo->size - 1;
        *output = fifo->data_ptr[fifo->read_index];
        fifo->read_index = (++fifo->read_index) & MASK;
        fifo->elements--;
        return 1;
    }
}

The actual buffer is implemented at other source files like:
uint8_t rx_buffer[RX_BUFFER_SIZE];
struct fifo fifo = {
    .data_ptr = rx_buffer,
    .size = RX_BUFFER_SIZE,
};


texts: Flexbox layout, columns, rows, multiple heights

texts:
I wanted everything to just snap into place, but found I had to add spacing to some of the items in order to line them up. It's still neater than trying to float things, and Grid isn't ready yet. But any advice/feedback will be appreciated.

div {padding:0px;margin:0;}
.container {
  display:flex;
  width:1070px;
  min-height:500px;
  margin:0 auto;
  flex-flow:row wrap;
  justify-content:space-between;
  align-content:space-between;
  align-items:flex-start;
  box-sizing:border-box;
}
.item > .item:first-child {padding-bottom:5px;}
.full-width {padding:5px 0;}

https://codepen.io/wagonlips/pen/zZzLqG


texts: C# beginner's exercise in calling methods

texts:
This is one of my first experiences with C#. I'm trying to learn and as can be seen, I need some obvious help. I know it's only an example but I'd like to start with best practices from the beginning. This was my first experience with public and private methods.

What can I do to improve my code and why is the change better? What about it makes it preferred or a best practice?

using System;

namespace CallMethodsWithinSameClass
{
    class Program
    {
        static void Main()
        {
            bool I_Has_Energy = true;
            OtherClass TestClass = new OtherClass();
            I_Has_Energy = TestClass.NoIDont;
            Console.WriteLine("Do I have energy? " + I_Has_Energy);
            Console.WriteLine("Getting a public method " + TestClass.GiveMeAString());
            Console.WriteLine("Grabbing the privates " + TestClass.GrabThemPrivates());
            Console.ReadKey();
        }
    }

    class OtherClass
    {
        public bool YesIDo = true;
        public bool NoIDont = false;
        public string SimpleString = "This is only a test.";
        public string GiveMeAString()
        {
            return "Here's your sign, I mean string.";
        }
        private string KeepItToYourself()
        {
            return "Make sure you'll be gentle with them... *Wink*";
        }
        public string GrabThemPrivates()
        {
            return KeepItToYourself();
        }
    }
}


texts:
I want to be able to convert a list of objects into a string csv format.  I've written this extension method below but have a feeling I'm missing something as this seems like potentially a common thing to want to do.

private static readonly char[] csvChars = new[] { ',', '"', ' ', '\n', '\r' };

public static string ToCsv<T>(this IEnumerable<T> source, Func<T, object> getItem)
{
    if ((source == null) || (getItem == null))
    {
        return string.Empty;
    }

    var builder = new StringBuilder();
    var items = from item in source.Select(getItem)
                where item != null
                select item.ToString();

    foreach (var str in items)
    {
        if (str.IndexOfAny(csvChars) > 0)
        {
            builder.Append("\"").Append(str).Append("\"").Append(", ");
        }
        else
        {
            builder.Append(str).Append(", ");
        }
    }

    var csv = builder.ToString();

    return csv.Length > 0 ? csv.TrimEnd(", ".ToCharArray()) : csv;
}

Is there anything I can do to improve this or refactor to a more elegant or working solution.  Or even an existing method out there already that I may have missed.

UPDATE:  Updated to take into account quotations as per Jesse comments below.


texts:
I wanted to wrap the jkeymaster library in a Clojure wrapper (for my own use, but perhaps also to save others some time). I'm just learning Clojure so I'm still not quite sure what "idiomatic libraries/APIs" look like. In Ruby, I would have created an object with methods, but in one of the clojure books they recommended letting users manage state themselves, so I have function that creates a provider, and this provider must then be passed to the register function.

Here's first an example of usage:

(ns keymaster.core
  (:require [keymaster.keymaster :as km]))
(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (km/register (km/provider) "control shift 1" #(println "hi")))

And here is the full text of the "library".

(ns keymaster.keymaster
  (:gen-class)
  (:use (com.tulskiy.keymaster.common)))

(defn provider []
  "Gets and initiates a keymaster provider, which must be passed to register to register shortcuts"
  (let [provider (com.tulskiy.keymaster.common.Provider/getCurrentProvider true)]
    (.init provider)
    provider))

(defn- conv-keystroke [x]
  "Takes keystroke in the form \"control shift 1\" and returns a Keystroke class"
  (javax.swing.KeyStroke/getKeyStroke x))

(defn- conv-listener [f]
  "Takes a function with one argument, which will get passed the keycode, and creates a listener
   Todo: How to accept a function with or without a parameter to accept hotKey?"
   (proxy [com.tulskiy.keymaster.common.HotKeyListener] [] (onHotKey [hotKey] (f))))

(defn register
  [provider shortcut listener]
  "Registers a shortcut on provider, which will trigger listener (with one argument)"
  (let [k (conv-keystroke shortcut)
        l (conv-listener listener)]
    (.register provider k l)))

In addition to any general style feedback, both about the coding, and the design of the API, I'm also wondering if there is any way to have conv-listener accept either a 0 or 1-arity function. Right now I made the choice of accepting a 0-arity function, but if someone wanted to pass a 1-arity function, where the first argument would be the name of the keycode called (hotKey), which I would call with (f hotKey), I would have to rewrite... Possible to allow both? (1-arity is inconvenient for anonymous functions where we really don't need it - which I suspect is most of the time, since we can bind different hotkeys to different listeners).


texts:
I have some code which looks like this:

do {
    hr = pEnumMgmt->Next(1, &mgmtObjProp, &ulFetched);
    if (hr == S_FALSE) { break; }
    llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;
} while (hr != S_FALSE);

It is bad because hr == S_FALSE is checked twice on every iteration.

I could write it like this:

while (true) {
    hr = pEnumMgmt->Next(1, &mgmtObjProp, &ulFetched);
    if (hr == S_FALSE) { break; }
    llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;
};

It is bad because it gives the impression that there exists no loop invariant (i.e. it could be an infinite loop, which would be a programmer error).

Finally, I could write it with gotos, but that is bad because gotos are considered harmful. Also, it gets really hard to check the correctness of the loop.

How would you write this loop and why?


texts:
I am implementing an automated help function in my code. It is simply a few bubbles that pop up with some text in them. I use d3 to select one bubble, display it for a short time, and then select another bubble and display that one. It works, but I don't like the shape the code is taking. Am I approaching this correctly?

d3.select("#targetYear-bubble")
    .transition().duration(2000)
    .style("opacity", 1)
    .transition().duration(2000)
        .style("opacity", 0)
        .each("end", function()
        {
            d3.select("#navTree-bubble").transition().duration(2000)
                .style("opacity", 1)
                .transition().duration(2000)
                .style("opacity", 0);
        })
        ;

This code displays 2 pop-up bubbles. It's manageable for now, but if I had a complex screen with 7 or 8 (or more) bubbles, this code would be much too complex.

Can someone make a suggestion for a better implementation of this?


texts:
I am learning python from CS106. Please review my code for Khan Sole Academy, I think my code not efficient. Please add critique and advice for beginner like me.
About Code
Generate 2 random numbers and add those numbers. If the user supplied answer is correct, row will increase by 1, goal is 3. If answer is false, row will be reset to zero.
Question From Assignment CS106

Your program should be able to generate simple addition problems that involve adding two 2-digit integers (i.e., the numbers 10 through 99).  The user should be asked for an answer to each problem.  Your program should determine if the answer was correct or not, and give the user an appropriate message to let them know.  Your program should keep giving the user problems until the user has gotten 3 problems correct in a row.
(Note: the number of problems the user needs to get correctly in a row to complete the program is just one example of a good place to specify a constant in your program)

   import random

MIN_NUM = 10
MAX_NUM = 99
row = 0

def main():
    """
    Pre Condition: Generate random number. Additional num 1 and num 2
    Post Condition : Check user answers. If answer correct add row, if incorrect reset row to zero
    """
    row = 0
    while row < 3:
        # number generator
        num_1 = random.randint(MIN_NUM, MAX_NUM)
        num_2 = random.randint(MIN_NUM, MAX_NUM)
        print("What is " + str(num_1) + " + " + str(num_2) + " ?")
        total = num_1 + num_2
        #user answer
        user_input = int(input("Your answer: "))
        # Check user answer
        # if answer is incorrect, reset row to zero
        if user_input == total:
            row += 1
            print("Correct!  You've gotten " + str(row) +" correct in a row ")
        else:
            print("Incorrect. The expected answer is " + str(total))
            row = 0

if __name__ == "__main__":
    main()


texts:
I have created a BST like many others. I am curious to if there is a better way to write it. It seems pretty straight forward, but I feel like it can be improved on a bit.

//MRBST.h

#ifndef MRBST_H
#define MRBST_H
#include <iostream>

template <class T>
class MRBST {

private:
        struct treeNode
        {
                treeNode* left;
                treeNode* right;
                int data;

        };
        treeNode* root;
        int count;

public:
        void push(const T &);
        MRBST();
        bool search(const T &);
        void PrintPreorder();
        ~MRBST();
        bool empty() const;
        int numberOfNodes() const;
        void preorder(treeNode* pre);

};

template<class T>
MRBST<T>::MRBST()
{
    root = NULL;
    count = 0;
}

template<class T>
void MRBST<T>::push(const T & n)
{
    treeNode* d = new treeNode;
    treeNode* parent;
    d->data = n;
    d->left = NULL;
    d->right = NULL;
    parent = NULL;
    if(empty())
    {
        root = d;
        count++;
    }
    else
    {
        treeNode* current;
        current = root;

        while(current != NULL)
        {
            parent = current;
            if(d->data >= current->data)
            {
                current = current->right;
            }
            else
            {
                current = current->left;
            }
            if(d->data <= parent->data)
            {
                parent->left = d;
            }
            else
            {
                parent->right = d;
            }
        }
        count++;
    }
}

template<class T>
int MRBST<T>::numberOfNodes() const
{
    return count;
}

template<class T>
bool MRBST<T>::empty() const
{
    return root == NULL;
}

template<class T>
void MRBST<T>::PrintPreorder()
{
    preorder(root);
}

template<class T>
void MRBST<T>::preorder(treeNode* pre)
{
    if(pre != NULL)
    {
        std::cout << " " << pre->data << " ";
        if(pre->left)
        {
            preorder(pre->left);
        }
        if(pre->right)
        {
            preorder(pre->right);
        }
    }
}

template<class T>
MRBST<T>::~MRBST()
{
    delete root;

}
#endif


texts: Calculations to position a text box next to another object

texts:
I am implementing a program to draw a box of text next to some other drawn object (that can have any position and dimensions) and the text box should always be visible, even if the drawn object's width is of the entire screen and vice versa.
They should simply not overlap.

This is a code to position the text on some relatively good coordinates.

if(x > (box_w + 20)) box_x = x - (box_w + 20);
else                            box_x = w + 20;
if(y > (box_h + 20)) box_y = y - (box_h + 20);
else                            box_y = h + 20;
if(w > width - (box_h + 20) || x + w + box_w + 20 > width)
{
    box_x = 20;

    if(y < box_h + 20)
    {
        box_y = h + 20;
    }
    else box_y = y - (box_h + 20);
}

x, y, w, h are the coords and dimensions for the object; box_x, box_y, box_w and box_y are for the text box and width/height is the dimension of the area.

Here is schematically how this code positions text (darker blue) near the object (lighter blue)

It is quite obvious that it could have been written much better.
To target performance, but more importantly - code space.

Can anyone suggest a better way to find good coordinates for the text box?


texts: Defining a class that behaves exactly like an `int`

texts:
This is an exercise to create a class that behaves exactly like an int.

Questions

Am I missing anything?
Or did I going about this about this the wrong way?
Is there anything I could improve on?
Are there any tricks that I could learn from this?
How about style; does the style look OK?

#include <iostream> // std::cout
#include <utility>  // std::move

class jd_int {
public:
    jd_int() = default;

    jd_int(int i)             : _i{i}                   { }
    jd_int(const jd_int& jdi) : _i{jdi._i}              { }
    jd_int(jd_int&& jdi)      : _i{std::move(jdi._i)}   { }

    jd_int operator= (int i)             { _i = i; return *this;                 }
    jd_int operator= (double d)          { _i = d; return *this;                 }
    jd_int operator= (const jd_int& jdi) { _i = jdi._i; return *this;            }
    jd_int operator= (jd_int&& jdi)      { _i = std::move(jdi._i); return *this; }

    ~jd_int() = default;

    operator bool()   { return !!_i;                    }
    operator int()    { return static_cast<int>(_i);    }
    operator double() { return static_cast<double>(_i); }

    jd_int operator+=(jd_int jdi) { return _i += jdi._i; }
    jd_int operator+ (jd_int jdi) { return _i +  jdi._i; }

    jd_int operator-=(jd_int jdi) { return _i -= jdi._i; }
    jd_int operator- (jd_int jdi) { return _i -  jdi._i; }

    jd_int operator*=(jd_int jdi) { return _i *= jdi._i; }
    jd_int operator* (jd_int jdi) { return _i *  jdi._i; }

    jd_int operator/=(jd_int jdi) { return _i /= jdi._i; }
    jd_int operator/ (jd_int jdi) { return _i /  jdi._i; }

    jd_int operator%=(jd_int jdi) { return _i %= jdi._i; }
    jd_int operator% (jd_int jdi) { return _i %  jdi._i; }

    jd_int operator++()    { return ++_i;                          }
    jd_int operator++(int) { jd_int tmp = *this; ++_i; return tmp; }

    jd_int operator--()    { return --_i;                          }
    jd_int operator--(int) { jd_int tmp = *this; --_i; return tmp; }

    friend bool operator< (jd_int lhs, jd_int rhs);
    friend bool operator> (jd_int lhs, jd_int rhs);
    friend bool operator<=(jd_int lhs, jd_int rhs);
    friend bool operator>=(jd_int lhs, jd_int rhs);
    friend bool operator==(jd_int lhs, jd_int rhs);
    friend bool operator!=(jd_int lhs, jd_int rhs);

private:
    int _i;

    friend std::ostream& operator<<(std::ostream& os, const jd_int jdi);
    friend std::istream& operator>>(std::istream& is, jd_int jdi);
};

bool operator< (jd_int lhs, jd_int rhs) { return (lhs._i <  rhs._i); }
bool operator> (jd_int lhs, jd_int rhs) { return (lhs._i >  rhs._i); }
bool operator<=(jd_int lhs, jd_int rhs) { return (lhs._i <= rhs._i); }
bool operator>=(jd_int lhs, jd_int rhs) { return (lhs._i >= rhs._i); }
bool operator==(jd_int lhs, jd_int rhs) { return (lhs._i == rhs._i); }
bool operator!=(jd_int lhs, jd_int rhs) { return (lhs._i != rhs._i); }

std::ostream& operator<<(std::ostream& os, const jd_int jdi) {
    os << jdi._i;
    return os;
}

std::istream& operator>>(std::istream& is, jd_int jdi) {
    is >> jdi._i;
    return is;
}
```


texts:
I've been working on a project (link) to download a spreadsheet of known ransomware and properties and turn it into json so I can better consume the information within early detection projects.

I'm new to python - what can I be doing better? The destination json I'm converting can be found here.

update_json.py (entry point)

from excel_to_json import excel_to_json
from download_file import download_file

SOURCESHEET = 'https://docs.google.com/spreadsheets/d/1TWS238xacAto-fLKh1n5uTsdijWdCEsGIM0Y0Hvmc5g/pub?output=xlsx'
OUTPUTSHEET = '../RansomwareOverview.xlsx'
JSONFILE = '../ransomware_overview.json'

def write_json_file(json_data, filename):
    output = open(filename, 'w')
    output.writelines(json_data)

def generate_json(source_file, download_destination, json_file):
    download_file(source_file, download_destination)
    write_json_file(excel_to_json(download_destination), json_file)

generate_json(SOURCESHEET, OUTPUTSHEET, JSONFILE)

download_file.py

import urllib.request

def download_file(source, destination):
    try:
        urllib.request.urlretrieve(source, destination)
    except IOError:
        print('An error occured trying to write an updated spreadsheet. Do you already have it open?')
    except urllib.error.URLError:
        print('An error occured trying to download the file. Please check the source and try again.')

excel_to_json.py

import simplejson as json
import xlrd
from collections import OrderedDict

def excel_to_json(filename):
    wb = xlrd.open_workbook(filename)
    sh = wb.sheet_by_index(0)
    mw = wb.sheet_by_index(2)

    # List to hold dictionaries
    c_list = []

    # Iterate through each row in worksheet and fetch values into dict
    for rownum in range(1, sh.nrows):
        wares = OrderedDict()
        row_values = sh.row_values(rownum)

        if row_values[6]=="":
            name = row_values[0]
            gre=[name]
        elif "," in row_values[6]:
            e=row_values[6].split(",")
            ge = [row_values[0]]
            gre=e+ge
        else:
            gre=[row_values[0],row_values[6]]

        wares['name'] = gre
        wares['extensions'] = row_values[1]
        wares['extensionPattern'] = row_values[2]
        wares['ransomNoteFilenames'] = row_values[3]
        wares['comment'] = row_values[4]
        wares['encryptionAlgorithm'] = row_values[5]
        wares['decryptor'] = row_values[7]
        if row_values[8]=="":
            wares['resources'] = [row_values[9]]
        elif row_values[9]=="":
            wares['resources']=[row_values[8]]
        else:
            wares['resources'] = [row_values[8], row_values[9]]
        wares['screenshots'] = row_values[10]

        for r in range(1, mw.nrows):
            rowe = mw.row_values(r)

            if row_values[0] == rowe[0]:
                wares['microsoftDetectionName']=rowe[1]
                wares['microsoftInfo'] = rowe[2]
                wares['sandbox'] = rowe[3]
                wares['iocs'] = rowe[4]
                wares['snort'] = rowe[5]

        c_list.append(wares)

    # Serialize the list of dicts to JSON
    return json.dumps(c_list, indent=4)


texts:
I am doing some projects so I can teach myself programming. The one that I finished states:
"Credit Card Validator - Takes in a credit card number from a common credit card vendor  and validates it to make sure that it is a valid number (look into how credit cards use a checksum)."
Would be glad if i can get a constructive feedback on this one.

import sys

cardnumb_input = input('Enter your credit card number: ')

def list_tweak():
    try:
        cardnumb = [int(i) for i in cardnumb_input]
        cardnumb[0::2] = [x * 2 for x in cardnumb[0::2]]
        cardnumb = [str(i) for i in cardnumb]
        cardnumb = list(''.join(cardnumb))
        cardnumb = [int(i) for i in cardnumb]
        return cardnumb

    except ValueError:
        print('Please enter only number in format: xxxxxxxxxxxxxxxx')
        sys.exit(1)

def valid_or_not():
    total = sum(list_tweak())
    if total % 10 != 0:
        print('It seems that this credit card number is not valid.')
    else:
        print('This credit card number is valid. ')

valid_or_not()


texts:
For my computer science class I am tasked with writing a rock/paper/scissors game. I understand how to write the game, but I was wondering if someone more experienced than I could give me some pointers on how to become a better programmer.

Is there anything I could do to reduce the size of the code, but without diminishing functionality?

public class RockPaperScissors
{
    static double wins = 0;
    static double losses = 0;
    static double draws = 0;
    static double games = 0;

    private static void lose() {
        System.out.println("YOU LOSE! :D");
        losses++;
        games++;
    }

    private static void win() {
        System.out.println("you win :D");
        wins++;
        games++;
    }

    // main method
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);

        // variables
        Integer answer1 = 0;
        boolean playing = true;

        // start of game
        do
        {
            // main menu
            System.out.println("Input R, P, S, or Q(to quit).");

            // player's move
            String answer = scan.next();
            answer = answer.toLowerCase();

            // converts player's move from str to int
            switch (answer.charAt(0))
            {
            case 'r':
                answer1 = 0;
                break;
            case 'p':
                answer1 = 1;
                break;
            case 's':
                answer1 = 2;
                break;
            case 'q':
                System.out.println("User exit.");
                double winP = wins/games*100;
                double loseP = losses/games*100;
                double drawP = draws/games*100;
                System.out.println("Wins: " + wins);
                System.out.printf("%.2f", winP);
                System.out.println(" Percent");
                System.out.println("Losses: " + losses);
                System.out.printf("%.2f", loseP);
                System.out.println(" Percent");
                System.out.println("Draws: " + draws);
                System.out.printf("%.2f", drawP);
                System.out.println(" Percent");
                playing = false;
                break;
            default:
                System.out.println("ERROR!!");
                playing = false;
                break;
            }

            // checks for conditions
            if (playing)
            {
                // computer's move
                Random random = new Random();
                Integer choice = random.nextInt(3); // (n-1) 0 = rock, 1 = paper, 2 = scissors
                String comp = choice.toString();
                switch (comp)
                {
                case "0":
                    System.out.println("computer chose rock");
                    break;
                case "1":
                    System.out.println("computer chose paper");
                    break;
                case "2":
                    System.out.println("computer chose scissors");
                    break;
                default:
                    System.out.println("ERROR!");
                    break;
                }
                // checks results
                if (answer1 == choice)
                {
                    System.out.println("Draw");
                    draws++;
                    games++;
                }
                else if ((answer1 + 1) % 3 == choice)
                    lose();
                else if ((choice + 1) % 3 == answer1)
                    win();
                else
                    System.out.println("ERROR! ERROR!");
            }
        } while (playing);
    }
}


texts:
We have some required services down temporarily when our server start. So we need some reconnection logic for them until they are finally up.
There is a requirement to have also syncronious way for that.
Here is my generic implementation for that via a single background thread:

public class RunUntilSuccess {

private static final Logger log = LoggerFactory.getLogger(RunUntilSuccess.class);

private final String processName;
private final Task task;
private final int maxAttempts;
private final int interval;
private final TimeUnit unit;
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
private AtomicInteger count = new AtomicInteger(0);

public RunUntilSuccess(String processName, Callable<Boolean> task, int interval, TimeUnit unit) {
    this(processName, task, interval, unit, -1);
}

public RunUntilSuccess(String processName, Callable<Boolean> callable, int interval, TimeUnit unit, int maxAttempts) {
    if (callable == null) {
        throw new IllegalArgumentException("Callable cannot be null");
    }
    this.processName = processName;
    this.task = new Task(callable);
    this.interval = Math.max(0, interval);
    if (unit == null) {
        throw new IllegalArgumentException("Unit cannot be null");
    }
    this.unit = unit;
    this.maxAttempts = (maxAttempts > 0) ? maxAttempts : -1;

    start();
}

private void start() {
    log.debug("Starting task execution. " + toString());
    executor.scheduleWithFixedDelay(task, 0, interval, unit);
}

/**
 * Wait until success
 */
public void await() throws InterruptedException {
    while (!executor.awaitTermination(interval, unit)) { }
}

public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
    return executor.awaitTermination(timeout, unit);
}

private boolean isAttemptsLimitReached(int attempt){
    return (maxAttempts > 0) && (attempt >= maxAttempts);
}

@Override
public String toString() {
    final StringBuilder sb = new StringBuilder();
    sb.append(RunUntilSuccess.class.getSimpleName());
    sb.append("{processName='").append(processName).append('\'');
    sb.append(", interval=").append(interval);
    sb.append(", unit=").append(unit);
    sb.append(", maxAttempts=").append(maxAttempts);
    sb.append('}');
    return sb.toString();
}

private class Task implements Runnable {
    private final Callable<Boolean> task;

    public Task(Callable<Boolean> task) {
        this.task = task;
    }

    @Override
    public void run() {
        if (isAttemptsLimitReached(count.getAndIncrement())) {
            log.debug("Task execution finished unsuccessfully after " + count + " attempts.");
            executor.shutdown();
        } else {
            log.debug("Attempt #" + count);
            try {
                if (Boolean.TRUE.equals(task.call())) {
                    log.debug("Attempt #" + count + " was successful. Task execution finished.");
                    executor.shutdown();
                } else {
                    throw new FalseExecution();
                }

            } catch (Exception e) {
                log.error("Attempt #" + count + " failed due to:", e);
            }
        }
    }
}

public static class FalseExecution extends RuntimeException {

}

usage:

Callable<Boolean> connector = new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            // connect to ...
            return true;
        }
    };

    RunUntilSuccess initializer = new RunUntilSuccess("name", connector, reconnectTimeoutSeconds, TimeUnit.SECONDS);
            // initializer.await() after it for sync way

Is it a common task and how generic this code?
Thanks!


texts:
I receive a weather forecast for 5 days, but in 3 hours intervals.
This classes represent the weather forecast:

public class Forecast : ILocation
{
    [JsonIgnore()]
    public string City { get; set; }
    [JsonIgnore()]
    public string Country { get; set; }
    [JsonProperty("list")]
    public IList<WeatherTimePoint> TimePoints { get; set; }
}
public class WeatherTimePoint
{
    [JsonProperty("dt")]
    [JsonConverter(typeof(UnixTimeStampConverter))]
    public DateTime TimePoint { get; set; }
    [JsonProperty("main")]
    public ClimaticData ClimaticData { get; set; }
    [JsonProperty("weather")]
    public IList<Weather> Weather { get; set; }
    [JsonProperty("wind")]
    public Wind Wind { get; set; }
    [JsonIgnore()]
    public Units Units { get; set; }
}

This method prints the forecast:

 static void PrintForecast(Forecast forecast, int days)
    {
        days = days > 5 ? 5 : days;
        DateTime printDate = DateTime.Now.Date;
        for (int i = 0; i < days; i++)
        {
            printDate = printDate.AddDays(1);
            ChangeColor(ConsoleColor.Magenta);
            Console.WriteLine("== Day {0} ==", printDate.ToLongDateString());

            var timePointsDuringtDay = forecast.TimePoints.Where((weatherTimePoint) => weatherTimePoint.TimePoint.Date == printDate);
            for(int hour = 6; hour  <= 21 ; hour = hour + 3)
            {
                var weatherAtHour = timePointsDuringtDay.SingleOrDefault((weatherTimePoint) => weatherTimePoint.TimePoint.Hour == hour);
                if (weatherAtHour != null)
                {
                    ChangeColor(ConsoleColor.DarkCyan);
                    Console.Write("{0}/", hour);
                    ChangeColor(ConsoleColor.DarkGreen);
                    Console.Write("{0}({1})/",weatherAtHour.Weather[0].Condition, weatherAtHour.Weather[0].Description);
                    ChangeColor(ConsoleColor.Red);
                    Console.Write("{0}{1}",weatherAtHour.ClimaticData.Temperature, UnitsHelper.GetUnit(forecast.Units, UnitsHelper.WeatherField.Temperature));
                    Console.WriteLine();
                }
            }
            ChangeColor(ConsoleColor.White);
            Console.WriteLine("Average humidity:{0}%", timePointsDuringtDay.Average((weatherTimePoint) => weatherTimePoint.ClimaticData.Humidity));
            Console.WriteLine("Average pressure:{0} hPa", timePointsDuringtDay.Average((weatherTimePoint) => weatherTimePoint.ClimaticData.Pressure));
        }
    }

I thought it's quite unreadable. I am searching for any suggestion to improve the printing method. (ILocation is just a interface, that defines city and country properties. This is irrelevant for this method ;) )


texts:
I'm just started learning TDD with Rails and RSpec. This is my first test for controller. Just plain RESTful UserController that responds with JSON, so it has no new and edit methods. Please review it

require 'spec_helper'

describe UsersController do
  let(:users) { 4.times.map { create(:user) } }

  describe '#index' do
    before(:each) { get :index }

    it 'assigns all users to @users' do
      expect(assigns(:users)).to match_array users
    end

    it 'success' do
      expect(response).to be_success
    end
  end

  describe '#show' do
    context 'when requested user exists' do
      let(:user) { users[rand 4] }
      before(:each) { get :show, id: user.id }

      it 'success' do
        expect(response).to be_success
      end

      it 'assigns it to @user' do
        expect(assigns(:user)).to eq user
      end
    end

    context 'when requested user does not exists' do
      it 'throws ActiveRecord::RecordNotFound' do
        expect { get :show, id: -1 }.to raise_exception ActiveRecord::RecordNotFound
      end
    end
  end

  describe '#create' do
    before(:each) { post :create, ** user_attrs }

    context 'when valid' do
      let(:user_attrs) { attributes_for(:user) }

      it 'success' do
        expect(response).to be_success
      end

      it 'saves and assigns new user to @user' do
        user = assigns(:user)

        expect(user).to be_kind_of ActiveRecord::Base
        expect(user).to be_persisted
        expect(users).not_to include user
      end
    end

    context 'when invalid' do
      let(:user_attrs) { attributes_for(:invalid_user) }

      it 'fails' do
        expect(response).not_to be_success
      end

      it 'assigns user to @user' do
        expect(assigns(:user)).to be_kind_of ActiveRecord::Base
      end
    end
  end

  describe '#update' do
    let(:user) { create(:user) }
    before(:each) { patch :update, ** new_values, id: user.id }

    context 'when valid' do
      let(:new_values) { attributes_for(:user) }

      it 'success' do
        expect(response).to be_success
      end

      it 'saves and assigns user to @user' do
        expect(assigns(:user)).to eq user
      end

      it 'saves updates' do
        expect { user.reload }.to change { user.nick }.to(new_values[:nick])
      end
    end

    context 'when invalid' do
      let(:new_values) { attributes_for(:invalid_user) }

      it 'fails' do
        expect(response).not_to be_success
      end

      it 'assigns user to @user' do
        expect(assigns(:user)).to eq user
      end
    end
  end

  describe '#destroy' do
    context 'when requested user exists' do
      let(:user) { users[rand 4] }
      before(:each) { delete :destroy, id: user.id }

      it 'success' do
        expect(response).to be_success
      end

      it 'removes user form DB' do
        expect(User.all).not_to include user
        expect { user.reload }.to raise_exception ActiveRecord::RecordNotFound
      end
    end

    context 'when requested user does not exists' do
      it 'throws ActiveRecord::RecordNotFound' do
        expect { delete :destroy, id: -1 }.to raise_exception ActiveRecord::RecordNotFound
      end
    end
  end
end

Here is controller, model and factory if you need them


texts: Is My Function to Find Triplets in Scala running in O(N^2)

texts:
Given the classical problem to find triplets that sum to zero in an array. Is my Scala implementation correct and executed in O(N^2)? If yes, why? Can someone make a running time analysis.
What other ways could we solve this issue? With duplicated elements and not using the two pointer technique?
def tripletsFromArrayThatSumZero(input: Array[Int]): Array[Array[Int]] = {
    val target = 0 // the target is the number after the sum
    val sortedArray = input.sorted
    var resultsArrayOfTriplets = Array[Array[Int]]()

    for (i <- sortedArray.indices) {
      var j = i + 1
      var k = sortedArray.length - 1
      val twoSum = target - sortedArray(i)

      Breaks.breakable {
        while (j < sortedArray.length) {
          val sum = sortedArray(j) + sortedArray(k)
          if (k == j) Breaks.break()
          if (sum > twoSum) {
            k -= 1
          } else if (sum < twoSum) {
            j += 1
          } else if (sum == twoSum) {
            val triplet = Array(sortedArray(i), sortedArray(j), sortedArray(k) )
            resultsArrayOfTriplets = resultsArrayOfTriplets :+ triplet
            Breaks.break()
          }
        }
      }
    }
    resultsArrayOfTriplets
  }


texts:
I have this if statement

if (dt.Month > 3 && dt.Month < 11)
{
    if (hours == 23 || (hours >= 0 && hours <= 6))
    {
        session = String.Empty;
    }
    else if (hours == 7)
    {
        session = String.Empty;
    }
    else if (hours >= 8 && hours <= 11)
    {
        session = String.Empty;
    }
    else if (hours >= 12 && hours <= 15)
    {
        session = String.Empty;
    }
    else if (hours >= 16 && hours <= 20)
    {
        session = String.Empty;
    }
    else if (hours == 22)
    {
        session = String.Empty;
    }
    else
    {
        session = String.Empty;
    }
}
else
{
    if (hours == 22)
    {
        session = String.Empty;
    }
    else if (hours == 23 || (hours >= 0 && hours <= 6))
    {
        session = String.Empty;
    }
    else if (hours == 7)
    {
        session = String.Empty;
    }
    else if (hours >= 8 && hours <= 12)
    {
        session = String.Empty;
    }
    else if (hours >= 13 && hours <= 16)
    {
        session = String.Empty;
    }
    else if (hours >= 17 && hours <= 20)
    {
        session = String.Empty;
    }
    else if (hours == 21)
    {
        session = String.Empty;
    }
    else
    {
        session = String.Empty; // I dont think this one is needed
    }
}

As you can see it's pretty long and nasty.  Is there a way to shrink it?  I was going to use a switch but in C# you can't fall through case statements.


texts: Dynamically adding and removing HTML classes

texts:
I am trying to add an active class to my subnavigation using the waypoints jQuery. I am trying to avoid writing multiple functions to adhere to the DRY idea. The waypoints toggle the function based on their location in the markup. Any suggestions welcome.

Markup

<?php include 'partials/homepage/topHero.php'; ?>

<?php include 'partials/homepage/section1.php'; ?>

JavaScript/jQuery

Backwards way:

$('.homeNavItem1').waypoint(function(direction) {
  $('.homeAnchor1').addClass("subActive");
  $('.homeAnchor2').removeClass("subActive");
  $('.homeAnchor3').removeClass("subActive");
  $('.homeAnchor4').removeClass("subActive");
  $('.homeAnchor5').removeClass("subActive");
});

Efficient code attempt:

function waypointItem(x, y, i) {
  $('.homeNavItem' + x).waypoint(function(direction){
    $('.homeAnchor' + y).addClass("subActive");
    $('.homeAnchor' + i).removeClass("subActive");
  });
}

for (i = 2; i <= 6; i ++){
  waypointItem(1, 1, i);
  console.log(i);
}


texts:
I've just started coding and have written a program to calculate your tax to be paid. Is there anywhere where I can improve this?

while True:
    try:

      income = int(input("Please enter your taxable income: "))
  except ValueError:
      print("Sorry, I didn't understand that please enter taxable income as a number")

      continue
  else:

      break
  if income <= 18200:
      tax = 0

  elif income <= 37000:
      tax = (income - 18200) * 0.19

  elif income <= 90000:
      tax = (income-37000) * 0.235 + 3572

  elif income <= 180000:
      tax = (income - 90000) * 0.37 + 20797

  else:
      tax = (income - 180000) * 0.45 + 54097

  print("you owe", tax, "dollars in tax!" )


texts:
I would like to know if this fullscreen page with image and overlay is written clearly. I'm afraid that those two empty divs (topOverlay, and topImage) are not correct. Someone told me that I shouldn't use empty divs when there's another way to do it, but I couldn't find an alternative way in this case. Is there a different suitable tag for this instead of using div?

Everything works great otherwise. I just want it as clean as possible.

@import url(https://fonts.googleapis.com/css?family=Josefin+Slab);

body, html{
    margin: 0;
    height: 100%;
}

/* TOP - fullscreen image with overlay */
#top{
    width: 100%;
    height: 100%;
}
#topOverlay{
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(26, 188, 156, 0.98);
    z-index: 2;
}
#topImage{
    width: 100%;
    height: 100%;
    background: url("../images/workspace.jpg");
    background-size: cover;
    background-position: center center;
    z-index: 1;
}
#topTextWrapper{
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 3;
}
#topText{
    position: relative;
    top: 40%;
    transform: translateY(-50%);
    font-family: 'Josefin Slab', serif;
    text-transform: uppercase;
    text-align: center;
    color: white;
}
#topText h1{
    font-size: 3.2em;
    margin:0;
    padding:0;
}
#topTextDescription h2{
   font-size: 1.4em;
    margin:0;
    padding:0;
}

Site header

Site description


texts: A C++ function to read Code Points from an UTF-8 Stream

texts:
I've written a function that reads and returns one UTF-8 code point from an istream. I am wondering if the code is efficient or if there are some obvious problems with the implementation.
chr_t utf32::get_utf32_char(std::istream &in_stream) {
    int next;
    chr_t out = in_stream.get();
    if (out == -1 || out < 0x80) {
        return out;
    } else if ((out & 0xe0) == 0xc0) {
        out &= 0x1f;
        out <<= 6;
        next = in_stream.get();
        if (next == -1) goto invalid_seq;
        out |= next & 0x3F;
        return out;
    } else if ((out & 0xf0) == 0xe0) {
        out &= 0x0f;
        out <<= 12;
        next = in_stream.get();
        if (next == -1) goto invalid_seq;
        out |= (next & 0x3F) << 6;
        next = in_stream.get();
        if (next == -1) goto invalid_seq;
        out |= next & 0x3F;
        return out;
    } else if ((out & 0xf8) == 0xf0) {
        out &= 0x07;
        out <<= 18;
        next = in_stream.get();
        if (next == -1) goto invalid_seq;
        out |= (next & 0x3F) << 12;
        next = in_stream.get();
        if (next == -1) goto invalid_seq;
        out |= (next & 0x3F) << 6;
        next = in_stream.get();
        if (next == -1) goto invalid_seq;
        out |= next & 0x3F;
        return out;
    } else {
        throw std::runtime_error("invalid utf8 character");
    }
invalid_seq:
    throw std::runtime_error("unexpected end of utf8 sequence");
}


texts:
Write a factorial function that takes a positive integer, N as a parameter and prints the result of N! (N factorial).

  Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of 0 .

Here's my solution in C++:

#include <iostream>

int factorial( int n ) {

    if(n<=1)

        return 1 ;

    else{

        return n * factorial (n-1) ;

    }

}

int main() {

    int n;

    std::cin >> n;

    std::cout << factorial (n) ;

}

Is there a more efficient solution to this problem?


texts: Checking dates against a .properties file

texts:
I am writing a script that will check the set values against a .properties file and I am just wondering if there is any nicer way to write what I have here.

#!/bin/bash
# @summary Check Values
# --------------------------------------------------------------------------------------------------
function _RunChecks
{
SuccessfulDiffRun="true"
timestamp() { date +"%F"; }
TodaysDate=$(timestamp)
#Read savedState.properties file
while read LINE; do eval $LINE; done < savedState.properties
#Compare the Values
echo "HotPatch : "
if [ "$TodaysDate" = "$WD_MANAGEGOLD_DATETIMESTAMP" ]; then
    echo Dates Are A Match : TodaysDate:$TodaysDate = HotpatchRunDate:$WD_MANAGEGOLD_DATETIMESTAMP
    if [ "$SuccessfulDiffRun" = "$WD_MANAGEGOLD_SUCCESS" ]; then
        echo SuccessfulDiffRun : $WD_MANAGEGOLD_SUCCESS
        echo Hotpatch Run Was Successful
    else
        echo SuccessfulDiffRun : $WD_MANAGEGOLD_SUCCESS
        echo Exiting
        exit 0
    fi
else
    echo Dates Not A Match: TodaysDate:$TodaysDate = HotpatchRunDate:$WD_MANAGEGOLD_DATETIMESTAMP
    exit 0
fi
echo ""
echo "RC Prod  : "
if [ "$TodaysDate" = "$WD_MANAGERC_DATETIMESTAMP" ]; then
    echo Dates Are A Match : TodaysDate:$TodaysDate = RCRunDate:$WD_MANAGERC_DATETIMESTAMP
    if [ "$SuccessfulDiffRun" = "$WD_MANAGERC_SUCCESS" ]; then
        echo SuccessfulDiffRun : $WD_MANAGERC_SUCCESS
        echo RC Run Was Successful
    else
        echo SuccessfulDiffRun : $WD_MANAGERC_SUCCESS
        echo Exiting
        exit 0
    fi
else
    echo Dates Not A Match: TodaysDate:$TodaysDate = HotpatchRunDate:$WD_MANAGEGOLD_DATETIMESTAMP
    exit 0
fi
}
# --------------------------------------------------------------------------------------------------
# @summary Start
_RunChecks


texts: Reload pickled objects into dict - assigned to variable name from file name

texts:
I'm doing a bunch of work with echonest audio objects (as returned by the echonest API) in the Python CLI and rather than having to recreate them each time, they can be saved.

This bit of code reloads them all, referenced via a dict:

def get_saved(directory = 'audio/', extension = 'en'):
    return glob.glob(directory + '*.' + extension)

def file_queue(files):
    """
    Get list of files, add them to a queue and return the queue.
    """
    q = Queue()

    for f in files:
        q.put(f)

    return q

def lazarus(filename):
    """
    Get pickled (*.en) filename (path) and return echonest analysis object
    """
    with open(filename) as f:
        return pickle.load(f)

def lazarus_queue(q):
    container = {}
    while not q.empty():
        track = q.get()
        filename = track.replace('.mp3.analysis.en', '')
        filename = filename.replace('audio/', '')
        container[filename] = lazarus(track)
    return container

def resurrect():
    files = get_saved()
    q = file_queue(files)
    return lazarus_queue(q)

It's part of a little helper module:

>>> import mtu
>>> audio_objs = mtu.resurrect()
>>> audio_objs
{'claudia': <echonest.remix.audio.LocalAudioFile object at 0x10712e910>, 'GlitchBit_BJanoff': <echonest.remix.audio.LocalAudioFile object at 0x10712e690>, 'livingstonleo': <echonest.remix.audio.LocalAudioFile object at 0x10f52e0d0>, 'amandathorpe': <echonest.remix.audio.LocalAudioFile object at 0x10712ef90>, 'cucumbers': <echonest.remix.audio.LocalAudioFile object at 0x10712e990>}

(Note that pickle itself does not work on the echonest LocalAudioFiles, which have their own save() method.


texts:
I'm trying to show data in UITablleView after getting it from an HTTP request. I heard that the best and professional way to do it is configure the cell and do the call request in model class then send it to the view controller.

Here is what I tried to do, but I think it's not going well. I know this is a wrong way but I wanted to show you what I got based on someone.

UITable View Cell

@IBOutlet weak var status : UILabel!
@IBOutlet weak var date : UILabel!
@IBOutlet weak var model : UILabel!

 func ConfigCell (car : Car){
  let urlstr = "http://localhost:8000/api/newuser/check"
  let url = URL(string: urlstr)
  guard let token = UserDataSingleton.sharedDataContainer.token else { return    }
  let headers = ["Authorization":"Bearer \(token)"]
  var statusCode: Int = 0
request(url! ,  method: .get,  encoding: JSONEncoding.prettyPrinted ,      headers: headers )
    .responseJSON { response in
        if let value: AnyObject = response.result.value as AnyObject? {
            //Handle the results as JSON
            let json = JSON(value)
            for (key, subJson) in json["allcar"] {
                if let status = subJson["status"].string {
                    self.status.text = status
                    if let date = subJson["created_at"].string {
                          self.date.text = date

                        if let model = subJson["model"].string {
                            self.model.text = model
                            let Status = [
                                Car(model: model, status: status, date: date)]

Car model

  class Car {

private var _mode : String?
private var _status : String?
private var _date : String?

var model : String{
return _model!
   }
    var status : String {
    return _status!
     }
      var date : String {
       return _date!
           }

init(model : String , status :String,date : String) {
        self._status = status
        self._model = model
        self._date = date
   }

Controller

class testViewController: UIViewController, UITableViewDelegate , UITableViewDataSource {

    let data = [Car]()

   @IBOutlet weak var tableview: UITableView!

      override func viewDidLoad() {

   tableview.delegate = self
   tableview.dataSource = self
    print(data.count)
     }

       func numberOfSections(in tableView: UITableView) -> Int {
          return 1
   }
         func tableView(_ tableView: UITableView, numberOfRowsInSection section:  Int) -> Int {
       return data.count
    }
         func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

     let cell = tableView.dequeueReusableCell(withIdentifier: "CarCell",for: indexPath) as! CarC

      let entry = data[indexPath.row]
       cell.date.text = entry.date
      cell.model.text = entry.model
      cell.status.text = entry.status
      return cell


texts:
I've just started to practice coding in OOP and just wanted to ask if my code's pattern is correct.  I need your comments or suggestions so I can improve it.

sample_class.php:

<?php
$host = 'localhost';
$db = 'sample_db';
$user = 'sample_user';
$pass = 'sample_password';
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

Class MySearchClass {

    public function __construct(PDO $conn) {
        $this->pdo=$conn;
    }

    public function search_name($keyword){

        $query = "SELECT * FROM table WHERE name = '$keyword'";
        $result = $this->pdo->prepare($query);
        $result ->execute();

        return $result;
    }

    public function view_all(){
        $query = "SELECT * FROM table";
        $result = $this->pdo->prepare($query);
        $result ->execute();

        return $result;
    }
}

search_form.php:

<?php
include('sample_class.php');
$search= new MySeachClass($database_connection);

if (isset($_POST['submit'])){
    $keyword = $_POST['keyword'];
    $go_search = $search->search_name($keyword);

    $data = $go_search->fetchAll(PDO::FETCH_ASSOC);

    foreach($data as $row){
        echo $row['name'];
        echo other rows....
    }

}else{
    $view = $search->view_all();
    $data = $view->fetchAll(PDO::FETCH_ASSOC);

    foreach($data as $row){
        echo $row['name'];
        echo other rows....
    }
}

<form action="" method="POST">
<input type="text" name="keyword">
<input type="submit" name="search">
</form>


texts: Convert *.VCF contact file for cellphone import

texts:
My new mobile phone is capable of importing contact information from a renamed *.VCF file stored on an SD memory card (https://www.quora.com/How-do-I-sync-contacts-on-Nokia-130). Annoyingly, it does not work very well for contacts with multiple phone numbers or anything not tagged as TEL: or TEL;TYPE=CELL:.

The following script takes an *.vcf file, parses the stored contact information as needed - first name, last name and phone numbers - and outputs the information in a way that the phone imports it correctly. Therefore, each contact may only contain one number. For multiple numbers, a contact will be duplicated for each phone number. The resulting string is simply printet out.

#!/usr/bin/python

import re

class Contact(object):
    """
    Contains the contact infromation,
    including a list of phone numbers.

    Arguments:
        object {[type]} -- [description]
    """

    def __init__(self):
        self.FirstName = ""
        self.LastName = ""
        self.Phonenumbers = []

def extract_number(line):
    """
    Extracts the phone number from a vCard-file line,
    by removing everything but numbers and '+'

    Arguments:
        line {string} -- the line to extract the phone number from

    Returns:
        string -- the phone number
    """

    line = line[line.index(":")+1:].rstrip()
    line = re.sub('[^0-9+]', '', line)
    return line

def generate_vcard_contact_string(contact):
    """
    Generates the vCard string for this contact.
    Will generate a sperate vCard for each phone number of the contact.

    Arguments:
        contact {Contact} -- the contact to generate the vCard string from

    Returns:
        string -- the generated vCard string
    """

    base = f"BEGIN:VCARD\n"
    base += f"N:{contact.LastName};{contact.FirstName}\n"
    base += f"TEL:{{phone_number}}\n"  # use '{phone_number}' as a placeholder.
    # Will be replaced by actual number.
    base += f"END:VCARD\n"

    result = ""
    for number in contact.Phonenumbers:
        # Add the base string for this contact,
        # replace {phone_number} with actual number
        result += base.replace("{phone_number}", number)

    return result

contacts = []

with open(r'contacts.vcf') as f:
    current_contact = Contact()
    for line in f:
        # Some lines are build like "item1.TEL;...",
        # remove "item1.", "item2.", to ease parsing
        if line.startswith("item"):
            line = line[line.index(".")+1:]

        if "BEGIN:VCARD" in line:
            # Marks the start of a vCard,
            # create a blank contact to work with
            current_contact = Contact()

        elif line.startswith("N:"):
            # Line contains a name in the format N:LastName;FirstName;...;...;
            # Only LastName and FirstName will be used
            line = line.replace("N:", "")  # remove "N:" from line
            chunks = line.split(';')
            current_contact.LastName = chunks[0].strip()
            current_contact.FirstName = chunks[1].strip()

        elif line.startswith("TEL"):
            # Line contains a phone number
            # phone number type may be specified by "TYPE=...",
            # currently, TYPE will ne omitted
            # One contact may contain multiple phone numbers.
            number = extract_number(line)
            current_contact.Phonenumbers.append(number)

        elif "END:VCARD" in line:
            # Marks the end of a vCard,
            # append contact to list
            contacts.append(current_contact)

result = ""
for contact in contacts:
    # Generate a string containing a vCard for each of the contacts phone
    # numbers, append those string to create one big text containing everything
    result += generate_vcard_contact_string(contact)

print(result)


texts: MySQLi query and error handling for select, insert, and update

texts:
I am creating a new webpage with database connection. I want to make sure that I am handling the MySQLi query correctly for Search, Insert, and Update. I also want to make sure if any errors do pop up, that the function will catch the error for type of query I am running.

Is the if (!$Results) the correct way to test for Error/Failure on both Select and Insert/Update?

I am planning on having another section of functions for each table in my database for Select, Insert/Update.

function DB_Select($Query, $Results, $Rows) {
    DB_Test($DB_Connection);
    $Results = mysqli_query($DB_Connection, $Query);
    if (!$Results) {
        $Message = 'Failed Search: ' . mysqli_error();
        include $NAV_DB_Failure;
        exit();
    } else {
        $Rows = mysqli_affected_rows($Results);
    }
}

function DB_Insert_Update($Query, $Results, $Rows) {
    DB_Test($DB_Connection);
    $Results = mysqli_query($DB_Connection, $Query);
    if (!$Results) {
        $Message = 'Failed Insert/Update: ' . mysqli_error();
        include $NAV_DB_Failure;
        exit();
    } else {
        $Rows = mysqli_affected_rows($Results);
    }
}


texts: 4 different implementations of modulo with fully defined behavior

texts:
I've implemented the 3 variants of the modulo operation described on this Wikipedia page.
The goal is to have fully defined behavior for all inputs.
Code
Implementation with truncated division (result has the same sign as the dividend)
int32_t rem(int32_t x, int32_t y) {
    if (y == 0) exit(-1);
    if (y == -1) return 0;
    return x % y;
}

This one is the simplest since it's already how the % operator is implemented in C.
We have to take care of two edge cases though:

If y == 0 it's an invalid operation; exit(-1).
INT32_MIN % -1 is undefined behavior, so I've hard-coded the result for y == -1.

Implementation with floored division (result has the same sign as the divisor)
int32_t mod(int32_t x, int32_t y) {
    if (y == 0) exit(-1);
    if (y == -1) return 0;
    return x - y * (x / y - (x % y && (x ^ y) < 0));
}

This one is a bit trickier.
We still have to handle the two previous edge cases.
However, the modulo is computed differently: x - y * floor(x / y).
We can't use floor here because we're working with integers, so the formula looks like this:
x - y * (x / y - {1 if x isn't a multiple of y and the result of x / y is negative, 0 else})
x - y * (x / y - {1 if x % y and the result of x / y is negative, 0 else})
x - y * (x / y - {1 if x % y and (x or y, but not both, is negative), 0 else})
x - y * (x / y - {1 if x % y and (x ^ y) < 0, 0 else})
x - y * (x / y - (x % y && (x ^ y) < 0))
Implementation with Euclidean division (result is always positive)
Portable implementation
int32_t euc1(int32_t x, int32_t y) {
    if (y == 0) exit(-1);
    if (y == -1) return 0;
    if (y == INT32_MIN) return x >= 0 ? x : INT32_MAX + x + 1;
    y = abs(y);
    return x - y * (x / y - (x < 0 && x % y));
}

It's basically the same implementation as the previous one, except that we use the absolute value of y.
Also, (x ^ y) < 0 was simplified to x < 0 because y is always positive (we use the absolute value).
However abs(INT32_MIN) is undefined behavior (because abs(INT32_MIN) = INT32_MAX + 1 which is not representable) so we have to take care of this special case:

If x >= 0, we have x % (INT32_MAX + 1) = x because x is always inferior to INT32_MAX + 1.
If x < 0, we have x % (INT32_MAX + 1) = INT32_MAX + 1 + x, then we reorder operations to avoid overflow on signed integers which is undefined behavior: INT32_MAX + x + 1 (remember that x is negative).

GCC implementation
int32_t euc2(int32_t x, int32_t y) {
    if (y == 0) exit(-1);
    if (y == -1) return 0;
    if (y != INT32_MIN) y = abs(y);
    int32_t tmp = x / y - (x < 0 && x % y);
    __builtin_mul_overflow(y, tmp, &tmp);
    __builtin_sub_overflow(x, tmp, &tmp);
    return tmp;
}

This implementation is the same as the portable one, except for the handling of the y = INT32_MIN edge case: there is less conditional logic, making it potentially easier to optimize.
If y == INT32_MIN we don't compute the absolute value because it's undefined behavior, then we continue the execution as nothing happened. A multiplication and a subtraction were replaced by their built-in functions counterparts to avoid undefined behavior on overflow.
Because of black magic it works:

If x >= 0 we have x / INT32_MIN - (x < 0 && x % INT32_MIN) = 0, then INT32_MIN * 0 = 0, then x - 0 = x, so the result is x as expected.
If INT32_MIN < x < 0 we have x / INT32_MIN - (x < 0 && x % INT32_MIN) = -1, then INT32_MIN * -1 = INT32_MIN (built-in function defined behavior), then x - INT32_MIN = INT32_MAX + x + 1 (built-in function defined behavior), so the result is INT32_MAX + x + 1 as expected.
If x == INT32_MIN we have INT32_MIN / INT32_MIN - (INT32_MIN < 0 && INT32_MIN % INT32_MIN) = 1, then INT32_MIN * 1 = INT32_MIN, then INT32_MIN - INT32_MIN = 0, so the result is 0 as expected.

Questions
Is there an error somewhere, something that i missed? Like a set of inputs that don't give the right result.
If this code really undefined behavior free?
Can it be simplified?


texts: Fetching translated strings, keeping in the philosophy of Zend framework

texts:
I have been wondering this for a while. Take this example:

<?= Zend_Registry::get('translate')->_('translate me!');

I have my views cluttured with such code. My coworkers also complain often that its a lot to type juste to get translation and since it is repeated all over the place it gets tedious.

Some of them would love some global function that wraps everything in a short name like:

function t($text){
    return Zend_Registry::get('translate')->_($text);
}

But to me this is not good design and kinda defeats the idea of putting my translation object in the registry.

So I was wondering what others do to avoid having to write all this unnecessary code.

One solution would be to do in my controller:

$this->view->t = Zend_Registry::get('translate);

and then in my view just:

<?= $this->t->_('translate me!'); ?>

Another would be to create a view helper that does the job:

<?= this->translate('translate me!');?>

But it is more work and again adds a layer of logic on top of the already pretty robust and straigthforward Zend_Registry+ZendTranslate.


texts: Fixing starting times command by command and globally

texts:
I have a lot of Command objects. Each command has lots of Task objects. Tasks and commands are related. Each command wants to know which task belongs to it. Where each task wants to know which command it belongs to.
class Command:

    def __init__(self, date):
        self.deadline = date
        self.tasks = []

    def add_task(self, task:Task):
        """
        add a task to this command
        """
        self.tasks.append(task)
        return task

    def has_task(self, task):
        return task in self.tasks

    def remove_task(self, task):
        """
        Remove the task from this command.  After calling this,
        the task is orphaned and the reference to the task should be discarded.
        """
        self.tasks.remove(task)

class Task:
    def __init__(self, command:Command, duration:int):
        self.duration = duration
        self._command = command

    @property
    def command(self):
        """
        Getter for self._command with sanity checking that
        the task is not orphaned.
        """
        if not self._command.has_task(self):
            raise ValueError("orphaned task")
        return self._command

class Problem:
    def __init__(self, commands:Dict[str,Command], tasks:Dict[str,Task]):
        self._commands = commands
        self._tasks = tasks

In the Problem object I feel there is some redundancy in the data between Commands and Tasks.
I fix starting times in two ways:

Fix the start time of tasks command by command.
This is why is a commands attribute in Problem.
Merge them and then fix the starting times.
This is why there is tasks attribute in Problem.

I need both ways to fix starting times. However, fixing the starting time of a task always depends on the deadline of the command to which it belongs.
I'm unsure if my design is good. Sometimes I need to go through the tasks command by command. Sometimes I need to consider all the tasks for the command they belong.
Is there a design pattern I can use?