texts: MySQL queries with try-except error handling

texts:
I have this function that I have written, that gets passed a row of data from a mysql function. The function then uses a try-except block to get some a list of values depending on a value within the row of data.

It then loops through this data and completes another try-except block within the first try-except block's else command.

In fact, a lot of my code is styled this way. Some blocks go on for so long, or other blocks start once one has finished. Is this good practice of writing code? Or should I refactor my code and move the second try-except block into another separate function?

def select_uploaded_series(row):
        try:
            select_series_name = """SELECT track_ser_series
            FROM track_series
            WHERE track_ser_id = %s"""
            dbDets[1].execute(select_series_name,(row['track_id']),)
            series_names = dbDets[1].fetchall()
        except Exception as e:
            raise(e)
        else:

            names = []

            for series in series_names:
                try:
                    select_series_name_query = """SELECT title
                    FROM series
                    WHERE categoryId = %s"""
                    dbDets[1].execute(
                            select_series_name_query,
                            (series['track_ser_series']),)
                    track_series_names = dbDets[1].fetchall()
                except Exception as e:
                    raise(e)
                else:

                    for t_names in track_series_names:
                        names.append(t_names['title'])

            return(names)


texts: Making sure all elements are processed in a JQuery call

texts:
I have a piece code similar to below:

But I keep having this nagging feeling that there has to be an easier way!
Any ideas?

var synch = false
var indexArray = new Array();
var rowCount = theTable.find('tr').length;
$(".views").each(function(index) {
    indexArray.push( $(this).val()); // Not the real code but something to this effect
    if (rowCount <= (index+1)) synch = true;
});
while (!synch);
DO something with indexArray.....


texts: A reliable way to remove consecutive appearances of a substring

texts:
I'm attempting to write a piece of code that is supposed to remove consecutive appearances of a string (not a single character) in a StringBuilder.
It's extremely important that the method works well and does not remove or change anything that it shouldn't. Solid performance is a secondary requirement.

for example:

Input: "xxxxABCxxxxABCABCxxxxABABCxxABCABCABC"
Remove consecutive: "ABC"

Output: "xxxxABCxxxxABCxxxxABABCxxABC"

I've written a method that does this and testing shows that it works as expected, but it will be catastrophic if I use it and it results in changing the StringBuilder in an unexpected way - that's why I want another opinion on whether my code is really 'safe' in all cases:

public static void RemoveConsecutive(this StringBuilder sb, string value)
{
    if (sb == null)
        throw new ArgumentNullException("sb");
    if (value == null)
        throw new ArgumentNullException("value");
    if (value == string.Empty)
        throw new ArgumentException("value cannot be an empty string.", "value");

    bool justRemoved = false;
    for (int i = 0; i < sb.Length - value.Length; i++)
    {
        if (justRemoved || Util.ExistsAt(sb, i, value))
        {
            if (Util.ExistsAt(sb, i + value.Length, value))
            {
                sb.Remove(i, value.Length);
                justRemoved = true;
                i--;
            }
            else
            {
                justRemoved = false;
            }
        }
    }
}

// Checks if the provided string appears in the StringBuilder at the specified index
public static bool ExistsAt(StringBuilder sb, int startIndex, string str)
{
    if (startIndex < 0 || startIndex >= sb.Length)
        throw new ArgumentOutOfRangeException("startIndex", "startIndex must be a valid index in the provided StringBuilder.");
    if (startIndex + str.Length > sb.Length)
        return false;
    for (int i = 0; i < str.Length; i++)
    {
        if (str[i] != sb[i + startIndex])
            return false;
    }
    return true;
}

While this piece of code does something rather trivial, I just want another set of eyes to look at it and possibly find faults I could not. Again, any sort of unexpected behavior might be catastrophic.


texts: Implementing Convolutional Neural Network

texts:
Context
I was making a Convolutional Neural Network from scratch in Python. I completed making it .... It works fine ... The only thing is that it takes a lot of time as the size of the input grows.
Code
import numpy as np
import math

class ConvolutionalNeuralNetwork():
    def __init__(self, num_of_filters, kernel_shape, stride):
        self.num_of_filters = num_of_filters
        self.kernel_shape = kernel_shape
        self.stride = stride
        self.kernels = []

        # Initialize
        for i in range(self.num_of_filters):
            self.kernel = np.random.uniform(-1, 1, size=[3,3])
            self.kernels.append(self.kernel)
        self.kernels = np.array(self.kernels)

    def ElementWiseAddition(self, images):
        if np.array(images).shape[0] == 1:
            return images[0]

        resultant_image = images[0]
        for image in images[1:]:
            resultant_image = np.add(image, resultant_image)
            resultant_image = resultant_image.astype(float)
            resultant_image /= 2.0

        return resultant_image

    def GetOutput(self, x):
        filter_maps = []
        for filter_n in range(self.num_of_filters):
            kernel_n_filter_maps = []
            for image in x:
                filter_map = []
                for i in range(0, (image.shape[0]-3)+1, self.stride):
                    row = []
                    for j in range(0, (image.shape[1]-3)+1, self.stride):
                        piece = image[i:i+3, j:j+3]
                        value = np.sum(np.multiply(self.kernels[filter_n], piece))

                        # Apply Softmax Activation
                        if value < 0.0:
                            value = 0
                        row.append(value)
                    filter_map.append(row)
                kernel_n_filter_maps.append(filter_map)
            filter_maps.append(self.ElementWiseAddition(kernel_n_filter_maps))
        return np.array(filter_maps)

input = np.random.uniform(-1, 1, size=[512, 4, 4])

ConvolutionalNN = ConvolutionalNeuralNetwork(1028, [3,3], stride=1)
output = ConvolutionalNN.GetOutput(input)
print(output.shape)

How can I make this code consume less time and make it more efficient?


texts: Show byte representation of generic type

texts:
I am new to Rust. I would like to know any better way of doing this and if it can be done preferably with safe code.

use std::mem;
use std::mem::size_of;

fn show_byte <T> ( element: T) {

    let array: * mut u8 = unsafe{ mem::transmute(&element) };
    for i in (0.. size_of::<T>()) {
         let current = (array as usize + i) as *mut u8;
         print!("{:X}", unsafe { *current });
    }
}

fn main() {
   show_byte(-1i64);
}


texts: Is there a better way to get the index of a minimum?

texts:
Consider the following reproducible example:

# note that lh is a standard ts dataset that ships with R
lh
# fit an R model
ar.mle<-ar(lh,method="mle")

# now get the min AIC, this is the relevant line:
ar.mle$aic[ar.mle$aic==min(ar.mle$aic)]

This works fine and gives back the smallest AIC value and it's index, which is the suggested AR order. I feel I am repeating myself in this last line of code. Is there an easier way to obtain index and value?
I know I could use partial autocorrelations to determine the level, too. This is not a stats question, but an R indexing question.


texts: Reflection optimization for export CSV on large scale

texts:
So, I'm building export/import CSV helper. I have some performance issues in the code below. it takes me to parse CSV of 25,000 rows at 7 seconds.
If someone can help, it will be awesome!

public System.IO.Stream ParseContent<T>(IEnumerable<T> entities) where T : class
    {
        if (entities == null)
            throw new ArgumentException(nameof(entities), "List accepted is empty.");

        Type type = entities.First().GetType();

        PropertyInfo[] properties = type.GetProperties();

        string headers = GenerateTemplate(properties);

        //No headers accepted - cannot export the content
        if (string.IsNullOrEmpty(headers))
            return null;

        string contentToExport = $"{headers}{NewLineDelimiter}";

        foreach (T entity in entities)
        {
            if (entity == null)
                continue;

            string template = this.ExportLine(entity, properties);

            contentToExport += $"{template}{NewLineDelimiter}";
        }

        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(contentToExport);
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes);

        return memoryStream;
    }

    private string ExportLine<T>(T entity, PropertyInfo[] properties) where T : class
    {
        if (entity == null || properties == null)
            return string.Empty;

        string template = "";

        foreach (PropertyInfo property in properties)
        {
            string value = null;

            if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            {
                Type underlyingType = property.PropertyType.GetGenericArguments()[0];

                if (underlyingType.IsValueType || underlyingType == typeof(string))
                {
                    System.Collections.IEnumerable list = (System.Collections.IEnumerable)property.GetValue(entity);

                    value = string.Join(EnumerableValueDelimiter, list.Cast<string>());
                }
            }
            else if (property.PropertyType.IsClass && (!property.PropertyType.IsPrimitive && !property.PropertyType.IsEnum) && property.PropertyType != typeof(string))
            {
                //Object type. need to be serialized
                object propertyValue = property.GetValue(entity);

                if (propertyValue != null)
                    value = JsonConvert.SerializeObject(propertyValue);
                else
                    value = "null";
            }
            else
            {
                value = property.GetValue(entity)?.ToString();
            }

            if (string.IsNullOrEmpty(value))
                value = "";

            template += $"{value}{LineValuesDelimiter}";
        }

        //Removing the last delimiter at the row.
        if (template.Length > 0)
            template = template.Remove(template.Length - 1, 1);

        return template;
    }


texts:
hey guys how you all doing,
I built a spider that crawls through a house price website and stores houses address and transactions on it, through a bunch of functions, and I was wondering if anyone could help me refactor it, possibly pointing me in the direction of an OOP spider, so it would be easier for me to make an auto updating one, as this one just strips the website, not update it.

Here is code:

import threading

if __name__ == "__main__":

    areas = pd.read_csv('postcodes.csv')
    areas = areas['0']
    result_list = split_list(flattened=areas, chunk_size=50)
    threads = []
    outer_count = 1

    for i in result_list:
        print('Started thread No. ' + str(outer_count))
        t = threading.Thread(target=final_function, args=(i,))
        threads.append(t)
        t.start()
        outer_count += 1

above code gets links from csv file, and around twelve threads get to work using final_function()

def final_function(link_set):
    root = 'http://www.rightmove.co.uk'
    pages = []

    for link in link_set:

        try:
            links = forty_page_getter(link)
            pages.append(links)
            print('Done for:' + str(link))
        except:
            print('not possible for:' + str(link))
            pass
    flattened = [item for sublist in pages for item in sublist]
    print('flattening the sublists done')

    for page in flattened:

        try:
            page_stripper(link=(root+page))
        except:
            print('couldnt do it for')
            pass

Final function will, for each page, get the rest of the results pages and then go through them with the function page_stripper, which is where I take all of the information:

def page_stripper(link):

    '''this function strips all the information on houses and transactions,
    ready for entry into the database, now make a function for the database '''

    myopener = MyOpener()
    page = myopener.open(link)
    soup = BeautifulSoup(page, 'html.parser')
    houses = soup.find_all('div', {'class':'soldDetails'})

    for house in houses:

        try:
            address = house.a.text

        except:
            address = house.find('div',{'class': 'soldAddress'}).text

        postcode_list = address.split()[-2:]
        postcode = postcode_list[0] + ' ' + postcode_list[1]

        table = house.find('table').find_all('tr')

        bedrooms = table[0].find('td', {'class': 'noBed'}).text

        if not bedrooms:
            bedrooms = '0'
        else:
            bedrooms = bedrooms[0]

        house_key = save_house_to_db(address=address, postcode=postcode, bedrooms=bedrooms)

        for row in table[::-1]:
            price = row.find('td', {'class': 'soldPrice'}).text
            date  = row.find('td', {'class': 'soldDate'}).text

            save_transactions_to_db(id = house_key, date= date, sale_price= price)
        print('saved %s to DB' %str(address))

so this should be it for the explanation. I am sure you guys have much better and more efficient ways of doing this, and I would love to know them.Any refactoring advice, especially for someone who wants to extend this to be auto updating?
Thank you for your help


texts:
Encryption is all the rage nowadays but let us not forget what it was like back before the advent of internet. I have written a small, simple cipher that takes texts, gets their char value, and adds or subtracts a certian given number from them aka "shifting" the keys.

If the receiving end has the direction and then number of the shift, he or she can easily decrypt the code. It's not a real cipher, and nothing important at all. Just something I've written as practice:

 """ This is a simple alphabetical shift encypter. Enter -1 or 1 for the direction, your desired shift and laslty, the
    text to cipher.
    Written by Sami Dena (aurlit@riseup.net)
"""

def cipher(direction, shift, text):
    text_split = list(text)

    text_split = [ord(i) for i in text_split]

    text_shift = [str(i + (direction * shift)) for i in text_split]

    return str.join(',', text_shift)

def decipher(direction, shift, text):
    text_split = str.split(text, ',')

    text_shift = [chr(int(i) - (direction * shift)) for i in text_split]

    return str.join('', text_shift)

if __name__ == '__main__':
    string = "The encryption step performed by a Caesar cipher is often" \
             " incorporated as part of more complex schemes, such as the Vigenère cipher" \
             ", and still has modern application in the ROT13 system. As with all single-alphabet" \
             " substitution ciphers, the Caesar cipher is easily broken and in modern practice offers " \
             "essentially no communication security."

    encrypted_string = cipher(-1, 4, string)
    print(encrypted_string)
    print(decipher(-1, 4, encrypted_string))

Thanks a lot for your reviews.


texts: NHibernate select with Query Over optimization for user roles base case

texts:
I have a complicated select procedure that I solved with a 5 query select, so I am posting it here to get suggestions on how I can shorten it up a bit.  I am hoping that someone can help me make it a single query select.
I'm using nhibernate query over here.

I have 7 tables which are

t_user
t_category
t_event
t_announcement
t_event_follower
t_event_register
t_event_subcribe

I will represent them in the classes below:

class User {
  int id;
  string username;
  IList<Registration> registrations;
  IList<Category> subscribes;
  IList<Event> follows;
}

class Category {
  int id;
  string description;
  IList<User> subscribers;
}

class Event{
  int id;
  string title;
  Category category;
  IList<Registration> registrations;
  IList<User> followers;
  IList<Announcement> announcements;
}

class Announcement {
  int id;
  string title;
  Event event;
  bool isForFollower;
  bool isForRegister;
  bool isForSubscriber;
}

class Registration {
  int id;
  Event event;
  User user;
  string additionalInfo;
  RegistrationStatus status;
}

enum UserRole {
  PUBLIC,
  FOLLOWER,
  SUBSCRIBER,
  REGISTERED
}

The goal is to show all announcements in 1 event based on user roles on that event.  What I had done first is populate user role in list with the code below:

User requester = _userRepo.SearchBy(username); // 1 query for user detail

// 3 lazy load objects make nhibernate to load the object from db, i assume it takes 3 query select if objects haven't load in session
bool isFollower = requester.Follows.Any(eventz => eventz.Id == eventId);
bool isSubscriber = requester.Subscribes.Any(category => category.Events.Any(eventz => eventz.Id == eventId));
bool isRegistered = requester.Registrations.Any(registration => registration.Event.Id == eventId);
var userRoleList= new List<UserRole>();

if (isFollower) userRoleList.Add(UserRole.FOLLOWER);
if (isSubscriber) userRoleList.Add(UserRole.SUBSCRIBER);
if (isRegistered) userRoleList.Add(UserRole.REGISTERED);

last with code in repository layer below i create dynamic disjunction for query over :

Disjunction filterRestriction = Restrictions.Disjunction();
// this condition to select announcement which is for public not specific
filterRestriction.Add(Restrictions.Where<Announcement>(a => a.IsForFollower == false
                                                            && a.IsForSubscriber == false
                                                            && a.IsForRegistered == false));

foreach (UserRole role in userRoleList)
{
    switch (role)
    {
        case UserRole.FOLLOWER:
            filterRestriction.Add(Restrictions.Where<Announcement>(a => a.IsForFollower));
            break;
        case UserRole.SUBSCRIBER:
            filterRestriction.Add(Restrictions.Where<Announcement>(a => a.IsForSubscriber));
            break;
        case UserRole.REGISTERED:
            filterRestriction.Add(Restrictions.Where<Announcement>(a => a.IsForRegistered));
            break;
    }
}
//this is the last query transaction, so total 5 times select from db CMIIW,
return _session.QueryOver<Announcement>()
               .Where(filterRestriction)
               .And(a => a.Event.Id == id)
               .List();

In the above code, the query result will show public announcement plus specific announcement based on role that user have in related event.

I admit this is the simplest solution I could think to solve the case.  Could someone give a suggestion or rework this just by 1 simple operation with query over or just remake it with better query?


texts:
I have this code for finding MST for undirected weighted graph, currently works for graphs with maximum 10 vertices. How can I update the code to scale for larger graphs?

# Python program for Kruskal's algorithm to find Minimum Spanning Tree
# of a given connected, undirected and weighted graph

from collections import defaultdict

#Class to represent a graph
class Graph:

    def __init__(self,vertices):
        self.V= vertices #No. of vertices
        self.graph = [] # default dictionary to store graph

    # function to add an edge to graph
    def addEdge(self,u,v,w):
        self.graph.append([u,v,w])

    # A utility function to find set of an element i
    # (uses path compression technique)
    def find(self, parent, i):
        if parent[i] == i:
            return i
        return self.find(parent, parent[i])

    # A function that does union of two sets of x and y
    # (uses union by rank)
    def union(self, parent, rank, x, y):
        xroot = self.find(parent, x)
        yroot = self.find(parent, y)

        # Attach smaller rank tree under root of high rank tree
        # (Union by Rank)
        if rank[xroot] < rank[yroot]:
            parent[xroot] = yroot
        elif rank[xroot] > rank[yroot]:
            parent[yroot] = xroot
        #If ranks are same, then make one as root and increment
        # its rank by one
        else :
            parent[yroot] = xroot
            rank[xroot] += 1

    # The main function to construct MST using Kruskal's algorithm
    def KruskalMST(self):

        result =[] #This will store the resultant MST

        i = 0 # An index variable, used for sorted edges
        e = 0 # An index variable, used for result[]

        #Step 1:  Sort all the edges in non-decreasing order of their
        # weight.  If we are not allowed to change the given graph, we
        # can create a copy of graph
        self.graph =  sorted(self.graph,key=lambda item: item[2])
        #print self.graph

        parent = [] ; rank = []

        # Create V subsets with single elements
        for node in range(self.V):
            parent.append(node)
            rank.append(0)

        # Number of edges to be taken is equal to V-1
        while e < self.V -1 :

            # Step 2: Pick the smallest edge and increment the index
            # for next iteration
            u,v,w =  self.graph[i]
            i = i + 1
            x = self.find(parent, u)
            y = self.find(parent ,v)

            # If including this edge does't cause cycle, include it
            # in result and increment the index of result for next edge
            if x != y:
                e = e + 1
                result.append([u,v,w])
                self.union(parent, rank, x, y)
            # Else discard the edge

        # print the contents of result[] to display the built MST
        print "Following are the edges in the constructed MST"
        for u,v,weight  in result:
            #print str(u) + " -- " + str(v) + " == " + str(weight)
            print ("%d -- %d == %d" % (u,v,weight))
 g = Graph(14)
 g.addEdge(0, 1, 7)
 g.addEdge(0, 3, 3)
 g.addEdge(1, 2, 3)
 g.addEdge(1, 4, 2)
 g.addEdge(2, 5, 2)
 g.addEdge(3, 4, 3)
 g.addEdge(3, 6, 2)
 g.addEdge(4, 5, 5)
 g.addEdge(4, 7, 7)
 g.addEdge(5, 8, 3)
 g.addEdge(6, 7, 3)
 g.addEdge(6, 9, 1)
 g.addEdge(7, 8, 7)
 g.addEdge(7, 10, 3)
 g.addEdge(9, 12, 4)
 g.addEdge(9, 10, 1)
 g.addEdge(10, 11, 6)
 g.addEdge(10, 13, 7)
 g.addEdge(11, 12, 6)
 g.addEdge(11, 14, 2)
 g.addEdge(12, 13, 4)
 g.addEdge(13, 14, 5)

 g.KruskalMST()


texts:
I want to implement in my code a cache mechanism with a fixed duration. For example an iframe will be cached for one hour, or a script file will be cached for 24 hours.

This is how I implemented it, with a rounded timestamp (simplified code assuming that the url doesn't have any query or hash part):

var duration=86400000; // example for 1 day = 86400000 milliseconds
url=url+"?_ts="+ getTimeStamp(duration);

function getTimeStamp(roundTime) {
  var timeStamp=new Date().getTime();
  if (roundTime) {timeStamp=Math.floor(timeStamp/roundTime);}
  return timeStamp;
}

My questions:

Are there any traps to watch for, or is the above code going to work just fine in all situations (dynamic script tag, iframe, ajax)?
Is there a better way to do it, for example with a JavaScript library?


texts: Moving from Solr (Sunspot) to ElasticSearch (Tire), Review needed

texts:
I would like a review regarding the following code in which I index and search the City model. Currently both solr (with sunspot gem) and elaticsearch (with the tire gem) are show. I am migrating from solr to ES and want to make sure I am not making any major mistakes.

I am new to ES.

class City < ActiveRecord::Base
  include Tire::Model::Search
  include Tire::Model::Callbacks

  class << self
    def search(params)
      tire.search(load: false, page: params[:page], per_page: (params[:per_page] || 50)) do
        query do
          boolean do
            should { string 'has_seo_doctors:true' }
          end
          term :state_id, params[:state_id]
        end
        sort { by :name_sortable, "asc" }
      end
    end

    def search_total
      Tire.search('cities', search_type: 'count') {}.results.total
    end
  end

  # elasticsearch
  mapping do
    indexes :name, type: 'multi_field',  stored: 'yes', fields: {
      name:          { type: 'string', analyzer: 'snowball' },
      name_sortable: { type: 'string', index: :not_analyzed }
    }
    indexes :id,              type: 'integer'
    indexes :seo_name,        type: 'string',  stored: 'yes'
    indexes :state_id,        type: 'integer', stored: 'yes', as: 'state.try(:id)'
    indexes :has_seo_doctors, type: 'boolean', stored: 'yes', as: 'has_seo_doctors?'
    indexes :state_seo_name,  type: 'string',  stored: 'yes', as: 'state.try(:seo_name)'
  end

  # solr (sunspot) indexing
  searchable(auto_index: true, auto_remove: true, include: :state) do
    boolean :has_seo_doctors, stored: true do
      has_seo_doctors?
    end
    string :id
    string :name, stored: true
    string :seo_name, stored: true
    string :state_id, stored: true do
      state.try(:id)
    end
    string :state_seo_name, stored: true do
      state.try(:seo_name)
    end
  end
  handle_asynchronously :solr_index unless Rails.env.test?

end

Performing a search is as easy as:

City.search({ state_id: State.first.id, page: 1 })

We have an admin dashboard which relies on the total indexes number of cities, so I have created the following convenience method:

City.search_total

A few comments:

I don't exactly understand when to use to_indexed_json
If 'as:' is the proper way of handling custom indexed methods

Thank you


texts: Deaf grandma doesn't allow me to leave until I say bye three times

texts:
So, I'm working through Chris Pine's "learn to program" and I have been banging my head against the wall regarding the "deaf grandma" lesson.

I think I got it.

I'm looking for advice regarding indentations, and/or structuring of the code to make it easier to read, for myself and others.

Here's the premise:

  Write a Deaf Grandma program.
  Whatever you say to grandma (whatever you type in), she should respond with HUH?! SPEAK UP, SONNY!, unless you shout it (type in all capitals). If you shout, she can hear you (or at least she thinks so) and yells back, NO, NOT SINCE 1938! To make your program really believable, have grandma shout a different year each time; maybe any year at random between 1930 and 1950. (This part is optional, and would be much easier if you read the section on Ruby's random number generator at the end of the methods chapter.) You can't stop talking to grandma until you shout BYE.

  Hint: Don't forget about chomp! 'BYE'with an Enter is not the same as 'BYE' without one!

  Hint 2: Try to think about what parts of your program should happen over and over again. All of those should be in your while loop.

  Extend your Deaf Grandma program: What if grandma doesn't want you to leave? When you shout BYE, she could pretend not to hear you. Change your previous program so that you have to shout BYE three times in a row. Make sure to test your program: if you shout BYE three times, but not in a row, you should still be talking to grandma.

Here's my solution:

puts "say hi to grandma"

bye = 0

while bye < 3 do
  input = gets.chomp

  if input == "BYE"
  bye = bye + 1
  puts "HEH?!"
  else
    if input == input.upcase
    bye = 0
    puts "NO, NOT SINCE " + rand(1930..1950).to_s + "!"
    else
    puts "HUH?! SPEAK UP SONNY!"
    bye = 0
    end
  end
end

puts "EH?! OH, BYE DEAR!"


texts:
The below may not look like much, but the ability to call methods in other classes, offloading all the work onto other classes from MainClass, and returning a variable to be passed to the next method is a rather large leap for me at least.

using System;

namespace CSharpTutoriel
{
    class Work
    {
        public static string TellMeWhatToSay(out string passTheQuote)
        {
            string whatIsWritten;
            Console.WriteLine("Tell Me What To Say");
            whatIsWritten = Console.ReadLine();
            passTheQuote = whatIsWritten;
            return passTheQuote;
        }
        public static void HelloWorld(string itWillBeSpoken)
        {
            Console.WriteLine(itWillBeSpoken);
        }
        public static void PressToContinue()
        {
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }

    class MainClass
    {

        public static void Main(string[] args)
        {
            string whatToSay;

            Work.TellMeWhatToSay(out whatToSay);
            Work.HelloWorld(whatToSay);
            Work.PressToContinue();
        }
    }
}


texts:
I am using this as a learning exercise primarily and want to ensure my code is optimal.  The main thing is that it is reliable and I am made aware of any flaws.

Could it be made more efficient or more readable?  How about style?

I thought about returning a char*, but then the caller would have to think to deallocate the returned string.  I saw this as a problem, so I left to caller to allocate and deallocate.  Is that the right decision?  Any comments?

/* Generate hex string from integer.  Odd number of characters must be preceded
   with zero character
   Eg. 9 becomes "09", 10 becomes "0A" and 16 becomes "10"
*/

#include <stdio.h>

unsigned int num_hex_digits(unsigned int n) {
    int ret = 0;
    while(n) {
        n >>= 4;
        ++ret;
    }
    return ret;
}

void make_hex_string_easy(unsigned int invokeid, char** xref)
{
    int pad = 0;
    int len = num_hex_digits(invokeid);
    /* if odd number, add 1 - zero pad number */
    if(len % 2 != 0)
        pad = 1;

    sprintf(*xref, "%s%X", pad ? "0" : "", invokeid);
}

void make_hex_string_learning(unsigned int invokeid, char** xref)
{
    char* p = *xref;
    int pad = 0;
    int len = num_hex_digits(invokeid);
    /* if odd number, add 1 - zero pad number */
    if(len % 2 != 0)
        pad = 1;

    /* move to end of number string */
    p+= len + pad - 1;

    while(invokeid) {
        int tmp = invokeid & 0xF;
        if(tmp < 10)
            *p = tmp + '0';
        else
            *p = tmp + 'A' - 10;

        invokeid >>= 4;

        p--;
    }

    if(pad) {
        *p = '0';
    }
}

int main() {
    unsigned int testdata[] = {~0, 1, 255, 256, 0xFFFE, 0xFFFF, 0x10000, 0xABC };
    int sz = sizeof(testdata) / sizeof(int);
    int i;

    char* test = (char*) calloc (20, 1);
    printf("Using sprintf method\n");
    for(i = 0; i < sz; ++i) {
        make_hex_string_easy(testdata[i], &test);
        printf("hex string of %#10x = \t%10s\n", testdata[i], test);
        memset(test, 0, 20);
    }

    printf("\nUsing homegrown method\n");
    for(i = 0; i < sz; ++i) {
        make_hex_string_learning(testdata[i], &test);
        printf("hex string of %#10x = \t%10s\n", testdata[i], test);
        memset(test, 0, 20);
    }
    free(test);

    return 0;
}

Output on my PC:

Using sprintf method
hex string of 0xffffffff =        FFFFFFFF
hex string of        0x1 =              01
hex string of       0xff =              FF
hex string of      0x100 =            0100
hex string of     0xfffe =            FFFE
hex string of     0xffff =            FFFF
hex string of    0x10000 =          010000
hex string of      0xabc =            0ABC

Using homegrown method
hex string of 0xffffffff =        FFFFFFFF
hex string of        0x1 =              01
hex string of       0xff =              FF
hex string of      0x100 =            0100
hex string of     0xfffe =            FFFE
hex string of     0xffff =            FFFF
hex string of    0x10000 =          010000
hex string of      0xabc =            0ABC


texts: Solving an unwieldy inheritance framework function

texts:
I have a simple inheritance framework:

class BaseValidator
{
    protected virtual void Validate()
    {
        // Base validator code .....
    }
}
class PhoneValidator:BaseValidator
{
    public override void Validate()
    {
        base.Validate();
        // custom validation logic...
    }
}
class EmailValidator:BaseValidator
{
    public override void Validate()
    {
        base.Validate();
        // custom validation logic...
    }
}

The problem is in //custom validation logic. The more custom validation logic code that is written , the more unwieldy the
Validate() function becomes. I can organize custom validation logic into separate functions, but that would be another mess.

public override void Validate()
{
    base.Validate();
    CustomValidation1();
    CustomValidation2();
    CustomValidation3();
    ...
}

What are other patterns\practices that I can use to manage the Validate() function?  Sometimes I feel this is a the problem with inheritance, but suggestions are welcome in any direction.


texts: A library for interacting with JPL Horizons

texts:
I'm writing a tiny Python library that fetches data from Horizons, JPL's solar system data and ephemeris computation service. An overview of their batch CGI is here. While the script is simple, I would like to make it as clear and standardized as possible.
The idea is to initialize the HorizonsRequest class with a location for the observer (center), target (COMMAND), datetime, and the the data you want (quantities). The response can be retrieved as either a complete list of the lines sent back or as a dictionary of the requested values.
Example request
A request for the angle of Jupiter (599), its distance, and light travel time in relation to Earth (399) at the current time. Horizons users can find these numeric ids using the web-interface.
request = horizons.HorizonsRequest("399", "599", datetime.utcnow(), "2,20,21")
request.send()

dictionary = request.get_dictionary()
for key in dictionary:
    print(key, ":", dictionary[key])

Library
import sys
import urllib.request
import math
from datetime import datetime, timedelta

def get_julian_datetime(date):
    # Ensure correct format
    if not isinstance(date, datetime):
        raise TypeError('Invalid type for parameter "date" - expecting datetime')
    elif date.year < 1801 or date.year > 2099:
        raise ValueError('Datetime must be between year 1801 and 2099')

    # Perform the calculation
    julian_datetime = 367 * date.year - int((7 * (date.year + int((date.month + 9)
    / 12.0))) / 4.0) + int((275 * date.month) / 9.0) + date.day + 1721013.5
    + (date.hour + date.minute / 60.0 + date.second / math.pow(60,2)) / 24.0
    - 0.5 * math.copysign(1, 100 * date.year + date.month - 190002.5) + 0.5

    return julian_datetime

class HorizonsRequest:
    def __init__(self, center, target, datetime, quantities):
        self.keys = {
            "CENTER": center,
            "COMMAND": target,
            "QUANTITIES": quantities,
            "TLIST": str(get_julian_datetime(datetime)),
            "MAKE_EPHEM": "YES",
            "OBJ_DATA": "NO",
            "TABLE_TYPE": "OBSERVER",
            "CAL_FORMAT": "BOTH",
            "ANG_FORMAT": "DEG",
            "CSV_FORMAT": "YES"
        }
        self.response = []
        self.dictionary = {}

    def set_key(self, key, value):
        self.keys[key] = str(value)

    def delete_key(self, key):
        self.keys.pop(key, None)

    def send(self):
        # create request
        request = "https://ssd.jpl.nasa.gov/horizons_batch.cgi?batch=1"
        for key in self.keys:
            request += "&" + key + "='" + self.keys[key] + "'"

        # send request
        file = urllib.request.urlopen(request)
        for line in file:
            self.response.append(line.decode('utf-8').replace('\n', ''))

    def get_dictionary(self):
        keys = []
        values = []

        # locate data position in response
        i = 0
        while i < len(self.response):
            if "$$SOE" in self.response[i]:
                keys = self.response[i - 2].split(",")
                values = self.response[i + 1].split(",")
            i += 1

        # create dictionary
        i = 0
        while i < len(keys):
            self.dictionary[keys[i].strip()] = values[i].strip()
            i += 1

        return self.dictionary

    def get_response(self):
        return self.response

Any feedback would be greatly appreciated.


texts:
I just started learning Erlang. Here is my crack at the Seive, based on (https://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf):

-module(seive).
-export([seive/1]).

seive(N) ->
    L = lists:seq(1,N),
    {Megass, Ss, Micros} = erlang:timestamp(),
    S = doseive(L, 2),
    {Megase, Se, Microe} = erlang:timestamp(),
    {Megase-Megass, Se-Ss, Microe-Micros, S}.

doseive(L, Index) ->
    Isq = Index*Index-1,
    if Isq > length(L) -> [X || X <- L, X /= -1]; %done crossing out
    true ->
        case  lists:nth(Index, L) == -1 of
        true -> doseive(L, Index + 1); %nothing to cross this pass
        false ->
            {L1, L2} = lists:split(Isq, L),
             L3 = lists:map(fun(X) -> if X == -1 orelse (X rem Index == 0 andalso X /= Index) -> -1; true  -> X  end end , L2),
             doseive(lists:append(L1, L3), Index + 1)
    end end.

This takes 52 seconds to generate the first two million primes:

6> seive:seive(2000000).
{0,19,53218,
 [1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,
  73,79,83,89|...]}

I was expecting it to be faster based on other solutions on the web.

Sticking to serial (I have not even attempted a parallel solution yet, so I'd like to try that on my own first), what are the problems with my code? I looked for "in place" versions of map so that I don't continuously copy lists into new lists, which I think is what is killing me, but the essence of functional is this immutable-ness.

If I was in an imperative language, I would iterate over a hashmap, but there is no "map-update" function for hashmaps. I guess I could try accessing values in a loop, but this solution better lends itself to imperative languages. Would be nice to have something like

mapupdate(F, V)
%updates all values for keys to V where F(key) is true

I also tried a solution with filter:

doseivev2(L, Index) ->
if Index > length(L) -> L;
true ->
    case Index > length(L) of
        true -> L;
        false ->
            %if you do filter, you dont know what index p^2 is anymore...
            doseivev2(lists:filter(fun(X) -> X =< Index orelse X rem Index /= 0 end, L), Index + 1)
end end.

but it is WAAAAY slower. Does not even finish for 1M.


texts: Populate list with Excel range and keep formatting

texts:
I have written a Python programme that takes data from Excel sheets and adds this data to new .DAT files.
I use win32com.client because the Excel sheets will already be opened and other modules need to open a file before they can process it.

As the win32com.client outputs the range as a Component Object Model, it changes the content in some minor but destructive ways. Numbers, such as 2, are outputted as 2.0. Moreover, empty cells are outputted as None.
For this reason I cannot immediately put the cells' values into a file, and instead I use a loop to fill a list during which I edit the data.

This loop, however, is relatively very slow. I'd like a faster method, but I am unsure how to achieve this.

from win32com.client import GetObject

def convertdata(r, l):
    newr = []
    for c in r:
        # Some codes start with leading zeroes and need to be left as-is
        # The try...except clause would convert this code into integers, stripping
        # the leading zeroes. str(c) == '0.0' makes sure single 0 values do get
        # processed.
        if str(c) == '0.0' or not str(c)[:1] == '0':
            try:
                float(str(c))
                newr.append(str(int(c)))
            except ValueError:
                if str(c) == 'None':
                    newr.append('')
                else:
                    newr.append(str(c))
        else:
            newr.append(str(c))
        if c.Column == l and not c.Row - 1 == r.Rows.Count:
            newr.append('\n')
        else:
            newr.append('\t')
    return newr

# ... Code omitted
exl = GetObject(None, "Excel.Application")
exl_wbs = exl.Workbooks
sht = exlwbs[0].Worksheets(2)
rng = sht.Range(sht.Cells(2, 1), sht.Cells(lrow, lcol))
newrng = convertdata(rng, lcol)
dataf = ''.join(newrng)

with open(fpath, "w") as newfile:
    newfile.write(dataf)

lrow and lcol are integers. fpath is a string to the new file. sht is a Worksheet object.

Input example

Output example (not the same data as the input, but you get the gist of it)

I   08.5070     Plate assembly  Plate assembly  5   5070    VIRTUAL 1   1   1               0
I   0070_01.01      Plate D10 (SA)  Plate D10 (SA)  08.58070    101 VIRTUAL 1   1   1               0
I   001170      Support Support 6   1170    VIRTUAL 1   1   1               0
I   0010.1170_01.01     conveyor (SA)   conveyor (SA)   0090.1170   101 VIRTUAL


texts: Using flexbox to replace fixed and absolute positioning

texts:
I'm using flexbox to create a simple header, hero image with caption and footer.

As you can see from my snippet, the header is fixed and the hero image scrolls underneath.

Is there a way to achieve my layout without fixed or absolute positioning? I'm relatively new to flexbox and and haven't come across a solution.

For the image, I could use the background property, but I'd like to maintain what I have to easily implement img srcset and an alt tag.

body {
  margin: 0;
}

/* Flexbox */
.main-navigation,
.main-navigation ul,
.hero {
 display: flex;
 flex-flow: row wrap;
}

.main-navigation {
 justify-content: space-between;
 align-items: center;
}

/* Site header */
.site-header {
  position: fixed;
 top: 0;
 z-index: 9999; /* Always on top */
 width: 100%; /* Must have width for flex */
  padding: 24px;
  color: #fff;
  background-color: #021928;
}

/* Hero */
.hero {
 position: relative; /* For image */
 height: 100vh; /* Fill viewport */
  justify-content: center;
 align-items: center;
}

.hero img {
  position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 z-index: -1; /* Send image to back */
 height: 100vh;
 object-fit: cover;
 object-position: bottom;
}

/* Cosmetic */
ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
 margin-right: 12px;
}

li:last-child {
  margin: 0;
}

a,
a:visited,
a:focus,
a:hover {
  color: #fff;
}

p {
  padding: 24px;
}

.caption {
  padding: 0;
}

h1 {
  margin: 0 0 12px;
}

.logo {
  margin: 0;
}

.caption {
  max-width: 600px;
 text-align: center;
  color: #fff;
}

.site-footer {
  padding: 24px;
  background-color: #021928;
  color: #fff;
}

Logo

Item One

Item Two

Item Three

Title goes here

And a caption

Main page content

  Some information about stuff


texts: Given some text and a word list, print the 7 most common correctly spelled words

texts:
I've got a basic python function that I've been tasked with finishing in a class.

It's already fulfilling all the requirements for an A as it's an introductory course to Python, but I'd like to get some advice on it still as it's taking quite some time to execute.

I've got a few years of experience with general programming, but I'm still quite new to Python. As such any sort of advice on what might be taking up time would be appreciated.

As it stands at the moment, it takes about .5 seconds to run through the code and print all the data.

A bit of detail to the program:

It reads three files:

A part of Alice in the Wonderland's first chapter (alice-ch1.txt)
A list of common words (common-words.txt)
And a list of correctly spelt words.

Finally it prints the top 7 words that have passed through the filters.

def analyse():
    #import listdir
    from os import listdir
    #import counter
    from collections import Counter
    files = "*************************************\n"
    for file in listdir():
        if file.endswith('.txt'):
            files = files + file + "\n"
    choice = input("These are the files: \n" + files + "*************************************\nWhat file would you like to analyse?\n")

    if choice.strip() == "":
        choice = "alice-ch1.txt"
    elif choice.endswith(".txt"):
        print(choice)
    else:
        choice = choice + ".txt"
    print(choice)

    with open(choice) as readFile, open('common-words.txt') as common, open('words.txt') as correct:
        correct_words = correct.readlines()
        common_words = common.readlines()
        common_words = list(map(lambda s: s.strip(), common_words))
        correct_words = list(map(lambda s: s.strip(), correct_words))

        words = [word for line in readFile for word in line.split()]
        for word in list(words):
            if word in common_words or not word in correct_words:
                words.remove(word)
        print("There are " + str(len(words)))
        c = Counter(words)
        #for word, count in c.most_common():
        #    print (word, count)
        nNumbers = list(c.most_common(7))
        out = ""
        print("*************************************\nThese are the 7 most common:")
        for word, count in nNumbers:
                out = out + word + "," + str(count) + "\n"
        print(out + "\n*************************************")

    input("\nPress enter to continue...")


texts: Digital persona fingerprint verification takes a lot of time

texts:
I'm using Digital Persona U.are.U 4000b fingerprint reader and I have this function that verifies the fingerprint from SQL server

My problem is the loop because it takes a lot of time to compare the templates.

Please give me some advice on how can I optimize or revise my code.

CODE:

Protected Sub Process(ByVal Sample As DPFP.Sample)
    con = New SqlConnection

    con.ConnectionString = "Data Source=Test;Initial Catalog=TestDB;Persist Security Info=True;User ID=sa;Password=Passw0rd"

    Dim command As String = "SELECT * FROM Bio_Emplist"

    Dim da As New SqlDataAdapter(command, con)
    Dim dtb As New DataTable
    da.Fill(dtb)
    If dtb.Rows.Count > 0 Then
        rowCount = dtb.Rows.Count
        Try
            For Each dr As DataRow In dtb.Rows
                Dim fpt As Byte() = CType(dr("Fpt"), Byte())

                Dim ms As New MemoryStream(fpt)
                Dim tmpObj As DPFP.Template = New DPFP.Template
                Dim verify As DPFP.Verification.Verification = New DPFP.Verification.Verification

                Template = tmpObj
                tmpObj.DeSerialize(fpt)

                DrawPicture(ConvertSampleToBitmap(Sample))

                Dim features As DPFP.FeatureSet = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification)
                ' Check quality of the sample and start verification if it's good
                If Not features Is Nothing Then
                    ' Compare the feature set with our template
                    Dim result As DPFP.Verification.Verification.Result = New DPFP.Verification.Verification.Result()
                    verify.Verify(features, Template, result)
                    'UpdateStatus(result.FARAchieved)

                    If result.Verified Then
                        MakeReport("The fingerprint was VERIFIED.")

                        empID = dr("EmpID")
                        empFName = dr("FName")
                        empLName = dr("LName")
                        SetVerifyText(empID, empFName, empLName)
                        Exit Try
                    Else
                        FailedVerifyText()
                        If rowCount = 1 Then
                            MakeReport("The fingerprint was NOT VERIFIED.")
                        Else
                            rowCount = rowCount - 1
                            MakeReport("Finding Match...")
                        End If
                    End If
                End If
            Next
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End If
End Sub


texts: Moving WordPress database and files to new host

texts:
I've written a script in an attempt to try to automate moving hosts from old hosts to our new docker containers.

All feedback and input appreciated!

#!/bin/bash

# Generate private public ssh-keys
if [ ! -f "$HOME/.ssh/id_rsa" ] && [ ! -f "$HOME/.ssh/id_rsa.pub" ]; then
        ssh-keygen -b 4096
fi

read -p "Enter your ssh host:" ssh_host
read -p "Enter your ssh username:" ssh_user
read -p "Enter your remote ssh port:" ssh_port

# REMOTE SSH

if [ -z "$ssh_user" ]; then
        echo -e "Config: SSH Username missing"
        echo $ssh_user
        exit
fi

if [ -z "$ssh_host" ]; then
        echo -e "Config: SSH Host is missing"
        exit
fi

if [ -z "$ssh_port" ]; then
        echo -e "Config: SSH Port missing"
        exit
fi

ssh-copy-id $ssh_user@$ssh_host -p $ssh_port -i "$HOME/.ssh/id_rsa" &>/dev/null

# REMOTE DATABASE

read -p "Enter path for wp-config.php:" wp_config_path

# INIT
db_details="cat $wp_config_path/wp-config.php"
scp -P $ssh_port -r $ssh_user@$ssh_host:"$wp_config_path/*" .

# Might be dangerous if file contains malicious input in the values?
eval $(awk -F "[()']" '/^define\(/{printf "%s='\''%s'\''\n", $3, $5;}' < wp-config.php | grep DB_*)

if [ -z "$DB_USER" ]; then
        echo -e "Config: RDB user missing"
        exit
fi

if [ -z "$DB_PASSWORD" ]; then
        echo -e "Config: RDB password missing"
        exit
fi

if [ -z "$DB_NAME" ]; then
        echo -e "Config: RDB name missing"
        exit
fi

dump="mysqldump -u $DB_USER --password='$DB_PASSWORD' $DB_NAME"

read -p "Enter your LOCAL database user:" local_db_user
read -p "Enter your LOCAL database name:" local_db_name
read -s -p "Enter your local database password:" local_db_password

printf "\033c"

ssh $ssh_user@$ssh_host -p $ssh_port $dump | mysql -u $local_db_user --password=$local_db_password $local_db_name

sed -i -e "s;\(define([[:space:]]*'DB_USER',[[:space:]]*\)\(.*\)\()\;\);\1'$local_db_user'\3;g" wp-config.php
sed -i -e "s;\(define([[:space:]]*'DB_PASSWORD',[[:space:]]*\)\(.*\)\()\;\);\1'$local_db_password'\3;g" wp-config.php
sed -i -e "s;\(define([[:space:]]*'DB_NAME',[[:space:]]*\)\(.*\)\()\;\);\1'$local_db_name'\3;g" wp-config.php

echo -e "Database imported to: $local_db_name"
echo -e "Cleaning up..."

# CLEANING UP

# This is bad, and should NEVER be used on hosts with active pub/private key authentication.
ssh $ssh_user@$ssh_host -p $ssh_port 'echo "" > $HOME/.ssh/authorized_keys'

ssh_user=
ssh_host=
ssh_port=
DB_USER=
DB_PASSWORD=
DB_NAME=
local_db_name=
local_db_password=
local_db_user=
wp_config_path=

echo -e "Exiting"


texts: Java: Constructor- and Method-overloading exercise

texts:
It's from a Java-course I'm enrolled into.

The classes "Instructor" and "Book" are already provided.

You got to write the different constructors of "Instructor" as well as the methods "getMostRecentBookTitle" and overloaded "updateBook".

Here's are the final classes expanded with my additional code:

// ------- Class Instructor ----------------------------------------
public class Instructor {
    public long id;
    public String name;
    public String title;
    public String department;
    public Book[] books;

    public Instructor(long id, String name, String title, String department, Book[] books) {
        this(id, name, title, department);
        this.books = books;
    }

    public Instructor(long id, String name, String title, String department) {
        this(id, name, title);
        this.department = department;
    }

    public Instructor(long id, String name, String title) {
        this(id, name);
        this.title = title;
    }

    public Instructor(long id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getMostRecentBookTitle() {
        return books[books.length - 1].title;
    }

    public Book updateBook(int index, String title) {
        Book retBook = books[0];
        Book[] updatedBooks = new Book[books.length + 1];
        int i = 0;
        int j = 0;

        while (i < updatedBooks.length) {
            if (i == index) {
                updatedBooks[i] = new Book(title);
                retBook = books[i];
            } else {
                updatedBooks[i] = books[j];
            }

            i++;

            if (i != index) {
                j++;
            }
        }

        books = updatedBooks;

        return retBook;
    }

    public Book updateBook(int index, Book book) {
        for (int i = 0; i < books.length; i++) {
            if (i == index) {
                Book oldBook = books[i];
                books[i] = book;
                return oldBook;
            }
        }

        return new Book("");
    }

    public static void main(String[] args) {
        Book book1 = new Book("Wind Energy Design");
        Book book2 = new Book("Aerodynamics");
        Book book3 = new Book("Effective Java");

        Instructor instructor =
            new Instructor( 248,
                            "Walter", "Lecturer", "Mechanical Engineering",
                            new Book[]{book1, book2, book3});
        System.out.println(instructor.getMostRecentBookTitle());
        System.out.println("Title of old book: " + instructor.updateBook(1, "Vector mechanics").getTitle());

        Book book4 = new Book("Thermodynamics");
        System.out.println("Title of old book: " + instructor.updateBook(1, book4).getTitle());
    }
}

// ------- Class Book ----------------------------------------
public class Book {
    public String title;

    public Book(String title) {
        this.title = title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }
}

It works well and it has passed the automated tests.

But I'm unsatisfied with the method "updateBook(int index, String title)". That's just too much code for to accomplish such a simple task. In my opinion.

In JavaScript they have these method "splice". I guess that won't work in Java because Array-sizes can't be changed after construction.

Nevertheless: Is there a better way to write that method in Java?

Other hints, comments and recommendations concerning my implementation welcomed too.


texts:
I'm looking for a good approach to AJAX communication using only pure JS and PHP. I would like it to be as safe as possible and compatible with most modern browsers and IE 10+. I did some research and found some code examples for writing a vanilla JS function to handle AJAX communication, but I was not sure how safe and up to date those were. I started coding my own solution based on what I've found. I need to receive and send data using AJAX. There will be a login system and also a text posting system.

index.html

<input type="checkbox" id="agreement"/> I agree with terms.

<input type="text" id="user"/> User

<input type="password" id="password"/> Password

<textarea id="text"></textarea> Text

<button id="submit" onclick="submit_form()">Submit</button>

ajax.php

if($_GET['action'] == 'submit_form')
{
    $agreement = $_POST['agreement'];
    $user = $_POST['user'];
    $password = $_POST['password'];
    $text = $_POST['text'];

    echo 'Data received:
';
    echo 'Agreement: '.$agreement.'
';
    echo 'User: '.$user.'
';
    echo 'Password: '.$password.'
';
    echo 'Text: '.$text.'
';
}

scrip.js

function submit_form()
{
    var ajax = new XMLHttpRequest();

    ajax.open('POST', 'ajax.php?action=submit_form', true);

    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    var content = '';

    content = content + 'agreement=' + document.querySelector('#agreement').checked;
    content = content + '&user=' + document.querySelector('#user').value;
    content = content + '&password=' + document.querySelector('#password').value;
    content = content + '&text=' + document.querySelector('#text').value;

    ajax.send(content);

    ajax.onreadystatechange = function()
    {
        if (ajax.readyState == 4 && ajax.status == 200)
        {
            document.querySelector('#result').innerHTML = ajax.responseText;
        }
    }
}

Can you spot any problems with this approach? Are there better, simpler or more cross-browser compatible ways for doing the same? Are there any special concerns I should have when sending and receiving passwords?


texts: Computing the Fourier transform of a distribution of electron charge (represented by atomic positions in space)

texts:
I am computing a nested loop operation using OpenCL (open computing language). My main question is, given the code outlined below, how might I optimize the speed and efficiency of using the GPU, for instance by using local memory calls instead of global ones?

Given some input vector \$V=(v_x, v_y, v_z)\$ (in math terms, the input vector is a point in reciprocal space where we evaluate the Fourier transform),  the desired computation involves iterating over a collection of atoms in space (of different species, like Hydrogen, Oxygen, etc.) and using the input vector to compute a function. Each atom is described by a 4-tuple, consisting of 3 spatial coordinates, \$A=(a_x, a_y, a_z)\$, and 1 species identifier, species_id, which ranges from 0 to the number of unique atom species.

The iterations look like this (in pseudocode):

for V in input_vectors:
    ft_magnitude = 0
    for (A, species_id) in atoms:
        ft_magnitude += get_scale_factor(V, species_id) * exp( -i * dot(A,V))

where i in the exponential is the complex number \$i=\sqrt{-1}\$, the term dot(A,V) is the dot product of two vectors \$A \cdot V = a_x \cdot v_x + a_y \cdot v_y + a_z \cdot v_z\$, and get_scale_factor(V,species_id) is a lookup operation which returns the correct, pre-computed scale factor, which changes with each vector V and species_id.

The idea of using a GPU for this problem is to let each GPU worker compute the output for one vector V. I wrote a kernel posted below to be used with OpenCL, after following several examples I saw online.

The inputs to the kernel are the following:

input_vectors which has length 3*n_vectors, 3 per input vector
atoms which has length 4*n_atoms, 4 per atom
scale_factors which has length n_species * n_vectors , 1 per atom species per input vector
outputs which has length 2*n_vectors, 1 complex number per input vector, representing the Fourier transform magnitude

Here is the kernel (note the use of cosine and sine to evaluate the complex exponential using Euler's formula) :

__kernel void compute(
__global float *input_vectors,
__global float *atoms,
__global float *scale_factors,
__global float2 *outputs,
const int n_vectors,
const int n_atoms){

int i_v = get_global_id(0);

if ( i_v < n_vectors) {

    float vx = input_vectors[i_v*3];
    float vy = input_vectors[ i_v*3+1];
    float vz = input_vectors[ i_v*3+2];

    for (int i_a=0; i_a< n_atoms; i_a++){

        float ax = atoms[ i_a*4];
        float ay = atoms[ i_a*4+1];
        float az = atoms[ i_a*4+2];
        int species = atoms[i_a*4+3];
        float factor = scale_factors[ species * n_vectors + i_v ];

        float dot = vx*rx + vy*ry + vz*rz;

        outputs[i_v].x += factor*native_cos(-dot);
        outputs[i_v].y += factor*native_sin(-dot);
        }
    }
}

I am using PyOpenCL to wrap to the kernel but could be convinced to switch to something else if it would get speedups. To give a sense of scale, typically, n_vectors is on the order of 1,000,000, and n_atoms is on the order of 100,000, with about 10 different atom species.

Here is the GPU information for the machine I am using:

81:00.0 3D controller: NVIDIA Corporation GK110BGL [Tesla K40m] (rev a1)
Subsystem: NVIDIA Corporation 12GB Computational Accelerator
Physical Slot: 4
Flags: bus master, fast devsel, latency 0, IRQ 64
Memory at fa000000 (32-bit, non-prefetchable) [size=16M]
Memory at 27800000000 (64-bit, prefetchable) [size=16G]
Memory at 27c00000000 (64-bit, prefetchable) [size=32M]
Capabilities: <access denied>
Kernel driver in use: nvidia
Kernel modules: nvidia, nouveau, nvidiafb


texts: Suggestions for improving collection of related PHP functions?

texts:
I am working on a Web chat application. In the app, users can run commands (such as /nick, /msg, etc) by starting with a / and then typing the command followed by parameters. For example, if someone wanted to change their username to "foobar", they would enter this in:

/whois foobar

However, I cannot think of a good way to organize the code for this. This is what I have so far:

In User.php

function User_command(array $args)
{
   $command = $args['command'];
   list($command_name, $command_parameters) = explode(' ', $command, 2);
  $command_name = str_replace('/', '', strtolower($command_name));

$result = Command::process($command_name, $command_parameters);

if (!$result)
    return responseFailure();

addQueueEntry($result['json'], $result['user_id'], $result['room_id'], $result['added_by']);
return responseSuccess();
}

* In Command.php *

class Command
{
public function process($command, $parameters)
{
    $method = 'MinteCommand_' . $command;

    if (function_exists($method))
        return $method($parameters);

    return null;
}
}

/* Note: When implementing commands, you must specify all fields for $response */
/*       If you don't, then they might not work correctly or as intended. */

function MinteCommand_notice($message)
{
$response = array();
$response['json'] = array('addChatNotice' => $message);
$response['user_id'] = null;
$response['room_id'] = MINTE;
$response['added_by'] = SYSTEM;

return $response;
}

function MinteCommand_announce($message)
{
$response = array();
$response['json'] = array('addChatAnnouncement' => $message);
$response['user_id'] = null;
$response['room_id'] = MINTE;
$response['added_by'] = SYSTEM;

return $response;
}

function MinteCommand_announcement($message)
{
// Command "announcement" is an alternative spelling for command "announce"
return MinteCommand_announce($message);
}

function MinteCommand_clear($message)
{
$response = array();
$response['json'] = array('clearChat' => $message);
$response['added_by'] = SYSTEM;
$response['user_id'] = MINTE;
$response['room_id'] = null;

return $response;
}

function MinteCommand_whois($username)
{
$response = array();
$response['added_by'] = 'SYSTEM';
$query = DB::query('SELECT ip_address, user_agent, last_activity, room_id FROM mt_users
    WHERE username = ? LIMIT 1', $username);

$exists = $query['num_rows'] > 0;
$ip_address = $user_agent = $last_activity = $room_id = "";

if ($exists)
{
    $row = $query['rows'][0];
    $ip_address = $row['ip_address'];
    $user_agent = $row['user_agent'];
    $last_activity = $row['last_activity'];
    $room_id = $row['room_id'];
}

$response['json'] = array('addChatNotice' => !$exists ? 'User ' . $username . ' does not exist' :
    '[' . $username . '] ' . $ip_address . '/' . $user_agent . ', last_activity=' . $last_activity . ', room_id=' . $room_id);

$response['added_by'] = SYSTEM;
$response['user_id'] = MINTE;
$response['room_id'] = null;

return $response;
}

function MinteCommand_msg($args)
{
    list($username, $message) = explode(' ', $args, 2);
}

How can I go about improving the code and making it more organized and elegant? In total there will be around 30 commands.


texts:
I'm reading a file with the following data,

char peer0_3[] = { /* Packet 647 */
0x02, 0x00, 0x04, 0x00, 0x11, 0x01, 0x06, 0x1b,
0x04, 0x01, 0x31, 0x0a, 0x32, 0x30, 0x31, 0x39,
0x2d, 0x30, 0x36, 0x2d, 0x31, 0x30, 0x0a, 0x32,
0x30, 0x31, 0x39, 0x2d, 0x30, 0x36, 0x2d, 0x31,
0x30, 0x01, 0x30 };

with the following code, to get this 'C' text in a python list

f=open(thisFile,'r')
contents=f.read()
tcontents=re.sub('\/\*.*\*\/','',contents).replace('\n', '').strip()      #suppress the comments
xcontents = re.findall("{(.+?)};", tcontents, re.S)                       #find the arrays
frames=[]
for item in xcontents:
    splitData =item.split(',')
    buff=bytes()
    for item in splitData:
        packed =  struct.pack("B", int(item,0) )
        buff+=packed
    frames.append(buff)

That's working fine, but I was wondering if there was not a smarter and more compact method?


texts: Dynamic two-column list, "Vertical Wrap"

texts:
I have created a very simple script that will create two columns which are populated by an array. It works, but I am certain that the way that I have gone about it is not the best way. I have been searching for simple, sample scripts which would aide me in understanding how to best approach this, but all of them have been too specific to their application.

This is what I have made:

$assets = array('Bag', 'Charger', 'Power Cable', 'Video Cable',
    'Mouse', 'Keyboard', 'Test', 'Test 2', 'Test 3');
$assets_count = count($assets);

$halfway_raw = $assets_count / 2;
$halfway = round($halfway_raw, 0) - 1;

echo '
';

for($i = 0; $i < $assets_count; $i++) {
    if($i == $halfway) {
        echo '
' . $assets[$i] . '
';
        echo '
';
        echo '
';
    } else {
        echo '
' . $assets[$i] . '
';
    }
}

echo '
';

I'm looking for something that scales easily and is obviously as small as possible, which I don't think my script is.


texts: Handling shared state between actix and a parallel thread

texts:
In order to learn rust and concurrency , im trying to share a common hashmap between actix web server and a parallel thread

Theres one thread which updates a hashmap with the current timestamp every 10 seconds
theres a GET API which returns the latest timestamp provided in the hashmap

heres my code
use actix_web::{web, App, HttpServer};
use std::collections::HashMap;
use chrono::prelude::*;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

async fn get_latest_timestamp(data: web::Data<Arc<Mutex<HashMap<String, String>>>>) -> String {

    let wrapped_data = data.lock().unwrap();

    match wrapped_data.get("time_now") {
        Some(i) => String::from(i),
        None => String::from("None")
    }
}

fn update_timestamps(data: Arc<Mutex<HashMap<String, String>>>) -> () {

    loop {
        thread::sleep(Duration::from_secs(10));
        println!("Updating time.... ");
        let now: DateTime<Local> = Local::now();

        let mut data = data.lock().unwrap();

        data.insert(String::from("time_now"), now.to_rfc2822());
    }
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {

    let mut hash = HashMap::new();
    hash.insert(String::from("time_now"), Local::now().to_rfc2822());

    let data = Arc::new(Mutex::new(hash));

    let hash_clone = Arc::clone(&data);
    thread::spawn(move || {
        update_timestamps(hash_clone)
    });

    HttpServer::new( move || {
        App::new()
            .data(data.clone())
            .route("/", web::get().to(get_latest_timestamp))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

Is there anything i could do handle better. A couple of questions i do have

How does one generally handle errors that occur on the parallel thread? is the main thread notified in someway?

the code in update_timestamps runs in a continous loop - is there a better way to handle it so that it cleanly exits?


texts: Swift for flattening JSON nested objects

texts:
I am receiving JSON from a service API (Airtable) that returns an object with a single key records which is an array of objects. These objects have most of their information in a nested object called fields . Like so:

{
    "records": [
        {
            "id": "recC3HgjwICxlg9CE",
            "fields": {
                "Title": "Software engineer",
                "Name": "Cameron Toth",
...

I wrote a function (currently an extension to Data, will move to i.e. Alamofire) that returns a flattened JSON list, with fields keys moved to the parent object, optionally remapping key names.

I'd especially appreciate feedback on my use of guard/let/throw

extension Data {
    func airtableFlattenedJson(_ mapping: [String: String]? = nil) throws -> [[String : Any]] {
        let json = try JSONSerialization.jsonObject(with: self, options: [])
        guard let casted = json as? [String: [[String: Any]]] else { throw AirtableParsingError.jsonCouldNotCast }
        guard var records = casted["records"] else { throw AirtableParsingError.noRecordsFound }
        for (index, record) in records.enumerated() {
            var updated = record
            guard let fields = record["fields"] as? [String: Any] else { continue }
            for (key, value) in fields {
                if let mapped = mapping?[key] {
                    updated[mapped] = value
                } else {
                    updated[key] = value
                }
            }
            updated.removeValue(forKey: "fields")
            records[index] = updated
        }
        return records
    }
}

enum AirtableParsingError: Error {
    case jsonCouldNotCast
    case noRecordsFound
}


texts: Groovy script to get average price per group from different data arrays

texts:
I've been trying to learn Groovy lately and I tried to solve a problem which involves designing a routine that will calculate the average Product price per Group.

I have the following data:

// contains information about [Product, Group, Cost]
products = [
    ["A", "G1", 20.1],
    ["B", "G2", 98.4],
    ["C", "G1", 49.7],
    ["D", "G3", 35.8],
    ["E", "G3", 105.5],
    ["F", "G1", 55.2],
    ["G", "G1", 12.7],
    ["H", "G3", 88.6],
    ["I", "G1", 5.2],
    ["J", "G2", 72.4]
]

// contains information about Category classification based on product Cost
// [Category, Cost range from (inclusive), Cost range to (exclusive)]
// i.e. if a Product has Cost between 0 and 25, it belongs to category C1
category = [
    ["C3", 50, 75],
    ["C4", 75, 100],
    ["C2", 25, 50],
    ["C5", 100, null],
    ["C1", 0, 25]
]

// contains information about margins for each product Category
// [Category, Margin (either percentage or absolute value)]
margins = [
    "C1" : "20%",
    "C2" : "30%",
    "C3" : "0.4",
    "C4" : "50%",
    "C5" : "0.6"]

What I tried so far is the following (I mixed some Java here):

def calculateResult() {
    def group1 = []
    def group2 = []
    def group3 = []
    def pricePerGroupMap = [:]

category.each { cat ->
    String catDesc = cat[0]
    BigDecimal min = cat[1]
    BigDecimal max = cat[2]

    if (max == null) {
        max = 9999.9;
    }

    products.each { product ->
        BigDecimal currProductPrice = BigDecimal.valueOf(product[2])
        if (currProductPrice.compareTo(min) >= 0 && currProductPrice.compareTo(max) <= 0) {
            String selectedMarginAsString = margins.getAt(catDesc);
            BigDecimal selMargin = 0.0;

            if (selectedMarginAsString.endsWith("%")) {
                selMargin = new BigDecimal(selectedMarginAsString.trim().replace("%", "")).divide(BigDecimal.valueOf(100));
            } else {
                selMargin = new BigDecimal(selectedMarginAsString);
            }

            if (product[1].equals("G1")) {
                group1.add(product[2] * (1 + selMargin))
            } else if (product[1].equals("G2")) {
                group2.add(product[2] * (1 + selMargin))
            } else if (product[1].equals("G3")) {
                group3.add(product[2] * (1 + selMargin))
            }
        }

    }
}
pricePerGroupMap["G1"] = group1.sum() / group1.size()
pricePerGroupMap["G2"] = group2.sum()/ group2.size()
pricePerGroupMap["G3"] = group3.sum()/ group3.size()
print pricePerGroupMap
}

I am sure there are better ways to optimize this algorithm taking advantage of closures.


texts:
(I was suggested to post here from stack overflow so hey guys!)

I have been given a problem where fractions between 1/2 - 1/1000 have to be added to create the longest sequence of all unique unit fractions.

The rules on constructing these fractions:

Let create a set: D , D is only to hold unique unit fractions , sub-fractions can add up to the same fraction for example:

       1/10
        /      \
1/110 + 1/11    1/35 + 1/14

All sub-fractions can be held within the set as long as they themselves are not the same fractions once we are adding them together it is ok for them to total up to the same root.

The goal:

The fractions have to be added in a way to sum up to exactly 1. Any sub-fractions are not allowed to be over 1000 it is explicitly between 2 and 1000 hence the fractions which make up 1/1000 would not be applicable ( 1/1004 + 1/251000 ).

What currently I found to be the most effective:

Find the two lowest multiples which make-up the current fraction that I am looking at so for e.g 1/6 = A = 3 , B = 2. And now we complete the following equation: C = (A+B)*A , D = (A+B)*B. Now C & D are the sub-fractions which add up to my initial fraction

      1/6
   /       \
1/15       1/10

In code:

public static int[] provideFactorsSmallest(int n) {
    int k[] = new int[2];

    for(int i = 2; i <= n - 1; i++) {
        if(n % i == 0) {
            k[0] = i;
            break;
        }
    }

    for(int i = k[0] + 1; i <= n - 1 && k[0] != 0; i++) {
        //System.out.println("I HAVE BEEN ENTERED");
        if(k[0] * i == n) {
            k[1] = i;
            int firstTerm =  k[0];
            int secondTerm = k[1];
            k[0] = (firstTerm + secondTerm) * firstTerm;
            k[1] = (firstTerm + secondTerm) * secondTerm;
            return k;
        }
    }
    return null;
}

My question:

What would be the most effective way to pair and group the numbers to achieve possible longest fraction sequence?


texts: Binary search tree implementation in Python

texts:
I am reading about algorithms and got to the binary search trees. I wanted to ask if the following implementation of a Binary Tree is correct.

import random

class Tree(object):

    def __init__(self):

        self.root = Node()

    def insert(self,data):

        self.root.insert(data)

    def delete(self,data):

        self.root.delete(data)

    def print_elements(self):

        return self.root.print_element()

class Node(object):

    def __init__(self,data = None, parent = None):

        self.parent = parent
        self.data = data
        self.left = None
        self.right = None

    def insert(self,data):

        if self.data == None:

            self.data = data
        else:
            if data < self.data:
                if self.left == None:
                    self.left = Node(data,self)
                else:
                    self.left.insert(data)
            else:
                if data > self.data:
                    if self.right == None:
                        self.right = Node(data,self)
                    else:
                        self.right.insert(data)

    def delete(self,data):

        if self.data == data:

            if self.right == None and self.left == None:

                if self.parent.left.data == data:

                    self.parent.left = None
                else:

                    self.parent.right = None
            elif self.right == None or self.left == None:

                if self.right == None:

                    self.data , self.left = self.left.data , self.left.left

                else:

                    self.data, self.right = self.right.data , self.right.right

            else:

                counter = self.right
                while True:
                    if counter.right == None:
                        break
                    else:
                        counter = counter.left
                self.data = counter.data
                counter.delete(counter.data)

        else:
            if data < self.data:
                self.left.delete(data)
            else:
                self.right.delete(data)

    def search(self,data):

        if self.data == data:
            return self.data
        else:
            if data < self.data:
                return self.left.search(data)
            else:
                return self.right.search(data)

    def print_element(self):

        if self.parent:

            print self.data, 'is below %s' % (self.parent.data)
        else:
            print self.data

        if self.right != None:
            self.right.print_element()
        if self.left != None:
            self.left.print_element()

The other thing I want to ask is, when I am implementing these data structures (also happened with linked lists) I find it easier to implement the methods in the Node class and not in the BT/LL class. Is this normal with Python ? I mean, I see the guides with C++ and the methods are mostly implemented in the BT/LL classes , but they use pointers and pointers are not available in Python. Am I doing it wrong ?


texts: K’th SmallestElement in Unsorted Array in python

texts:
I was solving this sorting problem, and I was wondering if I can get any code review and feedback. You can find this problem online.

#  Find Kth Smallest Element in a Range
#
#  Prompt:    Given an unsorted array of whole integers in the range
#             1000 to 9000, find the Kth smallest element in linear time
#             The array can have duplicates.
#
#  Input:     Unsorted array of whole integers in range of 1000 to 9000
#             Kth smallest element you want to find
#
#  Output:    Kth smalest element in the range
#
#  Example:   array = [1984, 1337, 9000, 8304, 5150, 9000, 8304], k=5
#             output = 8304
#
#  Notes:     What are the time and auxilliary space complexity?

# Time Complexity: O(N)
# Auxiliary Space Complexity: O(N)

def kthSmallest(lst, k):
    if k > len(lst):
        return None
    int_counts = [0 for x in range(8001)]
    for i in range(len(lst)):
        int_counts[lst[i] - 1000] += 1
    cumulative = []
    prev = 0
    for i in range(len(int_counts)):
        cumulative.append(int_counts[i] + prev)
        prev += int_counts[i]
    for i in range(len(lst) - 1, -1, -1):
        if cumulative[lst[i] - 1000] - 1 == k - 1:
            return lst[i]
        cumulative[lst[i] - 1000] -= 1

it passes all of the following test

from cStringIO import StringIO
import sys
import random

# code for capturing print output
#
# directions: capture_print function returns a list of all elements that were
#             printed using print with the function that it is given. Note that
#             the function given to capture_print must be fed using lambda.
#             Example cis provided below
class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self

    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        sys.stdout = self._stdout

# custom assert function to handle tests
# input: count {List} - keeps track out how many tests pass and how many total
#        in the form of a two item array i.e., [0, 0]
# input: name {String} - describes the test
# input: test {Function} - performs a set of operations and returns a boolean
#        indicating if test passed
# output: {None}
def expect(count, name, test):
    if (count is None or not isinstance(count, list) or len(count) != 2):
        count = [0, 0]
    else:
        count[1] += 1

    result = 'false'
    error_msg = None
    try:
        if test():
            result = ' true'
            count[0] += 1
    except Exception, err:
        error_msg = str(err)

    print('  ' + (str(count[1]) + ')   ') + result + ' : ' + name)
    if error_msg is not None:
        print('       ' + error_msg + '\n')

print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')

print('Kth Smallest Element Tests')
test_count = [0, 0]

def test():
    example = kthSmallest([1984, 1337, 9000, 8304, 5150, 9000, 8304], 5)
    return example == 8304

expect(test_count, 'should return 8304 for sample input', test)

def test():
    example = kthSmallest([1984, 1337, 9000, 8304, 5150, 9000, 8304], 1)
    return example == 1337

expect(test_count, 'should return 1337 for 1st smallest element with sample input array', test)

def test():
    example = kthSmallest([1984, 1337, 9000, 8304, 5150, 9000, 8304], 10)
    return example == None

expect(test_count, 'should error out when asking for kth smallest when k exceeds size of input array', test)

def test():
    example = kthSmallest([8304], 1)
    return example == 8304

expect(test_count, 'should work for single-element array', test)

def test():
    test_case = []
    for i in range(0, 1000000):
        test_case.append(int(random.random() * 8000) + 1000)
    example = kthSmallest(test_case, 185)
    test_case.sort()
    return example == test_case[184]

expect(test_count, 'should work for a large array', test)

print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')


texts: Calculating the number of prime numbers to solve the puzzle

texts:
How can the following program execution time improved?  I have used dynamic programming in both "recursive" as well as "prime" function, but I'm not getting the efficient execution time.

  There is a wall of size 4xN in the victim's house where. The victim
  also has an infinite supply of bricks of size 4x1 and 1x4 in her
  house. In every configuration, the wall has to be completely covered
  using the bricks. Gale Bertram wants to know the total number of ways
  in which the bricks can be arranged on the wall so that a new
  configuration arises every time.

  Let the number of Configuration = \$M\$.

  So, he wants Patrick to calculate the number of prime numbers (say \$P\$)
  up to \$M\$ (i.e. \$<= M\$).  You are required to help Patrick correctly solve
  the puzzle.

  Sample Input

  The first line of input will contain an integer \$T\$
  followed by \$T\$ lines each containing an integer \$N\$.

  Sample Output

  Print exactly one line of output for each test case. The
  output should contain the number \$P\$.

  Constraints

  \$1 <= T <= 20\$
  \$1 <= N <= 40\$

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class Solution{
    public static int[] b = new int[217287];
    public static void main(String[] args){
        Scanner stdin = new Scanner(System.in);
        int t = stdin.nextInt();
        int[] a = new int[41]; //array initialized before because the value remains same.
        for(int j=0;j<4;j++){
                a[j] = 1;          //till n<=3, number of possiblities = 1. These will work as base cases.
            }
            a[4] = 2;
        for(int x=0;x<t;x++){
            int n = stdin.nextInt();
            for(int i=5;i<=n;i++){
                a[i] = -1;         //initialise all value in the array as -1.
            }
            if(n<4)
                System.out.println("0"); // if n<4, number of possibilities =1. So no prime number before that is 0.
            else{
                         //for n=4, possibilities = 2. This is a base case.
            int num1 = recursive(a,n);          // storing number of possibilities in num1.
            int num2 = prime(num1);    //calling to calculate number of prime numbers before or equal to num1.
            System.out.println(num2);
            }
        }
    }
    public static int recursive(int[] a, int n){
        if(a[n]!=-1)                             // retrieving a[n] value if already calculated.
            return a[n];
        else{
            a[n] = recursive(a,n-1) + recursive(a,n-4); // calling recursively.If we fill with a 4*1 first tile then number
                                                        //tiles left is n-1(try visualising).If we fill 1*4 tile first
                                                        // we have n-4 tile left.
            return a[n];
        }
    }
    public static int prime(int n){
        int count = 0;
        if(b[n]!=0)
            return b[n];
        else{
        for(int i=2;i<=n;i++){
            if(b[i]!=0){
                count = b[i];
            }
            else{
            int flag = 0;
            for(int j=2;j<=i/2;j++){
                if(i%j==0){
                    flag = 1;
                    break;
                    }
                }
        if(flag==0){
            count++;
            b[i]=count;
        }
        }
        }
        return count;
        }
    }
}

I got a timeout (more than 4s) for the following input:

20
35
23
25
38
4
35
19
8
23
35
3
36
12
10
30
13
18
31
40
37


texts: Function for simple navigation of dataframe in console

texts:
I was looking for a way to navigate through a dataframe in R using just the console that displays every n lines. There are a few functions you can find at StackOverflow that attempt to answer this but none are quite what I want. So I made my own function but it has a lot of if statements. How can I refactor my code to make it more concise and clean?

Note: I chose "." and "/" for page up and page down because code completion in RStudio automatically turns "[" into "[ ]". I'm open to any alternative symbols.

Here is the code. It is called "less" but it is obviously missing most of the functions in the Unix version of less.

less <- function(x, n = 10) {
  begin = 1
  end = n

  repeat {
    print(
      x[begin:end, ]
    )

    input <- readline("Type . to scroll up, type / to scroll down: ")

    if(input == ".") {
      begin = begin - n
      end = end - n
    }

    if(input == "/") {
      begin = begin + n
      end = end + n
    }

    if(end >= nrow(x)) break

    if(end < 1) break
  }
}


texts:
I've recently started teaching myself basic C++ and decided to implement a simple stack with pointers.

#include <iostream>

using namespace std;

struct StackElement {
    char value;
    StackElement* next;

    StackElement(char value, StackElement* next) : value(value), next(next) {}
};

struct Stack {
    StackElement* top = NULL;

    bool isEmpty() { return top == NULL; }

    void push(char value) {
        StackElement* newElement = new StackElement(value, top);

        top = newElement;
    }

    StackElement pop() {
        StackElement* toBeDeleted = top;
        StackElement toBeReturned = *top;

        top = top->next;
        delete toBeDeleted;
        return toBeReturned;
    }
};

int main() {
    Stack* stack = new Stack();
    cout << "Created a stack at " << &stack << endl;

    int number_of_inputs;
    cout << "Enter the number of elements you want to push at the stack: ";
    cin >> number_of_inputs;

    for (int i = 0; i < number_of_inputs; i++) {
        char input;
        cin >> input;
        stack->push(input);
    }

    cout << "- - - - - - - - - - - - - - - - " << endl;
    cout << "Displaying content of the stack: " << endl;

    while (!stack->isEmpty()) {
        cout << stack->pop().value << endl;
    }

    return 0;
}

My questions are:
- what could be generally done better here?
- is the pop() method written correctly? Does it create any memory leaks? Is there a way to write it shorter?

Thank you in advance! (And forgive use of using namespace std)


texts: CodeChef Fusing Weapons in a circular list

texts:
I am currently trying to solve this problem on Codechef:

  Before the start of each stage, N weapons appear on the screen in circular order. Each weapon has an integer associated with it, which represents its level. The chef can choose two adjacent weapons of the same level and fuse them into a single weapon of level A+1, where A is the level of the weapons before fusing. Both the old weapons will disappear and the new weapon will be placed in the place of the old weapons, shrinking the circle.

  Chef can fuse as many times as he wants, and in each stage, he wants to make a weapon with as high a level as possible. Each stage is independent of other stages.

  Please help Chef by figuring out the maximum level of a weapon that he can get in each stage.

However, my code seems to exceed the time limit. Can someone please tell me how to optimize this code to prevent it from exceeding the time limit?

#include <iostream>

using namespace std;

class Set
{
public:
    int data[200000];
    int length;
};

int findMax(int data[], int size)
{
    int max = data[0];
    for (int i = 1; i < size; i++)
    {
        if (max < data[i])
        {
            max = data[i];
        }
    }

    return max;
}

void mergeData(int data[], int &size)
{
    for (int i = 0; i < size - 1; i++)
    {
        for (int j = i + 1; j < size; j++)
        {
            if (data[i] == data[j])
            {
                data[i]++;

                for (int k = j; k < size - 1; k++)
                {
                    data[k] = data[k + 1];
                }
                size--;

                mergeData(data, size);
            }
        }
    }
}

//Main function
int main()
{
    int numSets;
    cin >> numSets;

    Set* sets = new Set[100];
    for (int i = 0; i < numSets; i++)
    {
        cin >> sets[i].length;
        for (int j = 0; j < sets[i].length; j++)
        {
            cin >> sets[i].data[j];
        }
    }

    for (int i = 0; i < numSets; i++)
    {
        mergeData(sets[i].data, sets[i].length);
        cout << findMax(sets[i].data, sets[i].length) << endl;
    }

    return 0;
}


texts: Setting the positions of nodes based on a layout

texts:
I have a bit of code that looks like this:

    for (Node n : g.getNodes().values()){
        n.setPosition(new Position(new Double(lo.getX(new Integer(n.getId()))).intValue(), new Double(lo.getY(new Integer(n.getId()))).intValue()));
    }

Essentially all I'm wanting to do is for each node in the collection, fetch and assign the position for that node from the layout.

Let me explain:

Node has an id of type int which is returned by n.getId().
The Layout lo will return the X and Y positions of the node by calling getX(Integer id) and getY(Integer id). The type returned is double.
A Node has a Position object which has constructor (int, int).

So:

In order to pass the id into the layout i need to use new Integer(id)
In order to convert the returned double to int I need to first upgrade the double to Double using new Double and then use .intValue() to convert it to an int.

It all seems ridiculous and verbose.

I am the one writing the Position and Node classes, so I can change the constructor and method signatures and return types if want. The Layout class is an external library, so I'll have to work with their signatures.

For example, an easy fix would be to create a Position(double x, double y) constructor, and do the double -> Double -> int conversion in the constructor.

public Position (double x, double y) {
    this.x = new Double(x).intValue();
    this.y = new Double(y).intValue();
}

This would change the code to:

    for (Node n : g.getNodes().values()){
        n.setPosition(new Position(lo.getX(new Integer(n.getId())),lo.getY(new Integer(n.getId()))));
    }

I could also create a second getter on Node to return Integer.

public Integer getIdAsInteger(){
    return new Integer(this.id);
}

Is this a good idea?

This would reduce the code to:

    for (Node n : g.getNodes().values()){
        n.setPosition(new Position(lo.getX(n.getIdAsInteger()),lo.getY(n.getIdAsInteger())));
    }

Finally, I could also create an additional setter setPosition(double x, double y).

public void setPosition(double x, double y) {
    this.position = new Position(x, y);
}

which would reduce the code to:

    for (Node n : g.getNodes().values()){
        n.setPosition(lo.getX(n.getIdAsInteger(),lo.getY(n.getIdAsInteger()));
    }

The question is - is this the right way to go about structuring my code? It still seems very verbose, and a lot of boiler plate, I'm wonder if there's another much simpler design pattern that addresses this.


texts:
I don't know much about the design of cryptographic hash functions but despite that I made an attempt for the sake of learning. This is what I got:

#include <stdio.h>

void hash(int* bits, int bitsLen, int* out, int outLen){
  const int tt[9] = {1,2,0,0,0,1,1,2,2};
  int st[128], i, k, j, y, a, b, o = 0;
  for (i=0; i<128; ++i)
    st[i] = i%3;
  for (k=0; k < bitsLen + outLen; ++k){
    for (j=0; j<32; ++j){
      if (k < bitsLen)
        st[0] = bits[k];
      for (i=j%2; i<128; i+=2){
        y = (i+1)%128;
        a = st[i];
        b = st[y];
        st[i] = tt[a*3+b];
        st[y] = tt[b*3+a];
      };
    };
    if (k >= bitsLen)
      out[o++] = (st[0] + st[1]*3 + st[2]*9 + st[3]*27) % 2;
  };
}

void printHex(int* bits, int bitsLen){
  int i;
  for (i=0; i<bitsLen/4; ++i)
    printf("%x", bits[i*4+0]*8+bits[i*4+1]*4+bits[i*4+2]*2+bits[i*4+3]);
}

void toBits(int n, int* bits, int bitsLen){
  int i;
  for (i=0; i<bitsLen; ++i)
    bits[bitsLen-i-1] = (n >> i) & 1;
}

int main(){
  const int bitsLen = 16;
  int bits[bitsLen];

  const int outLen = 256;
  int out[outLen];

  int i;
  for (i=0; i<256; ++i){
    toBits(i, bits, bitsLen);
    hash(bits, bitsLen, out, outLen);
    printHex(bits, bitsLen);
    printf(": ");
    printHex(out, outLen);
    printf("\n");
  };
}

This passes my (certainly lacking) criteria. I'd like to know what are the weaknesses of this function and how it could be exploited if actually used to replace, say, SHA3 in a cryptographic application that requires collision-resistance, non-reversibility and so on.


texts:
I created a script for interval timer with tkinter gui.
Here the part that is displaying time looks to be done not in
the best way. Any ideas would be greatly appreciated.

This timer is intended for timing HIIT/Tabata workouts.
User provides working time, rest time, preparation time
in seconds and integer number of intervals and upon hitting
start button displays work/rest seconds countdown.
After each interval a beep sound is played and a song
after all of them are over.
Also there options to change color of background and text.

from tkinter import *
from tkinter.colorchooser import *
from PIL import ImageTk, Image
import os

master = Tk()

def label_message(gt, wt, rt, it):

    res=[]

    for i in range(int(gt),-1,-1):
        res.append('Get Ready!: \n'+ str(i))
    res.append('')

    for i in range(int(it)):
        for j in range(int(wt),-1,-1):
            res.append('Round: \n' + str(i) +'\n Work : \n'+ str(j))
        res.append('')
        for k in range(int(rt),-1,-1):
            res.append('Round: \n' + str(i) +'\n Rest : \n'+ str(k))
        res.append('')

    res.append('Over!')

    return res

def window_color():
    color = askcolor()
    #print (color)
    widgets=[label1,label2,label3,label4,label5,master]
    for i in widgets:
        i.configure(background=color[1])

def text_color():
    color = askcolor()
    #print (color)
    widgets=[label1,label2,label3,label4,label5]
    for i in widgets:
        i.configure(fg=color[1])

def return_entry():

    wt = e1.get()
    rt = e2.get()
    gt = e3.get()
    it = e4.get()

    texts=label_message(gt, wt, rt, it)

    for i in texts:
        if i:
            master.after(1000, label5.config(text=i))
            master.update()
        else:
            master.bell()

    os.startfile('Jean Jacques Goldman - Asterix Et Obelix Contre Cesar (Generique Debut).mp3')

master.configure(background='white')
master.resizable()
master.title='Timer'

label1 = Label(master, text="Working Time", bg='white')
label2 = Label(master, text="Rest Time", bg='white')
label3 = Label(master, text="Get Ready Time", bg='white')
label4 = Label(master, text='Intervals', bg='white')
label5 = Label(master, text='time', height=5,  font=('Times New Roman', 15), bg='white')

img = ImageTk.PhotoImage(Image.open('clock.jpg'))
panel = Label(master, image = img)
panel.grid(column=0, row=0, rowspan=11, columnspan=3)

button1=Button(text='Window Color', command=window_color)
button1.grid(row=0, column=4, sticky=N+S+E+W)

button2=Button(text='Text Color', command=text_color)
button2.grid(row=0, column=5, sticky=N+S+E+W)

label1.grid(row=1, column=4)
label2.grid(row=2, column=4)
label3.grid(row=3, column=4)
label4.grid(row=4, column=4)
label5.grid(row=7, column=4, columnspan=2, rowspan=2)

e1 = Entry(master)
e2 = Entry(master)
e3 = Entry(master)
e4 = Entry(master)

e1.grid(row=1, column=5)
e2.grid(row=2, column=5)
e3.grid(row=3, column=5)
e4.grid(row=4, column=5)

button3=Button(text='Start', command=return_entry)
button3.grid(row=10, column=4, sticky=N+S+E+W)

button4=Button(text='Quit', command=master.quit)
button4.grid(row=10, column=5, sticky=N+S+E+W)

master.after(1000, None)
mainloop()


texts: Load data from WebAPI to the ViewController

texts:
My current code working perfectly, it is for data load from web api to the UIViewController (UITableView).
But I am confused that if it violates the Dependency Inversion Principle(DIP) of SOLID?
If so, how to fix that?

class AreaController: UIViewController {

        var townCityList : [TownCity]?

        override func viewDidLoad() {
            super.viewDidLoad()

           // locations implements ILocation interface

            let service = NetworkModelTownCity()

            // So here, when creating a new instance you're injecting the dependecy.

            let dataprocess = DataProcessLocation(location : service)

            dataprocess.locations({ (locations) in

                 self.townCityList = locations
                 self.tableView.reloadData()
            })
        }

    }

protocol Ilocation {

    func townCitys(_ completionHandler: @escaping (_ locations: [TownCity]) -> Void)
}

class DataProcessLocation {

    var location : Ilocation!

    init(location : Ilocation) {

       self.location = location
    }

    func locations(_ completionHandler: @escaping (_ locations: [TownCity]) -> Void) {

        self.location.townCitys( { (locations) in

            completionHandler(locations)

        })

    }

}

class NetworkModelTownCity : Ilocation {

     func townCitys(_ completionHandler: @escaping ([TownCity]) -> Void) {

        let _jsonFormatString = ["":""]

        RestApiService.shared.fetchDataByPostRequest(with: _jsonFormatString  , actionMethod: Constants.ApiRequest.actionMethod.townCity.rawValue) { (json) in

            var  _objs = [TownCity]()

            print(json)

            guard let objList = json as? [AnyObject] else {
                return
            }

            for obj in objList {
                if  let _obj = TownCity(fromAPIResponse: obj as! Dictionary<String, AnyObject>){
                    _objs.append(_obj)
                }

            }

            completionHandler(_objs)

        }
    }

}

class TownCity{

    var  townId : String = ""
    var  cityId : String = ""
    var  townName : String = ""
    var selectedShopTypeId : String = ""

    init?(fromAPIResponse resposne : Dictionary<String,AnyObject>){

        guard let townId = resposne["townId"]  as? String , let cityId = resposne["cityId"] as? String , let townName = resposne["townName"] as? String  else {
            return nil
        }

        self.townId = townId
        self.cityId = cityId
        self.townName = townName
    }
}