texts:
An array is defined to be maxmin equal if it contains at least two different elements and the number of times the maximum value occur is the same as the number of times the minimum value occur. So {11, 4, 9, 11, 8, 5 , 4, 10} is maxmin equal, because the max value 11 and min value 4 both appear two times in the array.

if the input array is {} , isMaxMinEqual should return false (array must have at least two different elements) status = false;
if the input array is {2}, isMaxMinEqual should return false (array must have at least two different elements).
if the input array is {1,1,1,1,1,1}, isMaxMinEqual should return false (array must have at least two different elements).
if the input array is {2,4,6,8,11}, isMaxMinEqual should return true (Both max value(11) and min value 2 appear exactly one time).
if the input array is {-2,-4,-6,-8,-11}, isMaxMinEqual should return true(Both max value(-2) and min value -11 appear exaclty one time).

I wrote the class MaxMin which satisfied the above condition.

public class MaxMin {

public static void main(String args[]) {
    System.out.println("The result is: " + isMaxMinEqual(new int[]{2, 2}));
}

public static boolean isMaxMinEqual(int[] a) {
    boolean status = false;
    int count = 0;
    if (a.length < 2) {
        status = false;
        return status;
    }
    for (int i = 1; i < a.length; i++) {
        if (a[i - 1] != a[i]) {
            count++;
        }
    }

    int max = a[0];
    int min = a[0];
    for (int i = 0; i < a.length; i++) {
        if (a[i] > max) {
            max = a[i];
        } else if (a[i] < min) {
            min = a[i];
        }
    }

    int maxCount = 0;
    for (int j = 0; j < a.length; j++) {
        if (a[j] == max) {
            maxCount++;
        }
    }

    int minCount = 0;
    for (int j = 0; j < a.length; j++) {
        if (a[j] == min) {
            minCount++;
        }
    }
    System.out.println(count);
    System.out.println("max is: " + max);
    System.out.println("min is: " + min);
    System.out.println("Max Count is: " + maxCount);
    System.out.println("Min Count is: " + minCount);

    if (maxCount == minCount && count >= 1) {
        status = true;
    }

    return status;
}
}


texts:
The rules for this script are simple:

If geocode is hit, then just geocode
If geocode and submit is hit, then geocode and then submit
If an autosuggest link is hit, then geocode instantly
In this case, do not re-geocode later when the button is hit

This is my code, based on help and advice from here:

http://jsfiddle.net/spadez/Jfdbz/14/

$(function () {
    var lastQuery = null,
        lastResult = null, // new!
        autocomplete,
        processLocation = function (callback) { // accept a callback argument
            var input = $("#loc"),
                lat = $("#lat"),
                long = $("#lng");
            var query = $.trim(input.val()),
                geocoder;
            // if query is empty or the same as last time...
            if (!query || query === lastQuery) {
                if (callback) {
                    callback(lastResult); // send the same result as before
                }
                return; // and stop here
            }

            lastQuery = query; // store for next time

            geocoder = new google.maps.Geocoder();
            geocoder.geocode({
                address: query
            }, function (results, status) {
                if (status === google.maps.GeocoderStatus.OK) {
                    lat.val(results[0].geometry.location.lat());
                    long.val(results[0].geometry.location.lng());
                    lastResult = true; // success!
                } else {
                    alert("Sorry - We couldn't find this location. Please try an alternative");
                    lastResult = false; // failure!
                }
                if (callback) {
                    callback(lastResult); // send the result back
                }
            });
        },
        ctryiso = $("#ctry").val(),
        options = {
            types: ["geocode"]
        };

    if (ctryiso !== '') {
        options.componentRestrictions = {
            'country': ctryiso
        };
    }
    autocomplete = new google.maps.places.Autocomplete($("#loc")[0], options);

    google.maps.event.addListener(autocomplete, 'place_changed', processLocation);

    $('#search').click(function (e) {
        var form = $(this).closest('form');
        e.preventDefault(); // stop the submission

        processLocation(function (success) {
            if (success) { // if the geocoding succeeded, submit the form
                form.submit();
            }
        });
    });

    $('#geosearch').click(function (e) {
        var form = $(this).closest('form');
        e.preventDefault(); // stop the submission
        processLocation();
    });
});

I think I have reached the point where it works correctly, and I can't seem to make it any more structured, any more readable, any more efficient or compact. However, I am new to javascript and I would be really open to hear if anyone feels that they can improve on this.

I must admit I a bit pedantic and get a lot of satisfaction out of the refining process!

EDIT: I pasted the code wrong - fixed


texts: Convert fs code to fs-extra using node js

texts:
i have code which used to read directory recursive and with given depth but i have wrote this code by using var fs= require("fs");
so my code look like this
async function checkFileLoc(folderPath, depth) {
  depth -= 1;
  let files = await fs.readdir(folderPath);
  files = await Promise.all(
    files.map(async (file) => {
      const filePath = path.join(folderPath, file);
      const stats = await fs.stat(filePath);
      if (stats.isDirectory() && depth > 0) {
        return checkFileLoc(filePath, depth);
      } else if (stats.isFile()) return filePath;
      else return null;
    })
  );
  return files
    .reduce((all, folderContents) => all.concat(folderContents), [])
    .filter((e) => e != null);
}

I want same code to be written by using fs-extra package with certain depth which is passed by user any idea how this code can be converted into fs-extra code


texts: Clock that changes document background color

texts:
This is a timer based clock (using setInterval()) that changes the background color of the body based on the clock time hexadecimal values. I suspect that this code is messy. Is there any way the following JS code be made more efficient?

var clock = document.getElementById('clock');
var color = document.getElementById('hex-color');

function hexclock(){

  var time = new Date();
  var hours = (time.getHours() % 12).toString();
  var minutes = time.getMinutes().toString();
  var seconds = time.getSeconds().toString();

  if(hours.length < 2) {

    hours = '0' + hours;
  }

  if(minutes.length < 2) {

    minutes = '0' + minutes;
  }

    if(seconds.length < 2) {

    seconds = '0' + seconds;
  }

  var clockString = hours + ' : ' + minutes + ' : ' + seconds;
  var hexColorString = "#" + hours + minutes + seconds;

  clock.textContent = clockString;
  color.textContent = hexColorString;

  document.body.style.backgroundColor = hexColorString;
}

setInterval(hexclock, 1000);
body{
  marin-top:20px;
  text-align:center;
  color:white;
}

#clock{
  font-weight:300;
  font-size:60px;
}

00 : 00 : 00

#000000


texts:
I have following model and database created using Entity Framework. Is it proper TPT Inheritance?

Is it possible to make the base class as abstract?

Model

Database

CODE

namespace LijosEF
{
public partial class Book
{
    public override void Sell()
    {
        this.AvailabilityStatus = "BookSOLD";
    }

}

public partial class DigitalDisc
{
    public override void Sell()
    {
        this.AvailabilityStatus = "DiscSOLD";
    }

}

public partial class SellingItem
{
    public virtual void Sell()
    {
        //Do nothing
    }
}
}

Client

namespace LijosEF
{
class Program
{

    static string connectionStringVal;

    static void Main(string[] args)
    {

        SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
        sqlBuilder.DataSource = ".";
        sqlBuilder.InitialCatalog = "LibraryReservationSystem";
        sqlBuilder.IntegratedSecurity = true;

        // Initialize the EntityConnectionStringBuilder.
        EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
        entityBuilder.Provider = "System.Data.SqlClient";
        entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
        entityBuilder.Metadata = @"res://*/MyModelFirstTest.csdl|res://*/MyModelFirstTest.ssdl|res://*/MyModelFirstTest.msl";

        connectionStringVal = entityBuilder.ToString();

        //AddBook();
        //AddDisc();

        //MakePurchase();

        int billAmount = GetTotalPurchaseValue(1);

    }

    private static void AddBook()
    {
        using (var db = new MyModelFirstTestContainer(connectionStringVal))
        {
            Book book = new Book();
            book.AvailabilityStatus = "Available";
            book.Price = 150;
            book.Title = "Maths Easy";

            db.SellingItems.AddObject(book);
            db.SaveChanges();

        }

    }

    private static void MakePurchase()
    {

        using (var db = new MyModelFirstTestContainer(connectionStringVal))
        {
            DigitalDisc disc = db.SellingItems.OfType<DigitalDisc>().FirstOrDefault(p => p.Artist == "Turtle Violin");
            disc.Sell(); //Changes State

            Book book = db.SellingItems.OfType<Book>().FirstOrDefault(p => p.Title == "Maths Easy");
            book.Sell(); //Changes State

            Purchase purchase = new Purchase();
            purchase.Date = DateTime.Now;
            purchase.SellingItems.Add(book);
            purchase.SellingItems.Add(disc);

            db.Purchases.AddObject(purchase);
            db.SaveChanges();

        }

    }

    private static int GetTotalPurchaseValue(int purchaseID)
    {
        using (var db = new MyModelFirstTestContainer(connectionStringVal))
        {

            var purchase = db.Purchases.FirstOrDefault(p => p.PurchaseId == purchaseID);
            if( purchase == null)
            {
                return 0;
            }

            var total = purchase.SellingItems.Sum(x => Convert.ToInt32(x.Price));
            return total;

        }

    }

    private static void AddDisc()
    {

        using (var db = new MyModelFirstTestContainer(connectionStringVal))
        {
            DigitalDisc disc = new DigitalDisc();
            disc.AvailabilityStatus = "Available";
            disc.Price = 300;
            disc.Artist = "Turtle Violin";

            db.SellingItems.AddObject(disc);
            db.SaveChanges();

        }

    }

}
}

REFERENCE:

https://stackoverflow.com/questions/4254182/inheritance-vs-enum-properties-in-the-domain-model/4259033#comment15499738_4259033
https://stackoverflow.com/questions/11683536/entity-framework-get-subclass-objects-in-repository#comment15499860_11683536
https://softwareengineering.stackexchange.com/questions/158472/why-should-i-add-check-constraint


texts:
I recently implemented a binary reader/writer for my multiplayer game.

Now reading bytes looks like this:

static int32_t readInt32(std::vector<uint8_t>& msg, int *off)
{
    if ((*off) > msg.size()) return 0;
    int32_t result; int size = sizeof (result);
    memcpy(&result, msg.data() + (*off), size); (*off) += size;
    return result;
}

And writing bytes looks like this:

static void writeInt32(std::vector<uint8_t>* msg, int32_t value)
{
    uint8_t const * array = reinterpret_cast<uint8_t const *>(&value);

    for (std::size_t i = 0; i != sizeof(value); ++i)
    {
        (*msg).push_back(array[i]);
    }
}

How can I improve this?


texts: Finding the profile name for a join in my Facebook auth backend

texts:
I've written a project for handling various Facebook things and I ran into the issue where one project named the users profile Profile while normally they would be named UserProfile.  When I was checking if the FacebookUser model was related to a User, I could just User.objects.get(userprofile__facebook=facebook_user) so I come up with a way to get the name, but it seems pretty ugly. Is there a cleaner way?

from django.conf import settings
from django.contrib.auth.models import User
from better_facebook.models import FacebookUser

# Get the name of the AUTH profile so that we can check if the user
# has a relationship with facebook. Is there a neater way of doing this?
_lowercase_profile_name = settings.AUTH_PROFILE_MODULE.split(".")[1].lower()
_facebook_relation = '{0}__facebook'.format(_lowercase_profile_name)

class FacebookBackend(object):
    """
    Authenticate against a facebook_user object.
    """
    def authenticate(self, facebook_user):
        assert(isinstance(facebook_user, FacebookUser))
        try:
            return User.objects.get(**{_facebook_relation: facebook_user})
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None


texts: Best syntax for executing an action between each loop iteration.

texts:
The question of the cleanest way to write a loop that executes some action between each iteration has always interested me.

In a sense, what is the best way in c/c++ to implement this fictional construct:

for (...) {
} between {
}

Using such a construct you could trivially implement string join(): (pseudocode)

result = "";
foreach ( item : input ) {
    result += str(item);
} between {
    result += sep;
}

I have looked through some popular code libraries to see how these types of loops are implemented, and there are some common strategies:

move the "between" code into an "if (!first/last iteration)" inside the loop.

This is the go-to method when the index/iterator/result freely stores the notion of first/last iteration (such as checks for values of 0, .empty(), NULL etc).

transform the "loop body" into a function and call it from two places: before and during the loop, and change the loop to skip the first element. (minor code duplication)

This is the go-to method when the "loop body" is a single function call

Neither of these is a completely generalized solution, and while its only a few lines + a state variable, I'm trying to find an ideal solution.

Priorities:

No needless source code duplication (but willing to accept binary code duplication)
Efficiency
Clear semantics
Trivially usable (aka simple syntax, few library requirements)


texts:
Indexing a book. Write a program that reads in a text file from
  standard input and compiles an alphabetical index of which words
  appear on which lines, as in the following input. Ignore case and
  punctuation. For each word maintain a list of location on which it
  appears. Try to use HashTable  and/or HashMap class (of java.util).

I have used a HashMap to store the line numbers for each word where it appears. Can this program be made better?

Index.java

package java_assignments.beg_assignment5;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Index {
    public Index(Readable text) {
        Scanner sc = new Scanner(text);
        occurences = new HashMap<String, ArrayList<Integer>>();

        int lineNo = 1;
        try {
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                String[] words = line.split("\\W+");
                for (String word : words) {
                    word = word.toLowerCase();
                    ArrayList<Integer> list = occurences.get(word);
                    if (list == null) {
                        list = new ArrayList<>();
                        list.add(lineNo);
                    } else {
                        list.add(lineNo);
                    }
                    occurences.put(word, list);
                }
                lineNo++;
            }
        } finally {
            sc.close();
        }
    }

    public String toString() {
        return occurences.toString();
    }

    private Map<String, ArrayList<Integer>> occurences;
}

BookIndexer.java

package java_assignments.beg_assignment5;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;

public class BookIndexer {
    public static void main(String[] args) {
        try {
            BufferedReader br;
            if (args.length == 0) {
                br = new BufferedReader(new InputStreamReader(System.in));
            } else {
                br = new BufferedReader(new FileReader(args[0]));
            }
            String index_str = new Index(br).toString();
            System.out.println(index_str);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}


texts:
I have to construct a URL string from smaller substrings. I'll usually have a resource url, an endpoint, a query, but you can imagine even more parts in creating a full URL.

If, for example, I have this resource URL: http://foo.com, this endpoint: bar/v1, and this query: q?var1=33,var2='abc', I expect the final URL to be:

http://foo.com/bar/v1/q?var1=33,var2='abc'

If the strings are formatted following a simple convention (for example, only have leading slashes on a substring) I could simply concatenate them together. The problem however is that these strings will be given as arguments to some library function calls, and hence it is very probable that some library users will miss the convention. It's so easy to add a trailing '/' or omit a leading '/'. So I do not want to impose a convention on this. Instead, I prefer to check and sanitise the arguments. I thought that urllib.parse.urljoin() would serve my purpose, but it does not. So I wrote a simple little method:

def slash_join(*args):
    '''
    Joins a set of strings with a slash (/) between them. Useful for creating URLs.
    If the strings already have a trailing or leading slash, it is ignored.
    Note that the python's urllib.parse.urljoin() does not offer this functionality.
    '''
    stripped_strings = []
    # strip any leading or trailing slashes
    for a in args:
        if a[0] == '/': start = 1
        else:           start = 0
        if a[-1] =='/':
            stripped_strings.append(a[start:-1])
        else:
            stripped_strings.append(a[start:])

    return '/'.join(stripped_strings)

Usage

>>> slash_join('http://foo.bar/', '/path/', '/query')
>>> 'http://foo.bar/path/query'

>>> slash_join('http://foo.bar', 'path', 'query')
>>> 'http://foo.bar/path/query'

>>> slash_join('http://foo.bar', 'path/', 'query/')
>>> 'http://foo.bar/path/query'

It works fine, but I was wondering if there is a more pythonic way of expressing this, or if I indeed missed a standard library method call that could have helped me.


texts: String parsing and saving ipaddress to file in Java

texts:
Following function will parse string resp, which will be like shown in following example. I will get an IP address in the form of a hexadecimal string like "C0A2AA32" and I need to convert that string and save it to a file.

Example of resp: "This is just a string with ip="2342A022" now I need to parse it"

void WritePublicIPAddressToFile(String resp)
{
    //find string in response
    String stringToFind = "ip=";

    //get index of stringToFind
    int indexOfIP = resp.indexOf(stringToFind);

    String newString = "";

    //find exact ip address which will be after = in stringToFind
    for(int i = indexOfIP; i<resp.length(); i++)
    {
        while(resp.charAt(i++) != '\"');

        while(resp.charAt(i) != '\"')
        {
            newString += resp.charAt(i++);
        }

        break;
    }

    int lenNewString = newString.length();
    String newIPAddress = "";

    //get two bytes from hex string and convert to ipaddress
    if(lenNewString == 8) //lenth of ipaddress raw data should be 8
    {
        long l;
        for(int i = 0;i<lenNewString;i+=2)
        {
             l = Long.parseLong(String.format("%c%c", newString.charAt(i),newString.charAt(i+1)),16);
             newIPAddress += String.format("%d.", l);
        }
    }

    StringBuilder sb = new StringBuilder(newIPAddress);
    sb.deleteCharAt(sb.length() - 1);//remvoe last '.' in ipaddress

    //final ipaddress to save in file
    newIPAddress = stringToFind + "\"" + sb.toString() + "\"";

    //write IP Address to file

    File file = new File("SomeFilePath.txt");
    FileWriter fileWriter;

    try {

        fileWriter = new FileWriter(file);
        fileWriter.write(newIPAddress);

        fileWriter.flush();
        fileWriter.close();

    } catch (IOException e2) {

        e2.printStackTrace();

    }
}


texts: Generate Random String and Writing to File

texts:
my task is to generate random strings and store in a file till the size of file is less than 10MB. My approach towards this problem is as follows.

import java.io.File;
import java.io.FileWriter;

public class Application {
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        File file = new File("Hello.txt");
        file.createNewFile();
        FileWriter writer = new FileWriter(file);

        while (file.length() <= 1e+7) {
            writer.write(Generator.generateRandomString(12, Generator.Mode.ALPHANUMERIC));
            writer.write("\n");
            writer.write(Generator.generateRandomString(12, Generator.Mode.NUMERIC));
            writer.write("\n");
            writer.write(Generator.generateRandomString(12, Generator.Mode.ALPHA));
            writer.write("\n");
        }
        writer.flush();
        writer.close();
        long end = System.currentTimeMillis();
        System.out.println((end - start) / 1000f + " seconds");
    }
}

It takes about 100.495 seconds to complete on my i3 processor with 4GB of RAM. So my question is, how to improve this performance? Why is the performance so poor? Is there any another workaround for this?


texts: Percentage of questions that are unanswered or answered

texts:
I put together this simple query which calculates the total percentage of answered questions and unanswered questions. The formulas used to calculate these are shown below:

$$
\text{Answered Percentage} = 100 - \left(\frac{\text{Unanswered}}{\text{Answered}} \times 100\right) \\
\text{Unanswered Percentage} = \frac{\text{Unanswered}}{\text{Answered}} \times 100
$$

Finally, here's the source:

DECLARE @TotalQuestions DECIMAL = (
  SELECT COUNT(*) FROM Posts
);

DECLARE @UnansweredQuestions DECIMAL = (
  SELECT COUNT(*) FROM Posts WHERE AnswerCount = 0
);

-- The percentage of un-answered questions. Calculated
-- using this:
  -- (Unanswered Questions / Total Site Questions) * 100
SELECT
  (@UnansweredQuestions / @TotalQuestions) * 100.0
AS [Percentage Of Unanswered Questions];

-- The percentage of answered questions. Calculated
-- using this:
  -- 100 - ((Unanswered Questions / Total Site Questions) * 100)
SELECT
  100 - ((@UnansweredQuestions / @TotalQuestions) * 100.0)
AS [Perentage Of Answered Questions];


texts: Fetching files or directories in a given directory

texts:
This is a self-teaching implementation to get files for a given directory in order to simplify os.Walk in Go (avoid to pass a func for recursively walking across the files and directories).

I'm pretty new to the language and feel there is already something wrong with
the way the structure ""implements"" the interface. I feel that it should not be by value but rather by reference in order to avoid redundant copies, should it?

package main

import (
    "os"
    "fmt"
    "path/filepath"
    "time"
)

type FileDetail interface {
    Path() string
    Info() os.FileInfo
}

type fileDetail struct{
    path string
    info os.FileInfo
}

func (detail fileDetail) Path() string {
    return detail.path
}

func (detail *ileDetail) Info() os.FileInfo {
    return detail.info
}

func GetFiles(path string) []FileDetail {
    var details []FileDetail

    walkFunc := func (filePath string, fileInfo os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if !fileInfo.IsDir() {
            var detail FileDetail = fileDetail{path: filePath, info: fileInfo}
            details = append(details, detail)
        }
        return nil
    }

    filepath.Walk(path, walkFunc)

    return details
}

func GetDirectories(path string) []FileDetail {
    var details []FileDetail

    walkFunc := func (filePath string, fileInfo os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if fileInfo.IsDir() {
            var detail FileDetail = fileDetail{path: filePath, info: fileInfo}
            details = append(details, detail)
        }
        return nil
    }

    filepath.Walk(path, walkFunc)

    return details
}

func main() {
    sandBoxDirectory := "F:/Perforce/eperret/XLC/R6Code/framework/source/scimitar/onlinemodule/Sandbox"

    time.Now()
    files := GetFiles(sandBoxDirectory)

    for index, file := range files {
        fileInfo := file.Info()
        fmt.Println(index, file.Path())
        fmt.Println(index, fileInfo.Name(), fileInfo.Size())
    }
}


texts: Python graphene-graphql, are global constants for SQL queries a good idea?

texts:
For python 3.6.5 using graphene-graphql and mysql-connector

Context:
I wrote an API using graphene, a python graphQL implementation, this is actually my first time using the graphQL specification so I'm looking to improve my code implementation for the resolvers using a MySQL database.

As you may know, GraphQL isn't tied to any specific database or storage engine so it specifies a resolve method, where you "resolve" for a field in your Type. eg. User has a field name, so the resolve method would be how you get that name.

All my types are in a package: mytypes with modules for each type, and they all follow the same styling as the following code example.

Code:
Please note how the last two functions are different implementations I've tried, more on this on my concerns down below.

import graphene

from database.connection import request

from mytypes.user import User
from mytypes.format import Format

_STUDENT_ID   = 'SELECT student_id FROM Rubrics WHERE id = %s'
_EVALUATOR_ID = 'SELECT evaluator_id FROM Rubrics WHERE id = %s'
_PROJECT_NAME = 'SELECT project_name FROM Rubrics WHERE id = %s'

class Rubric(graphene.ObjectType):
    uid            = graphene.ID()
    evaluator      = graphene.Field(User)
    student        = graphene.Field(User)
    rubricFormat   = graphene.Field(Format)
    projectName    = graphene.String()
    evaluationDate = graphene.Date()
    isPublic       = graphene.Boolean()

    def resolve_evaluator(self, info):
        evaluator_id = request(_EVALUATOR_ID, self.uid)
        return User(uid=evaluator_id)

    def resolve_student(self, info):
        student_id = request(_STUDENT_ID, self.uid)
        return User(uid=student_id)

   def resolve_rubricFormat(self, info):
       request = 'SELECT format_id FROM Rubrics WHERE id = %s'
       format_id = make(request, self.uid)
       return Format(uid=format_id)

    def resolve_isPublic(self, info):
        return rubric.is_public(self.uid)

Concerns:

Readability

My first concern is about readability, I'm trying to follow the PEP 8 styling for Python code which states that I shouldn't use or should avoid

  More than one space around an assignment (or other) operator to align it with another.

Which I do when defining my fields (uid, evaluator, student, etc), but this way it makes scanning it better in my opinion.

Resolve Implementation

As for the two methods I mentioned, first for resolve_rubricFormat I like the way make(request, self.uid) was read, where "make" was the same request imported as make but I realized I was just over-complicating.

Then, for resolve_isPublic I was delegating the data fetching to a package resolvers that had modules for every type and had all the logic there, but switching between both the Type and its resolvers/gets at the other package was tiring not to mention the original resolve methods would lose their significance since I was calling another method that was doing what the original resolve was intended for.

Global Variables

So I switched to global variables where I place the actual SQL query and use it as request(_WHATEVER, id) eg. request(_PROJECT_NAME, self.uid) would return the project name for the specified id, and since its on a module level its understood we are talking about the Rubric id.

But, I'm not sure if this is a good idea, what are your thoughts on this, any way to do it better?


texts:
I have a simple bisection method solver that I was told it has some problems in design and I need my code to be reviewed, so I was hoping for someone to give me guideline on how to improve my code.

It starts with a delegate:

 public delegate double MyFun (double x) ;

A class to add functions:

     class functions
{
    public static double fun1(double x) => Math.Pow(x,2) - 3;
    public static double fun2(double x) => 5* Math.Pow(x, 3) - 2* Math.Pow(x, 2) + 3 * x - 2;
    public static double fun3(double x) => 2 * Math.Sqrt(x) ;
}

A class that has a function that solves the equation. It has a function that takes 4 input parameters: delegate, start point, end point, guess of solution.

class Bisection
{

    public static double Bisection_method (MyFun fun , double start , double end , double? guess)
    {
        if ( fun(start) * fun(end) > 0 )
        {
            Console.WriteLine("wrong Entry");
            return -1;
        }
        if (fun(start) == 0)
        {
          return start;
        }

        double avg,tolerance,sign;

        avg = (guess.HasValue) ? guess.Value : ( (start + end) / 2 );
        do
        {
            tolerance = Math.Abs ( fun(end) - fun(start) );

            sign = fun(start) * fun(avg);
            if (sign < 0)
                end = avg;
            else if (sign > 0)
                start = avg;

            avg = (start + end) / 2;
        }
        while ( tolerance > 0.0001 );

        return end;
    }
}

Then the main method:

class Program
{
    static void Main(string[] args)
    {
        MyFun fun1 = functions.fun1;

        double start = 0;
        double end = 500;
        double guess = 10;

        double answer = Bisection.Bisection_method(fun1, start, end, guess);
        Console.WriteLine($"The Root = {answer}");
    }
}

I was hoping for someone to help me how to improve this simple code design and there is also some cases that I need to handle.


texts: Code that finds the largest palindrome from two three-digit factors

texts:
My code is really ugly, but I don't know how to make it better.

#include "stdafx.h"
#include <iostream>
#include <math.h>

using namespace std;

bool palindromeTest(double numberVectorAddition){//tests if the factors of the palindrome are both below 3 digits each.
    double p = numberVectorAddition;
    double i = 999;
    double c;
    for (;; i--){
        if (fmod(p, i) != 0)
            continue;
        if (fmod(p, i) == 0)
            c = p / i;
        if (1000 <= c){
            cout << "One of the factors is too high. Looking for next largest palindrome..." << endl;
            cout << endl;
            return false;
            }
        else if (c <= 1000){
        cout << "Factors of the number both below 1000 are " << i << " and " << c;
        return true;
        }
    }
}

void nLargestPalindrome(double number){
    int i = 5; //subtract "1" because array starts at zero
    int intermediate = i; //intermediate value - equal to the array index;
    double *decimalDigit = new double[i + 1];
        while (0 <= i){ //acquire digits of number
            decimalDigit[i] = (number - fmod(number, pow(10, i))) / pow(10, i);
            cout << "Value of digit place " << i << " is " << decimalDigit[i] << endl;
            number = fmod(number, pow(10, i));
            i--;
        }
        for (int q = 0; q < 100; q++){ //decreases size of palindrome, and also tests after the decrease.
            double numberVectorAddition = pow(10, 5)*decimalDigit[0] + pow(10, 4)*decimalDigit[1] + pow(10, 3)*decimalDigit[2] + pow(10, 2)*decimalDigit[3] + pow(10, 1)*decimalDigit[4] + decimalDigit[5];
            cout << decimalDigit[0] << decimalDigit[1] << decimalDigit[2] << decimalDigit[3] << decimalDigit[4] << decimalDigit[5] << '\t';
            cout << numberVectorAddition << endl;
            if (palindromeTest(numberVectorAddition))
                break;
            decimalDigit[2]--;
            decimalDigit[3]--;
                if (decimalDigit[2] == 0){
                    numberVectorAddition = pow(10, 5)*decimalDigit[0] + pow(10, 4)*decimalDigit[1] + pow(10, 3)*decimalDigit[2] + pow(10, 2)*decimalDigit[3] + pow(10, 1)*decimalDigit[4] + decimalDigit[5];
                    cout << decimalDigit[0] << decimalDigit[1] << decimalDigit[2] << decimalDigit[3] << decimalDigit[4] << decimalDigit[5] << '\t';
                    cout << numberVectorAddition << endl;
                    if(palindromeTest(numberVectorAddition))
                        break;
                        if ((decimalDigit[1] == 0) && (decimalDigit[2] == 0)){
                            decimalDigit[1] = 9;
                            decimalDigit[4] = 9;
                            decimalDigit[2] = 9;
                            decimalDigit[3] = 9;
                            decimalDigit[0]--;
                            decimalDigit[5]--;
                            continue;
                        }
                    decimalDigit[2] = 9;
                    decimalDigit[3] = 9;
                    decimalDigit[1]--;
                    decimalDigit[4]--;
                }
        }
    delete decimalDigit;
}

int main(){
    double n = 997799; //997799 is equal to 999*999 - 2; palindrome is smaller.
    nLargestPalindrome(n); //finds the largest palindrome below "n" that has both factors of three digits.
    cin.get(); //stops the command window from closing prematurely
}


texts: Remake of factoring/prime factorization calculator

texts:
Background info on factoring and prime factorization.

I've remade this program from my first attempt, and I'm sure it can still be improved.  My questions:

These calculations should only be done with positive integers.  Would something like templates help keep this type-safe?  What about throwing an exception?
Is this an effective way to use the typedefs?  Only the classes need them, so it seems better to qualify them with each class rather than a namespace.
Can both calculate()s be better optimized, considering they perform numerous divisions?
I'm not quite liking the call to calculate() in both display()s, even though there are no data member changes.  Is this still okay?  It doesn't quite make sense to perform the calculations in the constructor, and calculate() should still be private.

Factors.h

#ifndef FACTORS_H
#define FACTORS_H

#include <cstdint>
#include <map>

class Factors
{
private:
    typedef std::map<std::uint64_t, std::uint64_t> FactorsList;
    std::uint64_t integer;
    FactorsList calculate() const;

public:
    Factors(std::uint64_t);
    void display() const;
};

#endif

Factors.cpp

#include "Factors.h"
#include <cmath>
#include <iostream>

Factors::Factors(std::uint64_t i) : integer(i) {}

Factors::FactorsList Factors::calculate() const
{
    float sqrtInt = std::sqrt(static_cast<float>(integer));
    FactorsList factors;

    for (std::uint64_t i = 1; i <= sqrtInt; ++i)
    {
        if (integer % i == 0)
        {
            factors[i] = integer / i;
        }
    }

    return factors;
}

void Factors::display() const
{
    FactorsList factors = calculate();

    for (auto iter = factors.cbegin(); iter != factors.cend(); ++iter)
    {
        std::cout << iter->first << " x " << iter->second << "\n";
    }
}

Primes.h

#ifndef PRIMES_H
#define PRIMES_H

#include <cstdint>
#include <map>

class Primes
{
private:
    typedef std::map<std::uint64_t, std::uint64_t> PrimesList;
    std::uint64_t integer;
    PrimesList calculate() const;

public:
    Primes(std::uint64_t);
    void display() const;
};

#endif

Primes.cpp

#include "Primes.h"
#include <iostream>

Primes::Primes(std::uint64_t i) : integer(i) {}

Primes::PrimesList Primes::calculate() const
{
    std::uint64_t intCopy = integer;
    std::uint64_t divisor = 2;
    PrimesList primes;

    while (intCopy % divisor == 0)
    {
        intCopy /= divisor;
        primes[divisor]++;
    }

    for (divisor = 3; intCopy > 1; divisor += 2)
    {
        while (intCopy % divisor == 0)
        {
            intCopy /= divisor;
            primes[divisor]++;
        }
    }

    return primes;
}

void Primes::display() const
{
    PrimesList primes = calculate();

    for (auto iter = primes.cbegin(); iter != primes.cend(); ++iter)
    {
        if (iter != primes.cbegin()) std::cout << " x ";
        std::cout << iter->first;
        if (iter->second > 1) std::cout << '^' << iter->second;
    }
}


texts: Rotating an Image using own algorithm in python

texts:
For an uni assignment I have been giving the task of making my own rotating algorithm in python. This is my code so far.

import cv2
import math
import numpy as np

class rotator:

    angle = 20.0
    x = 330
    y = 330

    radians = float(angle*(math.pi/180))
    img = cv2.imread('FNAF.png',0)
    width,height = img.shape

    def showImg(name, self):
        cv2.imshow(name, self.img)
        self.img = np.pad(self.img, (self.height) ,'constant', constant_values=0)
        self.width,self.height = self.img.shape

    def printWH(self):
        print(self.width)
        print(self.height)

    def rotate(self):
        emptyF = np.zeros((self.width,self.height),dtype="uint8")
        emptyB = np.zeros((self.width,self.height),dtype="uint8")
        emptyBB = np.zeros((self.width,self.height),dtype="uint8")

        for i in range(self.width):
            for j in range(self.height):
                temp = self.img[i,j]
                #forward mapping
                xf = (i-self.x)*math.cos(self.radians)-(j-self.y)*math.sin(self.radians)+self.x
                yf = (i-self.x)*math.sin(self.radians)+(j-self.y)*math.cos(self.radians)+self.x
                #backward mapping should change the forward mapping to the original image
                xbb = (i-self.x)*math.cos(self.radians)+(j-self.y)*math.sin(self.radians)+self.x
                ybb = -(i-self.x)*math.sin(self.radians)+(j-self.y)*math.cos(self.radians)+self.x
                xbb = int(xbb)
                ybb = int(ybb)
                if xf < 660 and yf < 660 and xf>0 and yf > 0:
                    emptyF[int(xf),int(yf)] = temp
                else:
                    pass
                if xbb < 660 and ybb < 660 and xbb>0 and ybb > 0:
                    emptyBB[(xbb),(ybb)] = temp
                else:
                    pass
        cv2.imshow('Forward', emptyF)
        cv2.imshow('Backward', emptyBB)
def main():
    rotator.showImg('normal', rotator)
    rotator.printWH(rotator)
    rotator.rotate(rotator)
    cv2.waitKey(0)
    cv2.destroyAllWindows

if __name__ == '__main__':
    main()

Is there any way to improve this code or my algorithm? Any advise would be awesome.

NB. I also hav a problem with my backwards mapping. The output image has a lot of small black dots. Any suggestions to what that might be?

Please let me know.


texts:
I am wondering if it's possible to avoid looping. I want to make the function faster. The function is to find how many times a particular value is lower in the overall data. For example:

Value <- c(0,10,5,1,0,0,11,0,0,7,3,2,5) # length =13

The 1st value is 0 and 0 is NOT lower in any of the values. Therefore the value I would like to return from the function would be 0.

Something like this:

sum(Values < 0)
0

The 2nd value is 10:

sum(Values < 10)
11

I make a function something like below:

fun_num <- function(Value){
  gg <- vector()
  for (i in seq_along(Value)){
    x <- Value[i]
    y <- sum(Value < x)
    gg[i] <- y
  }
  return(gg)
}

Applying the function:

fun_num(Value)

[1]  0 11  8  5  0  0 12  0  0 10  7  6  8

Just wondering, is there a way to speed this function up using sapply and avoid using for loop?


texts: Receive a list of names and return a list of users - HackerRank test

texts:
So, few months ago I did a HackerRank test for a company. The problem was to create a function which receive a list of names and returns a list of unique usernames. For example:

For the list of names = ['john', 'john', 'tom', 'john']
The function must return: = ['john', 'john1', 'tom', 'john2']

My code was:

def username_system(u, memo={}, users=[]):
    copy_u = u.copy()
    try:
        name = copy_u[0]
    except IndexError:
        return users
    if name in memo.keys():
        memo[name] += 1
        username = name + str(memo[name])
        users.append(username)
        copy_u.remove(name)
        return username_system(copy_u, memo, users)
    else:
        username = name
        users.append(username)
        memo.update({name: 0})
        copy_u.remove(name)
        return username_system(copy_u, memo, users)
    return users

I'd like to know,  what could I improve in this code? I used memoization to make it faster. Also, I think this code is in O(n), but I'm not sure. Is that right?


texts: Monitored parallel mapping across a Pandas dataframe

texts:
This code maps a function over a dataset in parallel in a monitored fashion, and returns the result in the variable out.

import pandas as pd
import numpy as np
from tqdm import tqdm, trange
from joblib import Parallel, delayed
import multiprocessing
import math

n_jobs = multiprocessing.cpu_count()
df = pd.DataFrame(np.random.randn(10000, 200))
chunk_size = 32
n_chunks = min(len(df), int(math.ceil(len(df) / chunk_size)))

def func(x): # do something
    return x+1

out = Parallel(n_jobs=n_jobs, verbose=0)(
            delayed(func)(
               df[i * chunk_size: (i + 1) * chunk_size]
             )
             for i in trange(n_chunks))

What are the pros and cons of this approach? Are there better approaches? What if I needed to map in-place?


texts:
Which of these names is better: time.getHours() or time.hours()? And why?

public class Time implements Serializable {
    private final int hours;
    private final int minutes;

    public static Time from(Calendar calendar) {
        int hoursIn24HourFormat = calendar.get(Calendar.HOUR_OF_DAY);
        int minutes = calendar.get(Calendar.MINUTE);
        return new Time(hoursIn24HourFormat, minutes);
    }

    public Time(int hours, int minutes) {
        this.hours = hours;
        this.minutes = minutes;
    }

    // or may be getHours() name is better?
    public int hours() {
        return hours;
    }

    // or may be getMinutes() name is better?
    public int minutes() {
        return minutes;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof Time)) {
            return false;
        }
        Time other = (Time) obj;
        return (hours == other.hours) &&
               (minutes == other.minutes);
    }

    @Override
    public int hashCode() {
        return toMinutesOfDay();
    }

    private int toMinutesOfDay() {
        return hours * 60 + minutes;
    }

    @Override
    public String toString() {
        return twoDigitString(hours) + ":" + twoDigitString(minutes);
    }

    private static String twoDigitString(int timeComponent) {
        return (timeComponent < 10)
                ? ("0" + timeComponent)
                : String.valueOf(timeComponent);
    }

    public boolean before(Time time) {
        return toMinutesOfDay() < time.toMinutesOfDay();
    }

    public boolean after(Time time) {
        return toMinutesOfDay() > time.toMinutesOfDay();
    }

    public boolean within(Time fromIncluded, Time toIncluded) {
        return (!fromIncluded.after(this)) && (!this.after(toIncluded));
    }
}


texts: Split all images over x amount of pages with $_GET

texts:
I would like to receive some feedback on the code I am currently using to display x amount of images on my website per
$success = true;
$page = array_key_exists('page', $_GET) ? $_GET['page'] : 1;

$all_pictures = glob('crossles/*.jpg');

$total_images = 0;
foreach ($all_pictures as $img_total) {
    $total_images++;
}

$images_per_page = 30;

$max_pages = ceil($total_images / $images_per_page);

if ($page <= -1) {
    $success = false;
}

if ($page > $max_pages) {
    $success = false;
}
if ($success === false) {
    echo "

No pictures to be displayed.

";
}

I know that $_GET is not the safest way of doing this but since it is only to retrieve images I don't think it is that big of an issue.
It would be nice if I could get some feedback to implement it to my code if needed.


texts:
I am integrating a system of perturbed phase oscillators. I define the system of equation and also the Jacobian matrix. I have to reshape the one dimensional vector of system state to a 2 dimensional vector then do the matrix production.

Is there any single-threaded way to make the program faster?

using dim1 = std::vector<double>;
using dim2 = std::vector<std::vector<double>>;

dim2 multiply_matrices(dim2 &A, dim2 &B)
{
    int r1 = A.size();
    int c1 = A[0].size();
    int r2 = B.size();
    int c2 = B[0].size();

    assert(c1==r2 && "bad dimension for matrix multiplication");

    dim2 mult(r1, dim1(c2));

    for (int i = 0; i < r1; ++i) {
        for (int j = 0; j < c2; ++j) {
            mult[i][j] = 0;
        }
    }

    // Multiplying matrix A and B and storing in array mult.
    for (int i = 0; i < r1; ++i) {
        for (int j = 0; j < c2; ++j) {
            for (int k = 0; k < c1; ++k) {
                mult[i][j] += A[i][k] * B[k][j];
            }
        }
    }

    return mult;
}

class kuramoto_exe
{
    vector<vector<double>> &adj;
    dim1 &omega;
    int kind;
    int N;
    double coupling;

public:
    kuramoto_exe (
        int N_, int kind_, double coupling_,
        dim1& omega_, dim2& adj_) : adj(adj_), omega(omega_),
            kind(kind_), coupling(coupling_), N(N_) { }

        void operator() (const dim1 &X, dim1& dXdt, const double /*t*/)
    {

        dim1 x(X.begin(), X.begin() + N); // initial condition

        // reshaping:every colomn is a vector (reshape order "F")
        dim2 Y(N, dim1(N));
        for (int j=0; j<N; j++)
            for (int i=0; i<N; i++)
                Y[i][j] = X[N*j+i+N];

        dim2 Jac(N, dim1(N));

        // definition of unperturbed model
        for (int i=0; i<N; i++) {
            double sumj =0.0;
            for (int j=0; j<N; j++) {
                if ((i != j) && (adj[i][j] > 1e-8))
                        sumj += adj[i][j] * sin(x[j]-x[i]);

                dXdt[i] =  omega[i]+ coupling * sumj;
            }
        }
        // calculation of the Jacobian
        for (int i=0; i<N; i++) {
            for(int j=0; j<N; j++) {
                if (i!=j)
                    Jac[i][j] = coupling * adj[i][j] * cos(x[j] - x[i]);
                else {
                    double sumj = 0.0;
                    for (int jj=0; jj<N; jj++) {
                        if (jj!=i)
                            sumj += adj[i][jj] * cos(x[jj] - x[i]);
                    }
                    Jac[i][j] = -1.0 * coupling * sumj;
                }
            }
        }

        dim2 M = multiply_matrices(Jac, Y);

        for (int j=0; j<N; j++)
            for (int i=0; i<N; i++)
                dXdt[N*j+i+N] = M[i][j]; // revese of reshape order "F"
    }
};


texts:
Introduction:

The following script contains code that performs what I would usually do when staring a new scene (add lights, camera, objects). The script will serve as a starting point for most of my future scripts.

In the future, I might use more complex materials, create animations, or use the built-in physics simulator (for example, rigid body, fluid, smoke).

This is what the script below renders:

The command to run the code is blender --background --python-exit-code 1 --python monkey.py. The code has been tested on Blender 2.81a (released December 5, 2019).

Here are some of my concerns:

There are quite a few lines which use bpy.ops. bpy.ops should be avoided.
Clearing all objects in the beginning with select_all and then delete looks like a workaround to me. There might be a way to start a scene without the default cube, light, and camera.

monkey.py

import bpy
import shutil
import os
import time

def add_light(location, light_type='POINT', color=(1.00, 1.00, 1.00), energy=1000.00):
    bpy.ops.object.add(type='LIGHT', location=location)
    obj = bpy.context.object

    obj.data.type = light_type
    obj.data.color = color
    obj.data.energy = energy

def set_smooth(obj, level=None, smooth=True):
    if level:
        modifier = obj.modifiers.new('Subsurf', 'SUBSURF')
        modifier.levels = level
        modifier.render_levels = level

    mesh = obj.data
    for p in mesh.polygons:
        p.use_smooth = smooth

def create_focal_point(location=(0.00, 0.00, 0.00)):
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.10, location=location)
    focal_point = bpy.context.object
    focal_point.hide_render = True
    return focal_point

def set_focal_point(camera, focal_point):
    bpy.context.view_layer.objects.active = camera
    bpy.ops.object.constraint_add(type='TRACK_TO')
    camera.constraints['Track To'].target = focal_point
    camera.constraints['Track To'].track_axis = 'TRACK_NEGATIVE_Z'
    camera.constraints['Track To'].up_axis = 'UP_Y'

def create_monkey(origin=(0.00, 0.00, 0.00)):
    bpy.ops.mesh.primitive_monkey_add(location=origin)
    obj = bpy.context.object
    return obj

if __name__ == '__main__':
    # Delete all objects
    bpy.ops.object.select_all(action='SELECT')
    bpy.ops.object.delete()

    main_object = create_monkey()

    yellow_rgba = (1.00, 1.00, 0.00, 1.00)

    mat = bpy.data.materials.new(name='yellow')
    mat.use_nodes = True
    mat.diffuse_color = yellow_rgba
    nodes = mat.node_tree.nodes

    nodes.clear()
    node_material_output = nodes.new(type='ShaderNodeOutputMaterial')

    node_diffuse = nodes.new(type='ShaderNodeBsdfDiffuse')
    node_diffuse.name = 'Yellow Diffuse'
    node_diffuse.inputs['Color'].default_value = yellow_rgba

    input = node_material_output.inputs['Surface']
    output = node_diffuse.outputs['BSDF']
    mat.node_tree.links.new(input, output)

    main_object = bpy.context.active_object
    main_object.active_material = mat

    set_smooth(main_object, level=5)

    add_light(location=(5.00, -7.50, 5.00))

    bpy.ops.object.camera_add(location=(0.00, -5.00, 0.00))
    main_camera = bpy.context.object
    bpy.context.scene.camera = main_camera

    focal_point = create_focal_point(main_object.location)
    set_focal_point(main_camera, focal_point)

    bpy.context.scene.render.engine = 'CYCLES'
    bpy.context.scene.cycles.samples = 50

    bpy.context.scene.render.tile_x = 256
    bpy.context.scene.render.tile_y = 256

    bpy.context.scene.render.resolution_x = 600
    bpy.context.scene.render.resolution_y = 600

    bpy.context.scene.render.resolution_percentage = 100

    bpy.context.scene.render.image_settings.compression = 100

    base_filename = time.strftime('%Y %m %d - %H %M %S - ') + os.path.basename(__file__)
    base_filename_no_extension = os.path.splitext(base_filename)[0]
    shutil.copy(__file__, base_filename)

    bpy.ops.wm.save_as_mainfile(filepath=base_filename_no_extension+'.blend')

    bpy.context.scene.render.filepath = base_filename_no_extension+'.png'
    bpy.ops.render.render(write_still=True)


texts: Is there a cleaner way of building a list of the previous, next months than this?

texts:
At first I tried using a timedelta but it doesn't accept months as an argument, so my next working example is this:

from datetime import datetime
current_date = datetime.now()

months = []
for month_adjust in range(2, -3, -1): # Order by new to old.
    # If our months are out of bounds we need to change year.
    if current_date.month + month_adjust <= 0:
        year = current_date.year - 1
    elif current_date.month + month_adjust > 12:
        year = current_date.year + 1
    else:
        year = current_date.year
    # Keep the months in bounds.
    month = (current_date.month + month_adjust) % 12
    if month == 0: month = 12
    months.append(current_date.replace(year, month=month, day=1))

Is there a cleaner way?


texts:
I have a multidimensional array of house properties:

$array = array(
    array('apn' => 345345353, 'sqft' => 1121, 'address' => '12 Lincoln Ave.'),
    array('apn' => 345345351, 'sqft' => 1643, 'address' => '13 Lincoln Ave.'),
    array('apn' => 345345352, 'sqft' => 1222, 'address' => '14 Lincoln Ave.')
    array('apn' => 345345358, 'sqft' => 1226, 'address' => '6 Olark Ave.')
    array('apn' => 345345345, 'sqft' => 1200, 'address' => '323 Pacific Ave.'),
    array('apn' => 345345342, 'sqft' => 1421, 'address' => '324 Pacific Ave.'),
    array('apn' => 345345347, 'sqft' => 1093, 'address' => '328 Pacific Ave.'),
);

What I want to create from it is an array with just the lowest and highest address for each street. If a street has only one address then it shouldn't show up in the array.

array('323 Pacific Ave.', '328 Pacific Ave.', '12 Lincoln Ave.', '14 Lincoln Ave.')

Currently I have the following function that works find but it is very verbose and I'm trying to figure out a simple way to sort by value in a multidimensional array.

function minMaxAddress($data) {
    $addressRanges = array();
    $streets = array();
    $numProperties = count($data);
    $i = 0;
    foreach ($data as $key => $listing) {
        $address = $listing['address'];
        $street = getStreetName($address);
        if ($i == 0) {
          $addressRanges[] = $address;
        }
        else if ($street != end($streets)) {
          $addressRanges[] = $lastAddress;
          $addressRanges[] = $address;
        }
        if ($i == $numProperties - 1) {
            $addressRanges[] = $address;
        }
        $streets[] = $street;
        $lastAddress = $address;
        $i++;
    }
    $addressRanges = array_diff($addressRanges, array_diff_assoc($addressRanges, array_unique($addressRanges)));
    $addressRanges = array_values($addressRanges);
    return $addressRanges;
}


texts:
I reproduced my version of Abstract Factory Pattern in Java. I know it's redundant but can I get critical comments about my code. Is it really the classic implementation of the pattern or not?

/*
* The demonstration of Abstract Factory Pattern
*
* Here the 'DocumentFactory' creates documents of types
* 'Resume' or 'Letter' which are concrete classes responsible to
* create things like 'FancyResume' or 'CoverLetter'
*
* The example is inspired by Wikipedia documentation of Abstract
* Factory.
*/

interface letter{
    void print();
}

class CoverLetter implements letter{
    @Override
    public void print(){
        System.out.println("Cover letter printed");
    }
}

class FancyLetter implements letter{
    @Override
    public void print(){
        System.out.println("Fancy letter printed");
    }
}

interface resume{
    void process();
}

class CorporateResume implements resume{
    @Override
    public void process(){
        System.out.println("Corporate resume processed");
    }
}

class FancyResume implements resume{
    @Override
    public void process(){
        System.out.println("Fancy resume processed");
    }
}

//Create 'Concrete' factories
class LetterFactory{
    public letter getLetter(String type){
        switch(type){
            case "Fancy":
                return new FancyLetter();
            case "Cover":
                return new CoverLetter();
        }
        return null;
    }
}

class ResumeFactory{
    public resume getResume(String type){
        switch(type){
            case "Fancy":
                return new FancyResume();
            case "Corporate":
                return new CorporateResume();
        }
        return null;
    }
}

// create abstract factory
abstract class DocumentFactory{
    abstract LetterFactory letterFactory();
    abstract ResumeFactory resumeFactory();
}

class DocumentCreator extends DocumentFactory{
    @Override
    LetterFactory letterFactory(){
        return new LetterFactory();
    }

    @Override
    ResumeFactory resumeFactory(){
        return new ResumeFactory();
    }
}

class abstractfactory{
    public static void main(String args[]){
        DocumentCreator creator = new DocumentCreator();

        // create a fancy letter
        letter myLetter = creator.letterFactory().getLetter("Fancy");
        myLetter.print();

        // create a corporate resume
        resume myResume = creator.resumeFactory().getResume("Corporate");
        myResume.process();
    }
}


texts: HackerRank - Left Rotation in JavaScript

texts:
I'm looking to learn more about data structures, time complexity, and efficient algorithms. I have solved the Left Rotation Problem
on HackerRank using JavaScript. I am looking to see ways to optimize the time complexity. I feel like I have a lot to learn, as don't grok Big O.

function main() {
    const nd = readLine().split(' ')
    const numbers = parseInt(nd[0], 10)
    const rotations = parseInt(nd[1], 10)
    const arr = readLine().split(' ').map(aTemp => parseInt(aTemp, 10))
    const front = arr.slice(0, rotations)
    const back = arr.slice(rotations, numbers)
    const new_arr = back.concat(front)
    console.log(new_arr.join(' '))
}

I feel like this likely has bad time complexity, as under the hood, I believe the slice function uses a loop and has a time complexity of \$O(n)\$. In addition, I'm unsure of how JavaScript implements the merge from the concat method under the hood.


texts: Upload a photo with a unique name using PHP

texts:
I have written a script for basic uploading of a single image to a web server using PHP. This is an example that is intended for educational purposes in a basic PHP course. It does not take extensive consideration to security as it is not the focus.

Key points to focus on the review:

If the code comply with the PSR-1 and PSR-2 requirements
If the code can be more efficiently written.
Recommendations for presenting success/error messages. Errors are already in an array.

<?php
    // 1 MB = 1048576 bytes
    $max_file_size = 1048576;

    // Accepted file types
    $image_types = array('gif', 'jpg', 'png');

    // Folder for uploaded images
    $upload_dir = realpath(dirname(__FILE__)) . '/images/';

    // Error codes for file upload
    // See: http://www.php.net/manual/en/features.file-upload.errors.php
    $upload_errors = array(
        UPLOAD_ERR_OK         => 'No errors.',
        UPLOAD_ERR_INI_SIZE   => 'Larger than upload_max_filesize.',
        UPLOAD_ERR_FORM_SIZE  => 'Larger than form MAX_FILE_SIZE.',
        UPLOAD_ERR_PARTIAL    => 'Partial upload.',
        UPLOAD_ERR_NO_FILE    => 'No file.',
        UPLOAD_ERR_NO_TMP_DIR => 'No temporary directory.',
        UPLOAD_ERR_CANT_WRITE => 'Can not write to disk.',
        UPLOAD_ERR_EXTENSION  => 'File upload stopped by extension.'
    );

    // Checks form request method
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        // Return if no file has been submitted
        if (!isset($_FILES['photo'])) {
            return;
        }

        // Checks if image has been submitted
        if (isset($_FILES['photo'])) {

            // Creates array for containing errors
            $errors     = array();

            // Checks for errors in upload
            if ($_FILES['photo']['error'] > 0) {
                $error_message = $_FILES['file_upload']['error'];
                $errors[] = $upload_errors[$error_message];
            }

            // Declares file information
            $file_tmp    = $_FILES['photo']['tmp_name'];
            $file_name   = $_FILES['photo']['name'];
            $file_size   = $_FILES['photo']['size'];
            $file_sha1   = sha1_file($file_tmp);
            $file_ext    = pathinfo($file_name, PATHINFO_EXTENSION);

            // Creates unique name for uploaded file
            $target_name = $file_sha1 . '.' . $file_ext;

            // Checks if file is an image
            if (!getimagesize ($file_tmp)) {
                $errors[] = 'Ensure you are uploading an image.';
            }

            // Checks if image is a valid type
            if (!in_array($file_ext, $image_whitelist)) {
                $errors[] = 'Not a valid image. (.jpg, .png or .gif).';
            }

            // Checks if image exceed file size
            if ($file_size > $max_file_size) {
                $errors[] = 'Exceeded file size limit (1 MB).';
            }

            // Checks if file already exists
            if (file_exists($upload_dir . $target_name)) {
                $errors[] = 'File already exists.';
            }

            // Checks if there are any errors
            if (empty($errors)) {
                // Checks if upload file can be moved
                if (move_uploaded_file($file_tmp, $upload_dir . $target_name)) {
                    $success = "File uploaded successfully.";
                }
                else {
                    $errors[] = 'Error moving file to directory.';
                }
            }
        }
    }
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>send.php</title>
  </head>
  <body>
    <?php if(!empty($success)) { echo $success; } ?>
    <form action="send.php" method="post" enctype="multipart/form-data">
      Choose photo: <input type="file" name="photo">
      <input type="submit" name="submit" value="Submit">
    </form>
  </body>
</html>


texts:
I'm building an application that implements the A* algorithm to calculate a route between two rooms. I am trying to create a graph which the algorithm can operate on and I am not sure if this is the right way to do it.

Here's what I've done so far:

Vect2.java:

package myalgorithm;

public class Vect2 {

    private int x;
    private int y;

    public Vect2(int x,int y ){

        this.x = x;
        this.y = y;

        }

}

Node.java

package myalgorithm;

public class Node {

    Node parent;
    Vect2 vector;
    public int x;
    public int y;

    public double f;
    public double g;
    public double h;

    public Node( int x,int y,Node parent, double g,double h){

        this.x = x;
        this.y = y;
        this.parent= parent;
        this.g = g;
        this.h = h;
        this.f= this.g + this.h;

    }
}

NodeGraph.java

package myalgorithm;
import java.util.Arrays;

public class NodeGraph {

    Node a = new Node(88,623,null,0,0);
    Node b = new Node(727,627,null,0,0);
    Node c = new Node(723,93,null,0,0);
    Node d = new Node(90,92,null,0,0);
    Node e = new Node(94,349,null,0,0);
    Node f = new Node(397,358,null,0,0);
    Node g = new Node(722,339,null,0,0);
    Node[] arr = new Node[7];

public NodeGraph init(){

    arr[0]= a;
    arr[0]= b;
    arr[0]= c;
    arr[0]= d;
    arr[0]= e;
    arr[0]= f;
    arr[0]= g;

    return this;
}
public void createMatrx(){
boolean[][] matrix = new boolean[7][];
for (int i=0; i<matrix.length; i++) matrix[i] = new boolean[7];

int nodeA = Arrays.binarySearch(arr, a);
int nodeB = Arrays.binarySearch(arr, b);
int nodeC = Arrays.binarySearch(arr, c);
int nodeD = Arrays.binarySearch(arr, d);
int nodeE = Arrays.binarySearch(arr, e);
int nodeF = Arrays.binarySearch(arr, f);
int nodeG = Arrays.binarySearch(arr, g);

matrix[nodeA][nodeB] = true;
matrix[nodeA][nodeE] = true;
matrix[nodeB][nodeA] = true;
matrix[nodeB][nodeG] = true;
// A is connected to D
matrix[nodeC][nodeG] = true;
matrix[nodeC][nodeD] = true;
// B is connected to D
matrix[nodeD][nodeC] = true;
matrix[nodeD][nodeE] = true;
matrix[nodeE][nodeD] = true;
// C is connected to D
matrix[nodeE][nodeF] = true;
matrix[nodeE][nodeA] = true;
matrix[nodeF][nodeE] = true;
matrix[nodeE][nodeG] = true;

matrix[nodeG][nodeF] = true;
matrix[nodeE][nodeB] = true;
matrix[nodeE][nodeC] = true;

matrix[nodeD][nodeC] = true;
}
}


texts:
I am using the following method to validate if user has given any input or left an EditText empty. I am concerned about the return statement in particular, because my IDE keeps complaining about it.

Environment: Android Studio 1.0

public void clientsideauth() {

        if (TextUtils.isEmpty(edt_name.getText().toString().trim())) {
            onShake(edt_name, "Please enter a valid name");
            return;
        } else {
            name = edt_name.getText().toString().trim();
        }
        if (isValidEmail(edt_email.getText().toString().trim())) {
            email = edt_email.getText().toString().trim();
        } else {
            onShake(edt_email, "Please enter a valid email ID");
            return;
        }

        if (((edt_password.getText().length() < 6) || (TextUtils.isEmpty(edt_password.getText().toString().trim())))) {
            onShake(edt_password, "Password must be at least six characters long");
            return;
        } else {
            pwd = edt_password.getText().toString().trim();
        }

        if (TextUtils.isEmpty(edt_password1.getText().toString().trim())) {
            onShake(edt_password1, "Not valid");
            return;
        } else {
            pwd1 = edt_password1.getText().toString().trim();
        }

        if (pwd.equals(pwd1)) {
            startbackgroundtask("formBased");
        } else {
            onShake(edt_password, "Passwords do not match");
            onShake(edt_password1, "Passwords do not match");
            return;
        }
    }

The return type of the method is void, because I don't want any return from this, I only want to stop execution if validation fails. However my IDE complains about the last return statement in the last if-else construct. I am wondering if I should in fact change the return type from void to boolean and maintain an array value for each form field. Later on I can check if all the array values are true or not.

The above function gets called on the Submit button and is further processed to the server.


texts:
My implementation of generic Tree structure:

/**
 * Tree data structure
 */
public class Tree<T> {

    private T value;

    private Tree<T> parent;

    protected List<Tree<T>> children = Collections.emptyList();

    public Tree(T value) {
        this.value = value;
    }

    public Tree() {
    }

    /**
     * @return the value
     */
    public T getValue() {
        return value;
    }

    /**
     * @param value
     *            the value to set
     */
    public void setValue(T value) {
        this.value = value;
    }

    /**
     * Adds children
     *
     * @param children
     * @return this
     */
    public final Tree<T> addChildren(List<Tree<T>> newChildren) {

        if (children == Collections.EMPTY_LIST) {
            children = new ArrayList<>();
        }

        for (Tree<T> child : newChildren) {
            if (children.add(child)) {
                child.setParent(this);
            }
        }
        return this;
    }

    /**
     * Adds children
     *
     * @param children
     * @return this
     */
    @SafeVarargs
    public final Tree<T> addChildren(Tree<T>... children) {
        return addChildren(Arrays.asList(children));
    }

    /**
     * Removes children
     *
     * @param children
     * @return this
     */
    public final Tree<T> removeChildren(List<Tree<T>> children) {
        for (Tree<T> child : children) {
            if (this.children.remove(child)) {
                child.setParent(null);
            }
        }
        return this;
    }

    /**
     * Removes children
     *
     * @param children
     * @return this
     */
    @SafeVarargs
    public final Tree<T> removeChildren(Tree<T>... children) {
        return removeChildren(Arrays.asList(children));
    }

    /**
     * @return the parent
     */
    public Tree<T> getParent() {
        return parent;
    }

    /**
     * @param parent
     *            the parent to set
     */
    public void setParent(Tree<T> parent) {
        this.parent = parent;
    }

    /**
     * @return the tree root
     */
    public Tree<T> getRoot() {
        return parent == null ? this : parent.getRoot();
    }

    /**
     * @return children
     */
    public final List<Tree<T>> getChildren() {
        return children;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        buildString(sb, "", true);
        return sb.toString();
    }

    private void buildString(StringBuilder sb, String prefix, boolean isTail) {
        sb.append(prefix).append(isTail ? "└── " : "├── ").append(getValue()).append(System.lineSeparator());
        prefix += (isTail ? "    " : "│   ");

        for (int i = 0; i < children.size(); i++) {
            children.get(i).buildString(sb, prefix, (i == children.size() - 1));
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof Tree<?>))
            return false;

        Tree<?> other = (Tree<?>) obj;

        if (this.children.size() != other.children.size())
            return false;

        for (int i = 0; i < this.children.size(); i++) {
            if (!(children.get(i).equals(other.children.get(i))))
                return false;
        }

        return true;
    }

}

Any suggestions to make this better?


texts: Formatting 3 integers (hours, mins, secs) to `00:00:00`?

texts:
I have this at the moment, wondering if there's a cleaner way to do it or if this is already as compact as it gets.

 h = "%s" % str(h) if h >= 10 else "0%s" % str(h)
 m = "%s" % str(m) if m >= 10 else "0%s" % str(m)
 s = "%s" % str(s) if s >= 10 else "0%s" % str(s)
 print("{}:{}:{}".format(h, m, s))


texts:
I wrote this little script in PHP a bit ago. It takes a .csv file and outputs a .txt file with certain data arranged in a "psuedo-array" looking format. I recently started messing around with Ruby so I decided to redo it. It wound up essentially as an exact translation, though.

Is there a simpler / more Ruby way to do this?

require "csv"

class ArrayGenerator

    def initialize( file )
        @file = file
        open_csv
    end

    private
    def open_csv
        File.open("#{@file}" + "_output.txt", 'w') do |file|
            CSV.foreach(@file) do |row|
                lat = row[6]
                lon = row[7]
                img = "#{row[0]}".downcase
                part = "#{row[2]}"
                loc = "#{row[5]}"
                country = "#{row[4]}"
                focus =  "#{row[3]}"
                desc = "#{row[8]}"
                link = "#{row[9]}"

                file.write("[#{lat}, #{lon}, #{img}, #{part}, #{loc}, #{focus}, #{country}, #{desc}, #{link}],
")
            end
        end
    end
end

ARGV.each do |file|
    g = ArrayGenerator.new( file )
end


texts:
I'm new to Java programming and am really enjoying it. I made a bitshift program, but I think it's too long.

I expect the program to:

Let users input the number and degree to be shifted
Specify if it is a right or left shift
Restart the program if the user requires at the end
Ensure exceptions don't crash the program

import java.util.Scanner;
class BitShift{
    int a,b;
    String c;

    static int shiftNo(){
        Scanner sc=new Scanner(System.in);
        int x=sc.nextInt();
        return x;
    }

    static String shiftDir(){
        Scanner sc=new Scanner(System.in);
        String x=sc.nextLine();
        return x;
    }
    }

    class BitShiftObjects1 extends BitShift{

    public static void main(String []args){

        int answer;
        BitShift ob1=new BitShift();

    boolean isValue=false;
    while(isValue==false){
        try{
            System.out.println("Please enter number to be shifted");
            ob1.a=shiftNo();
            System.out.println("Please enter degree to be shifted");
            ob1.b=shiftNo();
            isValue=true;
        }
        catch(java.util.InputMismatchException e){
            System.out.println("ERROR:**Please Input Integer Number**");
            System.out.println("**Please enter from begining**");
            System.out.println("");
        }

    }

    isValue=false;
    while(isValue==false){

            System.out.println("Please enter r or l");
            ob1.c=shiftDir();

            if(ob1.c.equals("r") || ob1.c.equals("l"))
                isValue=true;
            else
                System.out.println("ERROR:**Please enter LOWERCASE r/l**");

        }

        if(ob1.c.equals("r")){
            answer=ob1.a >> ob1.b;
            System.out.println("Your Answer is : "+answer);
                }
        else{
            answer=ob1.a << ob1.b;
            System.out.println("Your Answer is : "+answer);
                    }

        System.out.println("");
        System.out.println("Do you want to enter a new data set??");
        System.out.println("Press y or n");

        isValue=false;
        while(isValue==false){
        ob1.c=shiftDir();

        if(ob1.c.equals("y")){
            System.out.println("**Reinitializing program**");
            isValue=true;
            main(args);
        }
        else if(ob1.c.equals("n"))
            isValue=true;
        else
            System.out.println("ERROR:**Please enter lowercase y or n**");
        }
    }
}


texts:
Here is my solution for CodeAbbey - Blackjack Counting

My code passes all tests on Code Abbey but I think I have some poor implementation specifically with my handling of the Aces in the score but otherwise I think I overall used good practices and design.

def calculate_player_hand(player_hand_input):
    """Return the score of a player hand"""
    # Variable to hold score for a hand
    total_player_hand_score = 0

    # Dictionary mapping cards to their score value
    card_values = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "T": 10, "J": 10, "K": 10, "Q": 10}

    # Find score of cards except Aces
    for card in player_hand_input:
        if card == "A":
            continue
        else:
            total_player_hand_score += card_values[card]

    # Return player_hand_score not including Ace card(s)
    return total_player_hand_score

# Return the total amount of Aces in a player's hand
def get_aces_count(player_hand_input):
    """Return the count of Aces"""
    return player_hand_input.count("A")

# Read in test cases
test_cases = int(input())

# List to hold all total scores
total_scores = []

# Iterate through test cases
for i in range(test_cases):

    # Read in player hand
    player_hand = input().split()

    # Variable to hold number of Aces in player hand
    player_score_without_aces = calculate_player_hand(player_hand)

    for j in range(get_aces_count(player_hand)):
        if 21 - player_score_without_aces < 11:
            player_score_without_aces += 1
        else:
            player_score_without_aces += 11

    # Rename variable since value of Aces were added
    total_player_score = player_score_without_aces

    # Add total score to total_scores list
    if total_player_score > 21:
        total_scores.append("Bust")
    else:
        total_scores.append(total_player_score)

# Output all total scores
for total_score in total_scores:
    print(total_score, end=" ")

Thank you.


texts:
I have some situations where I run async code inside class constructor:
1. Run async code that returns a response
I execute some async code that returns a response, then I apply then and catch inside class constructor:
class MyClass {

  constructor(
    someParameter,
    anotherParameter,
  ) {
    // Run async code that return a response
    someAsyncCode()
      .then( // do something with result of someAsyncCode )
      .catch( // do something if someAsyncCode goes wrong )
  }
}

2. Run async code that doesn't return a response
In some situations, the async code doesn't return anything, but I need to run it.
class MyClass {

  constructor(
    someParameter,
    anotherParameter,
  ) {
    // Run async code that doesn't return anything
    someAsyncCode()
  }

  async someAsyncCode() {
    const someAsyncResult = await something();
    // execute some other logic but not return anything
  }
}

Questions

Its a good or bad practice, execute some async code inside class constructor?
in the situation where you need to execute async code that does not return anything, it is necessary to execute then and catch?
what are the implications of executing asyn code without then and catch?


texts:
Just checking that this shuffling algorithm is suitable. Or maybe there could be improvements?

public static void shuffleArray(Object[] arr, Random rnd){
    int lastIndex = arr.length - 1;
    for (int i=0; i<=lastIndex; i++){
        int k = nextInt(i,lastIndex+1, rnd);
        Object a = arr[i];
        Object b = arr[k];
        arr[i] = b;
        arr[k] = a;
    }
}

//Returns an integer between start(inclusive) and end(exclusive) [start..end)
public static int nextInt ( int start, int end, Random rnd);


texts:
An anytime algorithm is an optimization algorithm that can be stopped at any time, and when it is stopped, it returns the best result that it found so far. I am trying to implement an anytime algorithm in Java.

To simulate the algorithm, I just select in each iteration a random number, and keep the smallest number found so far. When the algorithm is interrupted, it stops and returns the current smallest value.

Below there are two options to implement the anytime mechanism in the main()
method, one using a Thread directly and one using an ExecutorService.  Which of the two options is better? Is there a better option?

import java.util.concurrent.*;

public class Anytime {

    static double algorithm(long n) {
        double bestSoFar = Double.MAX_VALUE;
        for (int i=0; i<n; ++i) {
            Thread.yield();
            if (Thread.interrupted())
                break;
            bestSoFar = Math.min(bestSoFar, 1000000*Math.random());
        }
        return bestSoFar;
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Runnable task = () -> System.out.println("The result is "+algorithm(10000000));
        int timeInMillis = 1000;

        /* OPTION 1 */
        Thread t = new Thread(task);
        t.start();
        Thread.sleep(timeInMillis);
        t.interrupt();

        /* OPTION 2 */
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<?> future = executor.submit(task);
        try {
            future.get(timeInMillis, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            future.cancel(true);
        }
        executor.shutdown();
    }

}


texts:
I'm looking for a simple way of parsing complex text files into a pandas DataFrame. Below is a sample file, what I want the result to look like after parsing, and my current method.

Is there any way to make it more concise/faster/more pythonic/more readable?

I have also put this question on Stack Overflow. I eventually wrote a blog article to explain this to beginners.

Here is a sample file:

Sample text

A selection of students from Riverdale High and Hogwarts took part in a quiz. This is a record of their scores.

School = Riverdale High
Grade = 1
Student number, Name
0, Phoebe
1, Rachel

Student number, Score
0, 3
1, 7

Grade = 2
Student number, Name
0, Angela
1, Tristan
2, Aurora

Student number, Score
0, 6
1, 3
2, 9

School = Hogwarts
Grade = 1
Student number, Name
0, Ginny
1, Luna

Student number, Score
0, 8
1, 7

Grade = 2
Student number, Name
0, Harry
1, Hermione

Student number, Score
0, 5
1, 10

Grade = 3
Student number, Name
0, Fred
1, George

Student number, Score
0, 0
1, 0

Here is what I want the result to look like after parsing:

                                         Name  Score
School         Grade Student number
Hogwarts       1     0                  Ginny      8
                     1                   Luna      7
               2     0                  Harry      5
                     1               Hermione     10
               3     0                   Fred      0
                     1                 George      0
Riverdale High 1     0                 Phoebe      3
                     1                 Rachel      7
               2     0                 Angela      6
                     1                Tristan      3
                     2                 Aurora      9

Here is how I currently parse it:

import re
import pandas as pd

def parse(filepath):
    """
    Parse text at given filepath

    Parameters
    ----------
    filepath : str
        Filepath for file to be parsed

    Returns
    -------
    data : pd.DataFrame
        Parsed data

    """

    data = []
    with open(filepath, 'r') as file:
        line = file.readline()
        while line:
            reg_match = _RegExLib(line)

            if reg_match.school:
                school = reg_match.school.group(1)

            if reg_match.grade:
                grade = reg_match.grade.group(1)
                grade = int(grade)

            if reg_match.name_score:
                value_type = reg_match.name_score.group(1)
                line = file.readline()
                while line.strip():
                    number, value = line.strip().split(',')
                    value = value.strip()
                    dict_of_data = {
                        'School': school,
                        'Grade': grade,
                        'Student number': number,
                        value_type: value
                    }
                    data.append(dict_of_data)
                    line = file.readline()

            line = file.readline()

        data = pd.DataFrame(data)
        data.set_index(['School', 'Grade', 'Student number'], inplace=True)
        # consolidate df to remove nans
        data = data.groupby(level=data.index.names).first()
        # upgrade Score from float to integer
        data = data.apply(pd.to_numeric, errors='ignore')
    return data

class _RegExLib:
    """Set up regular expressions"""
    # use https://regexper.com to visualise these if required
    _reg_school = re.compile('School = (.*)\n')
    _reg_grade = re.compile('Grade = (.*)\n')
    _reg_name_score = re.compile('(Name|Score)')

    def __init__(self, line):
        # check whether line has a positive match with all of the regular expressions
        self.school = self._reg_school.match(line)
        self.grade = self._reg_grade.match(line)
        self.name_score = self._reg_name_score.search(line)

if __name__ == '__main__':
    filepath = 'sample.txt'
    data = parse(filepath)
    print(data)


texts: Freeing shared memory with a signal handler

texts:
I have a homework question that asks me to get 2 integers from the user, put them in shared memory, fork a child, have the child add them and put the result in shared memory, and then the child will end and the parent will print out the sum.  The program must also loop until the user does CTRL+C, at which point it should catch the signal and the parent should detach and remove shared memory, SIGKILL the child, and then terminate itself.

I've already submitted this, and it got full credit, but I can't help but feel there is a better way.  Mainly, my concern is with the way I free the memory at the bottom of main() and, how I handle the signal.  I really wanted to free the memory in the signal handler, but couldn't figure out how to do that without making all the shared variables globals.  Those if (runFlag) statements don't seem particularly elegant to me either.

#define _POSIX_SOURCE

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

int runFlag = 1; //this flag will be set to 0 by a SIGINT

/* This function creates a shared memory area in the parent's address space of size size_of_shared_memory, and returns a void* pointer to it */
void *create_shared_memory(int size_of_shared_memory){
  int fd;
  void *area;

  fd = open("/dev/zero", O_RDWR);
  area = mmap(0, size_of_shared_memory, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  close(fd);
  return area;
}

void intHandler()
{//toggle runFlag so main loop exits
    runFlag = 0;
    //shmdt(); //detaches shared memory
    //shmctl(shm_id, IPC_RMID, NULL); //removes shared memory

    return;
}

int main(int argc, char **argv)
{
    int *num1 = (int *)create_shared_memory(sizeof(int));
    int *num2 = (int *)create_shared_memory(sizeof(int));
    int *sum = (int *)create_shared_memory(sizeof(int));
    int *flag = (int *)create_shared_memory(sizeof(int));
    *flag = 1;
    int child_pid;

    while(runFlag)
    {//runFlag will be changed by a SIGINT
        //since runFlag could be changed anywhere we must test for it whereever the program will be sitting

        if (runFlag) printf("\nEnter the first number: ");
        if (runFlag) scanf("%d", num1);
        if (runFlag) printf("Enter the second number: ");
        if (runFlag) scanf("%d", num2);

        if (runFlag)
        {
            *flag = 1;
            child_pid = fork();
            signal(SIGINT, intHandler);

            if(child_pid < 0){
                printf("Fork error. \n");
                exit(-1);
            }
            if(child_pid == 0){ // Child code
                signal(SIGINT, SIG_IGN); //ignore ctrl+c
                *sum = *num1 + *num2;
                *flag = 0; //signal to parent that child is done
                exit(0);
            }

            /* Parent code */
            while (*flag); //wait for child to signal it is done

            /* Read the integers from shared memory */
            printf("The sum is: %d\n", *sum);
        }
    }
    //exit
    printf("\n");
    munmap(num1, sizeof(int)); //unmap memory
    munmap(num2, sizeof(int));
    munmap(sum, sizeof(int));
    munmap(flag, sizeof(int));
    if (child_pid > 0) kill(child_pid, SIGKILL); //kill child process
  exit(0); //kill parent
}


texts: Android Studio Autocomplete that creates a new entry if no entry selected

texts:
I want to use the android component autocomplete:

https://developer.android.com/reference/android/widget/AutoCompleteTextView

There are some possible values the user can select, but I also want that, the user starts typing and, if there is no match with any of the "possible" optionsm, then, the text the user wrote is also valid. So, to put an example, imagine we have an autocomplete to select favourite fruit, and the options are Banana, Apple, but the user types Pear, then, it should be fine.

For that, I did this:

mAutocompleteTextView = findViewById(R.id.select_fruit_autoCompleteTextView)
mAutocompleteTextView.threshold = 1

val fruitListener = OnFruitSet()
// if the user clicks in one of the options
mAutocompleteTextView.onItemClickListener = fruitListener
// if the user writes a different option
mAutocompleteTextView.addTextChangedListener(fruitListener)

And then, my OnFruitSet private inner class:

private inner class OnFruitSet: AdapterView.OnItemClickListener, TextWatcher {

        private val textModified = AtomicBoolean(false)
        // this is used to change focus if the user finishes (by clicking on one of the options, or in the go button, next, etc. but it isn't working very good)
        private val goToNext = AtomicBoolean(false)

        override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            // this means that the fruit is an option
            listeners.forEach{ it.onFruitSet(parent?.adapter?.getItem(position), true) }

        }

        override fun afterTextChanged(s: Editable?) {
            if (textModified.get()) {
                textModified.set(false)
                goToNext.set(true)
// right now the user can add new lines, and I want to avoid it.
                mAutocompleteTextView.setText(s?.replace("[\n]".toRegex(), ""))
            } else {
                goToNext.set(false)
            }

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            val name = if (s?.contains('\n') == true) {
                textModified.set(true)
                s.replace("[\n]".toRegex(), "")
            } else {
                s
            }

            if (!textModified.get()) {
                val fruit = if (name.isNullOrEmpty() || name.isNullOrBlank()) {
                    null
                } else {
                    s.toString()
                }
                listeners.forEach{ it.onFruitSet(fruit, goToNext.get()) }
            }

        }

    }

There are some corner cases that don't work very good, specially with the \n, and when the user clicks on "Next".

Any hint on how to improve it? or is there any component already doing this?

Thanks


texts: Generating combinations of n elements in groups of k

texts:
I've written this program that writes all the combinations (without repetition) of n elements in groups of k.

I think the code is good, but I like to know if you have some better (or faster) solutions.

The elements to combine are always the number from 0 to n-1, the program calls a function (newCombo()) for each generated combination.

EG: Using n=6 and k=4 the program generates the following output:

0 1 2 3
0 1 2 4
0 1 2 5
0 1 3 4
0 1 3 5
0 1 4 5
0 2 3 4
0 2 3 5
0 2 4 5
0 3 4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5

The code is below:

#include <stdio.h>

void newCombo(int *a,int n,int k);

void newCombo(int *a,int n,int k)
{
    int i;
    for(i=0;i<k;i++)
        printf("%d ",a[i]);
    puts("");
}

int main(int argc,char *argv[])
{
    int a[30];
    int n,k,p;

    do {
        printf("Insert n and k - EG: 5 3: ");
        if (scanf("%d %d",&n,&k)!=2)
            return 1;
        if (k>n)
            puts("k shall be <= n !");
        if (k==0 || n==0)
            puts("k and n shall not be 0!");
        if (k>30)
            puts("k shall be <=30");
    } while (k>n || k==0 || n==0 || k>30);

    p=0;
    a[0]=-1;
    do {
        if (++a[p]>n-k+p) {
            p--;
        } else {
            if (p<k-1) {
                a[p+1]=a[p];
                p++;
            } else {
                newCombo(a,n,k);
            }
        }
    } while(p>=0);

    return 0;
}


texts: std::accumulate alternative for the C programming language

texts:
I've come up with some simple implementation for algorithms in C and more specifically for std::accumulate alternate since I need something like it recently. Can you provide some review on the approach?
#include <stdio.h>
#include <string.h>

#define ARRSIZE(X) (sizeof(X) / sizeof(X[0]))

#define ACCUMULATE(RET, FIRST, LAST, INIT, SUM_CB)      \
    do {                                                \
        RET = INIT;                                     \
        while (FIRST != LAST){                          \
            RET = SUM_CB(RET, *FIRST);                  \
            FIRST++;                                    \
        }                                               \
    } while(0);

/**
 * example usage
 * sum integers and sum strings by some delimiter
*/
struct str_t
{
    char data[512];
};

struct str_t sumStr(struct str_t a, struct str_t b)
{
    struct str_t ret = {0};
    strcat(ret.data, a.data);
    strcat(ret.data, "--");
    strcat(ret.data, b.data);
    return ret;
}

struct A { int a, b, c; };

struct A sumA(struct A a, struct A b) {
    struct A ret ;
    ret.a = a.a + b.a;
    ret.b = a.b + b.b;
    ret.c = a.c + b.c;
    return ret;
}

int main()
{
    unsigned long i;

    struct A sumvec[10];
    struct str_t sumstr[10];
    memset(sumstr, 0, sizeof(sumstr));

    for(i=0; i < ARRSIZE(sumvec); i++) {
        sumvec[i].a = i;
        sumvec[i].b = i+1;
        sumvec[i].c = i+2;
        snprintf(sumstr[i].data, sizeof(sumstr[i].data), "%d", i);
    }

    for(i=0; i < ARRSIZE(sumvec); i++) {
        printf("[%d][%d][%d]\r\n", sumvec[i].a ,sumvec[i].b,sumvec[i].c);
    }

    struct A ret = {sumvec[0].a, sumvec[0].b, sumvec[0].c};
    struct A* pBegin = &sumvec[1];
    struct A* pEnd = &sumvec[ARRSIZE(sumvec)];

    ACCUMULATE(ret, pBegin, pEnd,  ret, sumA)

    printf("SUM: [%d][%d][%d]\r\n", ret.a, ret.b, ret.c);

    struct str_t retstr;
    strcat(retstr.data, sumstr[0].data);

    struct str_t *pBegs = &sumstr[1];
    struct str_t *pEnds = &sumstr[ARRSIZE(sumstr)];

    ACCUMULATE(retstr, pBegs, pEnds, retstr, sumStr);

    printf("SUM STR: [%s]\r\n", retstr.data);
    return 0;
}


texts: Transform a string into an array based on grouping rules

texts:
I've got a simple spec for defining character sets, ranges, or wildcards. I'd like to take the string and appropriately create an array based on these rules. I have a solution but I'm sure there is a better way!

Single characters may be used
Sets and ranges are enclosed in brackets []
Sets are comma separated, [1,3,S]
Ranges are hyphenated, [1-3]
Sets and ranges can be combined, [1-3,7,9-10,S]
Wildcard character is - and not enclosed in brackets
Strings can contain the following characters are A-Z 0-9 - .

Example inputs and expected outputs

'ABC' outputs ['A', 'B', 'C']
'S[1-2]-' outputs ['S', '1-2', '-']
'S[1-2]2.0[0-9][1,3,7]S' outputs ['S', '1-2', '2', '.', '0', '0-9', '1,3,7', 'S']
'S[1-2,7]' outputs ['S', '1-2,7']

My implementation:

function stringToArray(code) {
    var exploded = code.split(''),
            charGroups = [],
            tempGroup = '',
            inGroup = false;
    while (exploded.length > 0) {
        var cur = exploded.shift();
        if (cur === '[') {
            inGroup = true;
            continue;
        }
        if (inGroup) {
            if (cur === ']') {
                inGroup = false;
                charGroups.push(tempGroup);
                tempGroup = '';
            } else {
                tempGroup += cur;
            }
        }
        if (!inGroup) {
            if (cur !== ',' && cur !== '[' && cur !== ']') {
                charGroups.push(cur);
            }
        }
    }
    return charGroups;
}

Demo fiddle here: http://jsfiddle.net/3q25eps3/


texts: Generic NSMapTable replacement written in Swift

texts:
This is my attempt at writing a generic NSMapTable with weak keys and strong values (after your feedback I'll be trying to write Strong-Key/Weak-Value and Weak-Key/Weak-Value variants to have the complete functionality of NSMapTable with generics). To my knowledge it works correctly.

public class WeakKeyDictionary<K: AnyObject, V where K: Hashable> {

    private var dict = Dictionary<HashableWeakBox<K>, V>()
    public var block: (V)->() = { _ in }

    public init() {}
    public init(dictionary: Dictionary<K, V>) {
        for (k, v) in dictionary {
            setValue(v, forKey: k)
        }
    }

    public subscript(key: K) -> V? {
        get { return valueForKey(key) }
        set { setValue(newValue, forKey: key) }
    }

    public func valueForKey(key: K) -> V? {
        return dict[HashableWeakBox(key)]
    }
    public func setValue(newValue: V?, forKey key: K) {
        let hashableBox = HashableWeakBox(key)

        if let value = newValue {
            let watcher = DeallocWatcher { [weak self] in
                if let v = self?.dict[hashableBox] { self?.block(v) }
                self?.dict[hashableBox] = nil
            }

            objc_setAssociatedObject(key, unsafeAddressOf(self), watcher, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
            dict[hashableBox] = value
        }
        else {
            objc_setAssociatedObject(key, unsafeAddressOf(self), nil, 0)
            dict[hashableBox] = nil
        }
    }
    public func removeValueForKey(key: K) -> V? {
        objc_setAssociatedObject(key, unsafeAddressOf(self), nil, 0)
        return dict.removeValueForKey(HashableWeakBox(key))
    }

    public var count: Int { return dict.count }
    public var isEmpty: Bool { return dict.isEmpty }
    public var keyValues: [(K, V)] {
        var list = [(K, V)]()
        for (k, v) in dict { list.append((k.value!, v)) }
        return list
    }
    public var keys: [K] {
        var list = [K]()
        for k in dict.keys { list.append(k.value!) }
        return list
    }
    public var values: [V] {
        return Array(dict.values)
    }

    deinit {
        for box in dict.keys {
            objc_setAssociatedObject(box.value, unsafeAddressOf(self), nil, 0)
        }
    }
}

private func == <T: Hashable>(l: T, r: T) -> Bool { return l.hashValue == r.hashValue }

private class HashableWeakBox<T: AnyObject where T: Hashable>: Hashable {
    weak var value: T?
    let hashValueWhenNil: Int

    init(_ v: T) {
        value = v
        hashValueWhenNil = v.hashValue
    }

    var hashValue: Int { return value?.hashValue ?? hashValueWhenNil }
}

private class DeallocWatcher {
    let callback: ()->()
    init(_ c: ()->()) { callback = c }
    deinit { callback() }
}

The trick needed in order to be notified when one of the keys disappears is to add a watcher object (DeallocWatcher) as an associated object of the key (this only works on Swift 1.2, if I'm not mistaken). That way, whenever the key disappears, so does the watcher object, which in turn warns the dictionary class when deiniting.

The block property should, if needed, be set by the code using the class, and provides a way to be notified whenever a key is removed from the dictionary.

I'd like to know if this is reliable and works correctly in all cases. I'd also like to have a better idea of under which conditions can this be used across multiple threads. Finally, I'd like feedback on how I can better follow Swift guidelines and implement common "Swift-isms".