texts: Automatically generate a thunderbird importable contacts file for all employees

texts:
This is implemented in Ms Access 2003. The Table "People" is a ODBC linked database table on a MSSQL 2008 server. The file generated can be imported into Mozilla Thunderbird contacts to have a contact list of everyone in the company ready.

The entire thing is written under option explicit. This is mandated.

Private Sub GenerateContacts_Click()
'Automated Generation of an Importable .csv file for Mozilla Thunderbird contacts

'Variable Definitions
Dim fso As Object                   'File System Object
Dim oFile As Object                 'File Object
Dim path As String                  'User selected Path (Uneditable Textbox with "set path" button
Dim currentLine As String           'current Line to be written to file
Dim rs As Recordset                 'Recordset containing the data
Dim bigDelim As String              ' ",,,,,,,,,,,,,,,,,,,,,,,,,," Thunderbird CSV Format delimiter
Dim db As Database                  'Database object for query execution
Dim SQL As String                   'SQL Query to select the Users
Dim tel As String                   'Landline phone of the employee
Dim telMobi As String               'Mobile phone of the employee
Dim Email As String                 'Email adress of the employee
Dim Mng As Integer                  'Number of records to be processed
Dim pathDate As String              'Datediff to current date to append to filename to make files unique
Dim Name() As String               'Name of the employee

'Initialize the database
Set db = DBEngine(0)(0)

'Confirmation dialog
If Not MsgBox("Do you want to export all available contacts to thunderbird?", vbYesNo) = vbYes Then
  Exit Sub
End If
If Not Me![Outputpfad] <> "" Then
  MsgBox ("[Error] No output path selected.")
  Exit Sub
End If

SQL = "SELECT People.Name, People.Email, People.Telefon_int, People.Telefon_mobint FROM People WHERE People.Email <> '' AND People.Name NOT LIKE 'zz_%' ORDER BY People.Eintrag DESC"
Set rs = db.OpenRecordset(SQL, dbOpenDynaset, dbSeeChanges)
bigDelim = ",,,,,,,,,,,,,,,,,,,,,,,,,," 'Necessary for thunderbird .csv import format
pathDate = CStr(DateDiff("s", #1/1/1970#, Now()))
path = Me![Outputpfad] & "\"
path = path & pathDate & "-Company-Email-Contacts-Thunderbird.csv"

Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.CreateTextFile(path)
oFile.WriteLine "Vorname,Nachname,Anzeigename,Spitzname,Primäre E-Mail-Adresse,Sekundäre E-Mail-Adresse,Messenger-Name,Tel. dienstlich,Tel. privat,Fax-Nummer,Pager-Nummer,Mobil-Tel.-Nr.,Privat: Adresse,Privat: Adresse 2,Privat: Ort,Privat: Bundesland,Privat: PLZ,Privat: Land,Dienstlich: Adresse,Dienstlich: Adresse 2,Dienstlich: Ort,Dienstlich: Bundesland,Dienstlich: PLZ,Dienstlich: Land,Arbeitstitel,Abteilung,Organisation,Webseite 1,Webseite 2,Geburtsjahr,Geburtsmonat,Geburtstag,Benutzerdef. 1,Benutzerdef. 2,Benutzerdef. 3,Benutzerdef. 4,Notizen,"

rs.MoveFirst
Do While Not rs.EOF
    Email = rs![Email]
    Name = Split(rs![Name], ",")
    If rs![Telefon_int] <> "" Then
        tel = rs![Telefon_int]
    End If
    If rs![Telefon_mobint] <> "" Then
        telMobi = rs![Telefon_mobint]
    End If
    currentLine = Name(1) & "," & Name(0) & "," & Name(1) & " " & Name(0) & ",," & Email & ",,," & tel & ",,,," & telMobi & bigDelim
    oFile.WriteLine (currentLine)
    tel = ""
    telMobi = ""
    rs.MoveNext
Loop
oFile.Close
rs.Close
Set fso = Nothing
Set oFile = Nothing
MsgBox ("File successfully generated at path:  " & path)
End Sub

As far as I can tell, it works, with any subset or superset of the database records. I tested it against a employee table with 4000 entries for performance, and didn't notice a slowdown. Our actual production table is about 400 entries big. People whose names are starting with "zz_" have left the company (I didn't make that design choice and it's not changeable by me).


texts: How to format embedded if statements in JavaScript

texts:
What would be the best way to format this code? It looks a bit messy to me in regards to indentation etc.

 if (typeof _srwc != 'undefined') {
    for (var i=0; i < _srwc.length; i++){
         var currentArg = _srwc[i];;
          if (typeof window[currentArg[0]] == 'function') {
             window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
             } else {
             console.log('The Setter method: "' + currentArg[0] + '" is undefined');
             }
    }
 }


texts: Thread-safe object cache, for read, high performance in .NET

texts:
I want to realize an object cache which holds objects loaded from database, file or other slow access source, to make them available quickly with high performance. There will be a lot of accesses to get these objects from the dictionary!

It's not supposed to be Singleton/Static; multiple different object holders are possible, with multiple threads running on each.

Access is usually read-only, the objects themselves (in the dictionary) shall not be changed after being created.

For some special Admin functions, a Reload method exists, where thread safety can be ignored (not to be used by the main, multi-threaded program).

If I am right, the .NET Dictionary is thread-safe, as long as it is used only in read access, thus not requiring locks in reading methods. The dictionary will not be changed after being assigned to the _progObjects variable (do I need to make it volatile?). But time consuming volatile (alternatively Interlocked) access on the _areProgObjectsInitialized variable seems to be necessary, to make first accesses (with initialization) thread-safe.

Is the following a good and performant solution, can it still be improved, or are there safety risks?

/// <summary>
/// Not Singleton, but each instance multi-threaded!
/// Holds objects loaded from an external source (database, file, whatever...)
/// </summary>
public class ProgObjectsThreadSafeRead : IProgObjectsThreadSafeRead
{
    private IDictionary<ObjectKey, object> _progObjects = null;
    private object _progObjectsSyncObj = new object();
    private volatile bool _areProgObjectsInitialized = false;

    private void InitializeProgObjectsIfNeeded()
    {
        if (!_areProgObjectsInitialized)
        {
            lock(_progObjectsSyncObj)
            {
                if (!_areProgObjectsInitialized)
                {
                    IDictionary<ObjectKey, object> localProgObj = LoadProgObjects();
                    // do something more
                    _progObjects = localProgObj;
                    _areProgObjectsInitialized = true;
                }
            }
        }
    }

    public object GetProgObject(ObjectKey key)
    {
        InitializeProgObjectsIfNeeded();
        return _progObjects[key];
    }

    /// <summary>
    /// Not thread safe, don't use in multi-thread environments!
    /// Specific editing tools only! Not in interface.
    /// </summary>
    public void ReloadProgObjects()
    {
        lock (_progObjectsSyncObj)
        {
            _areProgObjectsInitialized = false;
            InitializeProgObjectsIfNeeded();
        }
    }

    // others removed
}


texts: Top Active Answerers on a Stack Exchange site

texts:
I created this query back in January to find the top active answerers on Code Review and thought that it might be a good idea to get other opinions on my SQL coding using a database that we can all access.

This will probably be the first of several queries that I post for review.

Actual SEDE Query --> Top Active Answerers on site

--@DaysSinceActivity is the amount of days that you would like to scan for activity
--@NumberOfUsers is the number of users you want to return.

DECLARE @DaysSinceActivity INT = ##DaysSinceActivity##

SELECT
    TOP ##NumberOfUsers##
    Users.Id as [User Link],
    Count(Posts.Id) AS Answers,
    CAST(AVG(CAST(Score AS float)) as numeric(6,2)) AS [Average Answer Score]
FROM
    Posts
INNER JOIN
    Users ON Users.Id = OwnerUserId
WHERE
    PostTypeId = 2 and CommunityOwnedDate is null and ClosedDate is null
    AND Users.LastAccessDate > DateAdd(Day, -31, GetDate())
GROUP BY
    Users.Id, DisplayName
HAVING
    Count(Posts.Id) > 10
ORDER BY
    [Average Answer Score] DESC


texts: Simple library for an undocumented archive format

texts:
I'm writing a little library for some undocumented file formats. The original program uses a path string to find files in an archive and this function tries to do the same.
The archive contains a magic string, an offset into the file list, the data in the files and the file list itself. A entry in the filelist consists of a path (256 bytes long, 0-padded) and three numbers, the second one being the offset from the archive start to the entry file. The entries are sorted alphabetically respecting case; here are some mockup paths to demonstrate the ordering:
Entry/Graphics/Sprite.cgf
Entry/Sound/Ding.wav
Quit/Graphics/exit.cgf
_RAW8123

Here are the relevant utility functions and defines. These are defined in Utils.h and Utils.c, I've put them here together for context.
#define BYTESZE sizeof(char)

typedef unsigned int uint;
typedef unsigned char byte;

uint readU4L(FILE* file) {
    byte buf[4];
    fread(buf, BYTESZE, 4, file);
    return buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0];
}

Finally, here's the "library":
// ====== BIGfile.h
#define BIG_MAGIC_LEN 7

#define BIG_SEEK_SUCC 1
#define BIG_SEEK_FAIL 0

typedef struct BIGFile {
    char magic[BIG_MAGIC_LEN];
    uint offset;
    FILE* read;

} BIGFile;

BIGFile* load_BIGFile(char* fpath);

int seekToEntry(BIGFile* bigfile, char* path);

// ====== BIGFile.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "Utils.h"
#include "BIGFile.h"

BIGFile* load_BIGFile(char* fpath) {
    BIGFile* bigfile = malloc(sizeof(BIGFile));

    fopen_s(&(bigfile->read), fpath, "rb");

    if (!bigfile->read) {
        printf("Can't open file.\n");
        return 0;
    }

    fread(bigfile->magic, BYTESZE, BIG_MAGIC_LEN, bigfile->read);
    bigfile->offset = readU4L(bigfile->read);
    return bigfile;
}

int seekToEntry(BIGFile* bigfile, char* path) {

    fseek(bigfile->read, bigfile->offset, SEEK_SET);

    byte buf[256];

    int pos = 0;

    // while not EOF, read string part
    while (fread(buf, BYTESZE, 256, bigfile->read)) {

        // seek over entry data
        fseek(bigfile->read, 12, SEEK_CUR);

        // loop until given path != read path
        while (path[pos]==buf[pos]) {
            pos++;

            // path has ended, so buf == path
            if (!path[pos]) {

                // seek back into entry data
                fseek(bigfile->read, -8, SEEK_CUR);

                // read unsigned little endian 4-byte int
                uint res = readU4L(bigfile->read);

                // seek there and return success
                fseek(bigfile->read, res, SEEK_SET);
                //printf("found at %d\n", res);
                return BIG_SEEK_SUCC;
            }
        }
        // path char is smaller than buf char
        // we seeked past where the entry could bem return failure
        if (path[pos]<buf[pos]) {
            return BIG_SEEK_FAIL;
        }
    }
    // EOF, return failure
    return BIG_SEEK_FAIL;
}

I'd like some feedback on general style, as well as on the seekToEntry function, perhaps this can be improved somehow? Thanks in advance!


texts:
Learn You a Haskell shows the lines function:

  It takes a string and returns every line of that string in a separate list.

Example:

>lines' "HELLO\nWORLD\nHOWAREYOU"
["HELLO","WORLD","HOWAREYOU"]

Here's my implementation:

lines' :: String -> [String]
lines' [] = []
lines' xs = lines'' xs []
             where lines'' [] ys = ys : []
                   lines'' (x:xs) ys
                     |  x == '\n' = ys : lines'' xs []
                     | otherwise  = lines'' xs (ys ++ [x])

Please critique it. Also, when using an accumulator value (such as ys in lines''), I don't know how to use the : function instead of ++.


texts: Restful CRUD API with Node.js and Express

texts:
I build a RESTful CRUD API with Node.js and Express. This application allows, for example, to create a table on the client side with the ability to add, update and remove data by ID.
I generate an array of random data for the availability of data when you start working on the client side with the table.
I will be grateful for tips on improving the style.

const express = require('express')
const bodyParser = require('body-parser')
const crypto = require("crypto");
const cors = require('cors')

const getId = () => crypto.randomBytes(16).toString("hex");
const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min)) + min;
const nameList = ['Andrew', 'John', 'Sebastian', 'Owen', 'Luke', 'Anthony', 'Dylan']
const cityList = ['Riga', 'Berlin', 'Paris', 'Tokyo', 'London', 'Milan', 'Madrid']
const colorList = ['red', 'blue', 'green']
const getRandomStr = (str) => (str[getRandomInt(0, str.length)])

const app = express()

const names = [
  { id: getId(),
    name: 'Li',
    city: 'Tokyo',
    color: 'blue',
    answers: '10',
    reputation: '1725' }
]

const generateNames = () => {
  for (let i=0; i<50; i++){
  const newId = getId()
  const newName = getRandomStr(nameList)
  const newCity = getRandomStr(cityList)
  const newColor = getRandomStr(colorList)
  const newAnswers = getRandomInt(10, 20).toString()
  const newReputation = getRandomInt(1500, 2000).toString()
  names.push({ id: newId, name: newName, city: newCity,
  color: newColor, answers: newAnswers, reputation: newReputation })
  }
}
generateNames()

app.use(bodyParser.json())

app.use(cors())

app.get('/names', (req, res) => {
  res.json(names)
})

app.post('/names', (req, res) => {
  const newId = getId()
  const newName = req.body.name
  const newCity = req.body.city
  const newColor = req.body.color
  const newAnswers = req.body.answers
  const newReputation = req.body.reputation
  names.push({ id: newId, name: newName, city: newCity,
  color: newColor, answers: newAnswers, reputation: newReputation })
  res
    .status(201)
    .json({ id: newId })
})

app.put('/names', (req, res) => {
  const { id } = req.body
  const indexToEdit = names.findIndex(obj => obj.id === id )
  names[indexToEdit].name = req.body.name
  names[indexToEdit].city = req.body.city
  names[indexToEdit].color = req.body.color
  names[indexToEdit].answers = req.body.answers
  names[indexToEdit].reputation = req.body.reputation
  const editName = names[indexToEdit].name
  const editCity = names[indexToEdit].city
  const editColor = names[indexToEdit].color
  const editAnswers = names[indexToEdit].answers
  const editReputation = names[indexToEdit].reputation
  res
    .status(200)
    .json({ name: editName, city: editCity,
      color: editColor, answers: editAnswers, reputation: editReputation})
})

app.delete('/names', (req, res) => {
  const { id } = req.body
  const indexToRemove = names.findIndex(obj => obj.id === id )
  names.splice(indexToRemove, 1)
  res
    .status(200)
    .json({ status: 'success'})
})

app.listen(3000, () => {
  console.log('listening on 3000')
})


texts: Prime engine: generation, primality, factorization

texts:
I've just written my first C# class, so I'm looking for some feedback before I go and write more code. The goal of the code is to provide a Singleton-like class to deal with common operations on the set of prime numbers that I will need to complete projecteuler.net problems.

I'm interested in feedback for all aspects of the implementation (short of the actual prime generation algorithms, the 6*i +/- 1 method was used solely for its simplicity).

I'm also interested in feedback about how the interfaces are split up. I split these up into slices of functionality in an attempt to allow future implementation changes. I am planning to use DI (e.g. SimpleInjector) to bind the singleton instance to each of the interfaces, but I'm seriously starting to doubt this pattern.

I'm less interested in feedback about the selections of methods, I just chose a relatively minimal subset of methods that I know that I will need at some point - more methods will probably be added as needed.

Interfaces

public interface IPrimeGenerator
{
    IEnumerable<long> PrimesUntilValue(long value);
    IEnumerable<long> PrimesUntilCount(int count);
}

public interface IPrimeChecker
{
    bool IsPrime(long value);
}

public interface IPrimeFactorizer
{
    IEnumerable<long> PrimeFactors(long value);
    IEnumerable<long> UniquePrimeFactors(long value);
}

Implementation

public class PrimeEngine: IPrimeGenerator, IPrimeChecker, IPrimeFactorizer
{
    private readonly ICollection<long> _primeCollection;
    private long _indexFactor;
    private long _maxChecked;

    public PrimeEngine()
    {
        _primeCollection = new Collection<long> {2, 3};
        _indexFactor = 1;
        _maxChecked = 3;
    }

    private void CheckNextPossiblePrimeDoublet()
    {
        var low = 6 * _indexFactor - 1;
        var high = low + 2;

        if (IsPrime(low))
        {
            _primeCollection.Add(low);
        }

        if (IsPrime(high))
        {
            _primeCollection.Add(high);
        }

        _indexFactor += 1;
        _maxChecked = high;
    }

    private IEnumerable<long> GetPossibleSmallerPrimeFactors(long value)
    {
        FillPrimesUntilRoot(value);
        return PrimesUntilRoot(value);
    }

    public bool IsPrime(long value)
    {
        var primePool = GetPossibleSmallerPrimeFactors(value);
        return primePool.All(prime => value % prime != 0);
    }

    private void FillPrimesUntilValue(long value)
    {
        while (_maxChecked < value)
        {
            CheckNextPossiblePrimeDoublet();
        }
    }

    private void FillPrimesUntilCount(int count)
    {
        while (_primeCollection.Count < count)
        {
            CheckNextPossiblePrimeDoublet();
        }
    }

    private static long FloorOfRoot(long value)
    {
        return (long) Math.Floor(Math.Sqrt(value));
    }

    private void FillPrimesUntilRoot(long value)
    {
        FillPrimesUntilValue(FloorOfRoot(value));
    }

    public IEnumerable<long> PrimesUntilValue(long value)
    {
        FillPrimesUntilValue(value);
        return _primeCollection.TakeWhile(prime => prime <= value);
    }

    public IEnumerable<long> PrimesUntilCount(int count)
    {
        FillPrimesUntilCount(count);
        return _primeCollection.Take(count);
    }

    public IEnumerable<long> PrimesUntilRoot(long value)
    {
        return PrimesUntilValue(FloorOfRoot(value));
    }

    public IEnumerable<long> PrimeFactors(long value)
    {
        FillPrimesUntilRoot(value);
        foreach (var prime in PrimesUntilRoot(value))
        {
            if (prime > value) break;

            while (value % prime == 0)
            {
                yield return prime;
                value /= prime;
            }
        }

        if (value != 1)
        {
            yield return value;
        }
    }

    public IEnumerable<long> UniquePrimeFactors(long value)
    {
        return PrimeFactors(value).Distinct();
    }
}


texts: Finding common elements, ignoring duplicates, in two given string arrays

texts:
I am going through the CodingBat exercises for Java. Here is the one I have just completed:

  Start with two arrays of strings, a and b, each in alphabetical order, possibly with duplicates. Return the count of the number of strings which appear in both arrays. The best "linear" solution makes a single pass over both arrays, taking advantage of the fact that they are in alphabetical order.

Here is my code:

public int commonTwo(String[] a, String[] b){

    String[] shortArray;
    String[] longArray;

    if (a.length != b.length) {
        shortArray = a.length < b. length ? a : b;
        longArray = a.length > b. length ? a : b;
    } else {
        shortArray = a;
        longArray = b;
    }

    int count = 0;
    String letterToAvoid = "";

    for (int i = 0; i < shortArray.length; i++) {
        for (int j = 0; j < longArray.length; j++) {
            if (shortArray[i] == longArray[j] && longArray[j] != letterToAvoid){
                count++;
                letterToAvoid = longArray[j];
            }
        }
    }
    return count;
}

My questions are:

Is there a better - or more efficient - way to find the longest and shortest array lengths (and subsequently assign them separately if the lengths are equal)?
Is my letterToAvoid idea, used to 'skip' certain array elements, good for this kind of exercise?
How could I make this code more efficient?


texts: Trying to write an equals method for a class containing array of objects

texts:
Im trying to write a College class equals method that compare the content of the arrays of the two objects of college class. So The method will compare the Student[] array in college object to other Student[] array in another college object and same for the teacher[] array. I have written an equals method for this, but it looks too long and not pretty. Is there a better way to write it?

College Class

public class College
{
  private Student[] student;
  private Teacher[] teacher;
  public College()
  {
    student = new Student[9];
    teacher = new Teacher[9];
  }

  public Student[] getStudent()
  {
    return student;
  }

  public void setStudent(Student[] student)
  {
    this.student = student;
  }

  public Teacher[] getTeacher()
  {
    return teacher;
  }

  public void setTeacher(Teacher[] teacher)
  {
    this.teacher = teacher;
  }

  public boolean equals(Object inObj)
  {// this equals method

    boolean isEqual = false;
    College inCollege = (College)inObj;

    if(student.length == inCollege.getStudent().length)
    {
      for(int i = 0; i < student.length; i++)
      {
        if(student[i].equals(inCollege.student[i]))
        {
            isEqual = true;
        }
      }
    }
    if((teacher.length == inCollege.getTeacher().length) && isEqual == true)
    {
      isEqual = false;
      for(int i = 0; i < inCollege.getTeacher().length; i++ )
      {
        if(teacher[i].equals(inCollege.teacher[i]))
        { System.out.println("im in");
          isEqual = true;
        }
      }
    }
    return isEqual;
  }
}

Student Class

public class Student
{
  private String name;
  private int age;

  public Student()
  {
    name = "Samrah";
    age = 19;
  }

  public Student(String name, int age)
  {
      this.name = name;
      this.age = age;
  }
  public String getName()
  {
    return name;
  }

  public void setName(String name)
  {
    this.name = name;
  }

  public int getAge()
  {
    return age;
  }

  public void setAge(int age)
  {
    this.age = age;
  }

  public boolean equals(Object inObj)
  {
    boolean isEqual = false;
    if(inObj instanceof Student)
    {
        Student inStudent = (Student)inObj;
        if(this.name.equals(inStudent.getName()))
          if(this.age == inStudent.getAge())
              isEqual = true;

    }
    return isEqual;
  }

  public String toString()
  {
    String str;

    return str = "name: "+name+" age: "+age;
   }

}

Teacher Class

public class Teacher
{
  private String name;
  private int age;

  public Teacher()
  {
    name = "Sanjay";
    age = 45;
  }

  public Teacher(String name, int age)
  {
    this.name = name;
    this.age = age;
  }

   public void setName(String name)
  {
    this.name = name;
  }

  public String getName()
  {
    return name;
  }

  public int getAge()
  {
    return age;
  }

  public void setAge(int age)
  {
    this.age = age;
  }

  public boolean equals(Object inObj)
  {
    boolean isEqual = false;
    if(inObj instanceof Teacher)
    {
       Teacher inTeacher = (Teacher)inObj;
        if(this.name.equals(inTeacher.getName()))
          if(this.age == inTeacher.getAge())
              isEqual = true;

    }
    return isEqual;
  }

  public String toString()
  {
    String str;

    return str = "name: "+name+" age: "+age;
   }
}

Trying to do something like this:

    boolean isEqual = false;

    if(inObject instanceof EngineClass)
    {
        EngineClass inEngine = (EngineClass)inObject;
        if(cylinders == inEngine.getCylinders())
        if(fuel.equals(inEngine.getFuel()))
            isEqual = true;
    }
    return isEqual;

but with since its an array I have to loop through the arrays so I'm really confused.


texts:
I have a move function in this game that I'm making.  It works fine, but I'd like to reduce its size a bit.

function move(moveTo, direction) {

    switch (direction) {
        case "right":
            $('#player').animate({ left: "+=" + scale }, "slow", function () {
                $("#player").appendTo("#" + moveTo);$('#player').attr("style", "");
            });break;
        case "left":
            $('#player').animate({ left: "-=" + scale }, "slow", function () {
                $("#player").appendTo("#" + moveTo);$('#player').attr("style", "");
            });break;
        case "up":
            $('#player').animate({ top: "-=" + (9 * (scale / 10)) }, "slow", function () {
                $("#player").appendTo("#" + moveTo);$('#player').attr("style", "");
            });break;
        case "down":
            $('#player').animate({ top: "+=" + (9 * (scale / 10)) }, "slow", function () {
               $("#player").appendTo("#" + moveTo);$('#player').attr("style", "");
            });break;
    }
}

I always execute the same commands:

$("#player").appendTo("#" + moveTo);

and

$('#player').attr("style", "");

I can't put it after the switch statement because I want to wait until the animate is finished.  Is there a way to do this other than making a function? I also want this type of thing for some other code, so a bit less case specific would be better.


texts:
Could you please review my spinlock implementation?

class spinlock {
private:
    static const std::thread::id lock_is_free;
    std::atomic<std::thread::id> lock_owner;
    int lock_count;

public:
    spinlock() : lock_owner(lock_is_free), lock_count(0) {
    }

    void lock() {
        static thread_local std::thread::id this_thread_local = std::this_thread::get_id();
        auto this_thread = this_thread_local;

        for (auto id = lock_is_free; ; id = lock_is_free) {
            if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; }
            id = this_thread;
            if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; }
        }
    }

    void unlock() {
        assert(lock_owner.load(std::memory_order_relaxed) == std::this_thread::get_id());
        if (lock_count > 0 && --lock_count == 0) {
            lock_owner.store(lock_is_free, std::memory_order_release);
        }
    }
};

const std::thread::id spinlock::lock_is_free;


texts:
I am making a Python program with what I learned so far where the user enters two IPs that represents the start and end of the range of IPs to be scanned, then saves the wanted IP in a text file.

   #ip range and scanning
import socket
import sys
ok=[]
def ipscan(start2,port):
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)
    try:
        s.connect((start2,port))
        print start2 ,'-->port %s is Open'%port
        ok.append(start2)
    except: print start2 ,'-->port %s is Closed ! '%port
def iprange(start,end):
    while end>start:
       start[3]+=1
       ipscan('.'.join(map(str,start)),p)
       for i in (3,2,1,0):
          if start[i]==255:
             start[i-1]+=1
             start[i]=0
 #--------------------------------------------#
sta=map(int,raw_input('From : ').split('.'))
fin=map(int,raw_input('to : ').split('.'))
p=input('Port to scan : ')
iprange(sta,fin)
print '-----------end--------------'
of=open('Output.txt','w')
for ip in ok:
    of.writelines(ip+'\n')
of.close()

It seems to be working but I need to be sure, and wanted to know if I can make it any faster, or if there is a better way.


texts:
I've seen a lot of Objective-C implementations but I'd like to do it in Swift.

I did it like this and it seems to work just fine. Does anyone have comments and/or improvements to make?

import SystemConfiguration

class EnvData: NSObject {

    class func getSSID() -> String {

        var currentSSID = ""

        let interfaces = CNCopySupportedInterfaces()

        if interfaces != nil {

            let interfacesArray = interfaces.takeRetainedValue() as [String]

            if interfacesArray.count > 0 {

                let interfaceName = interfacesArray[0] as String

                let unsafeInterfaceData = CNCopyCurrentNetworkInfo(interfaceName)

                if unsafeInterfaceData != nil {

                    let interfaceData = unsafeInterfaceData.takeRetainedValue() as Dictionary!

                    currentSSID = interfaceData["SSID"] as String

                } else {

                    currentSSID = ""
                }

            } else {

                currentSSID = ""
            }

        } else {

            currentSSID = ""
        }

        return currentSSID
    }
}


texts: Converting Geographic Coordinates into Lambert2008 coordinates

texts:
This is part of a game made in Unity3D.

I wrote this class to convert geographic coordinates into lambert 2008 coordinates based on this reference document:

http://www.ngi.be/Common/Lambert2008/Transformation_Geographic_Lambert_FR.pdf

Reason is that I'm using a Belgian National Geographic Institute map as background, and want to locate waypoint and player position with full accuracy.

Code works fine, and runs in .000001s but I'm unhappy with its readability.

I start by declaring all the constants I need

public const int a = 6378137;
public const double f = 1 / 298.257222101;
public const double lowerLatitude = 49.8333333 * Mathf.Deg2Rad;
public const double upperLatitude = 51.1666667 * Mathf.Deg2Rad;
public const double originLatitude = 50.797815 * Mathf.Deg2Rad;
public const double originLongitude = 4.359215833 * Mathf.Deg2Rad;
public const int originX = 649328;
public const int originY = 665262;

Then  I used properties for all values derived from those constants

public static double Excentricity {get => System.Math.Sqrt((2 * f) - (f * f));}

static double MLower { get => M(lowerLatitude);}
static double MUpper { get => M(upperLatitude);}

static double M(double latitude)
{
    return System.Math.Cos(latitude) / System.Math.Sqrt(1 - (Excentricity * Excentricity * System.Math.Pow(System.Math.Sin(latitude), 2)));
}

static double TLower { get => T(lowerLatitude); }
static double TUpper { get => T(upperLatitude); }
static double TOrigin { get => T(originLatitude); }

static double T(double latitude)
{

    return System.Math.Tan(Mathf.PI / 4 - latitude / 2) / System.Math.Pow((1 - Excentricity * System.Math.Sin(latitude)) / (1 + Excentricity * System.Math.Sin(latitude)), Excentricity / 2);
}

static double N { get => (System.Math.Log(MLower) - System.Math.Log(MUpper)) / (System.Math.Log(TLower) - System.Math.Log(TUpper)); }

static double G { get => MLower / (N * System.Math.Pow(TLower, N)); }

static double ROrigin { get => R(TOrigin); }

static double R (double t)
{
    return a * G * System.Math.Pow(t, N);
}

As you can see some of the calculations are written on very long lines. I'm unhappy with their readability, but I have no Idea on how to re-write them to make them look better while not messing up floating point approximations.

Finally I perform the actual conversion using all those calculated values.

public static Vector2 FromGeographicRelative(Vector2 coordinates)
{

    double t = T((double)coordinates.x * Mathf.Deg2Rad);
    double r = R(t);
    double angle = N * ((double)coordinates.y * Mathf.Deg2Rad - originLongitude);
    Vector2 lambertCoord = new Vector2
    {
        x = (float) (r * System.Math.Sin(angle)),
        y = (float) (ROrigin - r * System.Math.Cos(angle))
    };
    return lambertCoord;

}


texts: C-style `switch` statement implementation using decorators

texts:
Yes I know context managers are a much better way to do this, but I spent four hours working on implementing a switch construct using generic decorators, and I'd like to hear feedback on how I did. I'll do it with context managers tomorrow.

I don't think I qualify as a beginner anymore (I'm looking to start getting paid to write Python soon), and I would appreciate guidance on best practices.

My Code

"""Module to implement C style switch functionality using decorators.

  Functions:
    `switch_construct`: Returns functions that provide the required functionality and provides a closure for said functions.
"""

__all__ = ["switch", "case", "break_"]

import operator as op

def switch_construct():
  """Forms a closure to store the meta data used by the switch construct.

    Vars:
      `closure` (list): List to store dictionaries containing metadata for each `switch` instance.
        * The dictionary contains two keys: "control" and "halt".
          - "control": the value governing the current switch instance. `case` blocks are tested against this value.
          - `halt`: value is used to implement break functionality.
            > `True`: break after execution of current function.
            > Default: `False`.

    Returns:
      tuple: A tuple of functions (`switch`, `case`, `break_`) defined in the function's scope.
  """
  closure = []

  def switch(input_):
    """Sets the metadata for the current `switch` block.

      Args:
        `input` (object): The value governing the switch construct.

      Returns:
        `function`: A decorator for the function enclosing the switch block.
    """
    nonlocal closure
    def decorator(func):
      closure.append({"control": input_, "halt": False})  # Add the metadata to closure.
      # Sets `control` to `input_` and `halt` to `False` for each `switch` block.
      def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
      wrapper.switch_index = len(closure)-1
      # Assign the `switch_index` attribute to the decorated function for using when retrieving switch construct metadata.
      return wrapper
    return decorator

  def case(value, enclosing, test = op.eq):
    """Returns a decorator which executes decorated function only if its `value` argument satisfies some test.

      Args:
        `value` (object): value used to test whether the decorated function should be executed.
        `enclosing` (function): enclosing function corresponding to the current switch block.
        `test` (function): test that should be satisfied before decorated function is executed.
          - Default value is `op.eq`.
          - Returns `bool`.

      Returns:
        function: A decorator for the function corresponding to the case block.
    """
    def decorator(func):
      nonlocal closure
      index = enclosing.switch_index
      return_value = None
      if test(value, closure[index]["control"]) and not closure[index]["halt"]:
        return_value = func()
      return return_value
    return decorator

  def break_(enclosing):
    """Used to indicate that the switch construct should break after execution of the current function."""
    nonlocal closure
    closure[enclosing.switch_index]["halt"] = True
    return None

  return case, switch, break_

case, switch, break_ = switch_construct()

@switch(2)
def func():
  """Sample use case of the switch construct."""
  @case(1, func)
  def _(num=10):
    print(num + 1)

  @case(2, func)
  def _(num=10):
    print(num + 2)
    break_(func)

  @case(3, func, op.gt)
  def _(num=10):
    print(num + 3)

func()


texts:
I have a class which creates a new match. My problem is that I am sure the code is unnecessary long and can get much improved (just keep in mind it is beginner level).

Specifically, I would like to know:

Can I change the below into 1 setter and 1 getter method?
I would like to use the rand() function for match ID can I do this inside the setter function of setMatchId or should it be done outside of the class?
When I upload the class to a db I assume I would need to create a new method and code the DB upload inside the method or should this be done outside of the class.

<?php
class match{
private $matchId;
private $team1;
private $team2;
private $venue;

function __construct($pMatchId, $pTeam1, $pTeam2, $pVenue){
    $this->matchId = $pMatchId;
    $this->team1 = $pTeam1;
    $this->team2 = $pTeam2;
    $this->venue = $pVenue;
}
    function setMatchId($pMatchId){
        $this->matchId = $pMatchId;

    }

    function getMatchId(){
        return $this->matchId;

    }
    function setTeam1($pTeam1){
        $this->team1 = $pTeam1;
    }
    function getTeam1(){
        return $this->team1;

    }

    function setTeam2($pTeam2){
        $this->team2 = $pTeam2;
    }
    function getTeam2(){
        return $this->team2;

    }
    function setVenue($pVenue){
        $this->venue = $pVenue;

    }
    function getVenue(){
        return $this->venue;

    }

} // c;lass match

$x = new match("1", "Patriots", "Chargers", "Newlands");
echo $x->getMatchId();
echo'
';
echo $x->getTeam1();
echo'
';
echo $x->getTeam2();
echo'
';
echo $x->getVenue();
?>


texts: F# code to check whether there are three same digits within a given number

texts:
I came across this problem by accident and gave it a go. I think my solution works as it has passed all the unit tests I wrote. Given I just started learning F# a couple of weeks I would love to have some feedback on the code regarding both its accuracy and its quality.

To be clear about the problem, given an integer number, check whether the number has at least 3 same digits in it e.g. 1222, 12222, 222, 123123123 are both counted as yes.

module Miscellaneous =
    let (|ThreeSame|_|) = function
        | (l : int list) when l.Length > 20 -> Some()
        | x :: y :: z :: _ when x = y && y = z -> Some()
        | _ -> None

    ///
    /// Given any integer convert its digits into a list
    ///
    ///<param name="number">The integer</param>
    ///<returns>
    ///A int list
    ///</returns>
    let convertNumberToList (number: bigint) =
        let numberString = string number
        numberString.ToCharArray()
        |> Array.map (string >> int) //use composition to replace (fun x -> int (string x))
        |> Array.toList

type NumberCheck() =
        ///
        /// A helper function to check whether a list of numbers contains three or more
        /// same numbers
        ///
        ///<param name="l">The list to be checked</param>
        ///<param name="sorted">The flag to indicate whether the given list is sorted or not</param>
        ///<returns>
        /// True if there are at least 3 same numbers; False otherwise
        ///</returns>
        static member private TripleNumberHelper(l : int list, ?sorted) =
            if l.Length < 3 then false
            else
                if defaultArg sorted false then
                    match l with
                    | Miscellaneous.ThreeSame -> true
                    | _ -> NumberCheck.TripleNumberHelper(l.Tail, true)
                else
                    let sortedList = l |> List.sort
                    match sortedList with
                    | Miscellaneous.ThreeSame -> true
                    | _ -> NumberCheck.TripleNumberHelper(sortedList.Tail, true)

        ///
        /// Test whether a number has 3 or more same digits in it
        ///
        ///<param name="number">The number to be checked</param>
        ///<returns>
        ///Ture of False
        ///</returns>
        static member TripleNumber(number : bigint) =
            let l = Miscellaneous.convertNumberToList number
            NumberCheck.TripleNumberHelper(l)


texts: Flask site that uses x-editable to edit elements and update mysql db

texts:
This code is built in flask, it allows a user to edit a title and a description of a div.

I have used the X-editable library which allows a user to edit text and use ajax requests.

I also process the value of the edited text and using python insert it into a mysql database.

The code works fine it is editing and saving to the db correctly. My question is my code set up correctly can or should I enhance it (considering the jQuery code)?

Also should I be performing more validation checks (i.e. should I be checking for http 200 repsonses within the python or jQuery?) or are my try/except blocks fine for this purpose.

Here is my html;

    {% for x in data %}

                    {{ x.pri_title }}

                    {{ x.pri_desc }}

{{ x.pri_link }}

{{ x.pri_img_link }}

{{ x.pri_source }}

    {% endfor %}

Here is my jQuery;

$.fn.editable.defaults.mode = 'inline';

$(document).ready(function() {
  $('.pri_title').editable();
  $('.pri_desc').editable();
});

and finally here is my python-flask code;

@app.route('/editTitle',methods=['GET','POST'])
def editTitle():
  if request.method == 'POST':
    updatedTitle = request.form['value']
    priId = request.form['pk']
    try:
        sql = "UPDATE pri_table SET pri_title = %s WHERE pri_id = %s"
        dbDets[1].execute(sql,(updatedTitle,priId),)
        dbDets[0].commit()
    except Exception as e:
        print("Error: "  + str(e))
  return redirect('/priority')

@app.route('/editDesc',methods=['GET','POST'])
def editDesc():
  if request.method == 'POST':
    updatedDesc = request.form['value']
    priId = request.form['pk']
    try:
        sql = "UPDATE pri_table SET pri_desc = %s WHERE pri_id = %s"
        dbDets[1].execute(sql,(updatedDesc,priId),)
        dbDets[0].commit()
    except Exception as e:
        print("Error: "  + str(e))
  return redirect('/priority')


texts: Python - Knight's tour recursive function

texts:
I realize that there're many implementations of Knight's tour problem suggested across webs, without jumping to those suggested solutions (most in Java, I'm not proficient in Java), I managed to implement one myself using Python. It works and returns some results.

Description

  A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only once. If the knight ends on a square that is one knight's move from the beginning square (so that it could tour the board again immediately, following the same path), the tour is closed, otherwise it is open.

For example:

board = Board(4,4)
a = list(dfs_search([0,0], tuple()))

Outputs:

# a[0]

([0, 0], [2, 1], [3, 3], [0, 2], [1, 0], [3, 1], [1, 2], [2, 0], [3, 2], [1, 1], [3, 0], [2, 3], [0, 3], [2, 2], [0, 1], [1, 3])

Most of the outputs are correct, which seems that the recursive function is actually working. The last few vertex, transit from [1,1] to [3,0] is problematic. I've spent hours debugging trying to resolve it, but failed. As the last resort, I bring the question here, hoping anyone could shed some light to my implementation.

This is my implemntaion of Knight's tour problem using recusive functions.

def dfs_search(start, path):
    if not path:
        path = (start,)
    if len(path) == board.goal:
        yield path

    for next_cell in board.avaiable_moves(start):
        if next_cell not in path:
            path += (next_cell,)
            yield from dfs_search(next_cell, path)

class Board(object):
    def __init__(self, width, length):
        self.width = width
        self.length = length
        self.goal = width * length

    def is_legit_move(self, cell):
        row, col = cell
        return (row >= 0 and row <= self.width-1) and (col >=0 and col <= self.length-1)

    def avaiable_moves(self, cell):
        ret = []
        r, c = cell
        tmp = [[r+1, c-2], [r+2, c-1], [r+2, c+1], [r+1, c+2],\
               [r-1, c-2], [r-2, c-1], [r-2, c+1], [r-1, c+2]]
        for elem in tmp:
            if self.is_legit_move(elem):
                ret.append(elem)
        return ret


texts:
I would be thankful for feedback for following html5 markup.
The outer div (class articles) has no more meaning as setting flex for it's child elements. Is a div the semantically correct choice in this case?

.articles {
  display: flex;
}

.articles__article {
  flex: 1;
}

Headline

Text Text Text

Headline

Text Text Text


texts: Implementation of a singleton HttpClient with generic methods

texts:
I need advice for this implementation that I made for a service access portable class library referenced to Xamarin.Android and Xamarin.Ios projects. For now, it works fine, but I have doubts about its performance or if it would crash on simultaneous calls.

public class HttpClientBase : HttpClient
{

    private static readonly HttpClientBase instance = new HttpClientBase();

    static HttpClientBase() { }

    private HttpClientBase() : base()
    {
        Timeout = TimeSpan.FromMilliseconds(15000);
        MaxResponseContentBufferSize = 256000;
    }

    public static HttpClientBase Instance
    {
        get
        {
            return instance;
        }
    }

    public async Task<List<T>> GetListItems<T>(string Url)
    {
        var uri = new Uri(string.Format(Constantes.BaseUrlApi, Url));
        var response = await GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            var Items = JsonConvert.DeserializeObject<List<T>>(content);
            return Items;
        }
        throw new Exception(response.ReasonPhrase);
    }

    public async Task<T> GetItem<T>(string Url)
    {
        var uri = new Uri(string.Format(Constantes.BaseUrlApi, Url));
        var response = await GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            var Item = JsonConvert.DeserializeObject<T>(content);
            return Item;
        }
        throw new Exception(response.ReasonPhrase);
    }

    public async Task PostItem<T>(T item, string url)
    {
        var uri = new Uri(string.Format(Constantes.BaseUrlApi, ""));
        var json = JsonConvert.SerializeObject(item);
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        HttpResponseMessage response = null;
        response = await PostAsync(uri, content);
        if (response.IsSuccessStatusCode)
        {
            return;
        }
        throw new Exception(response.ReasonPhrase);
    }
}


texts:
public boolean isNaN(String string){

@SuppressWarnings("unused")
BigDecimal bg = null;

try{

    bg = new BigDecimal(string);

}catch(Exception e){

    return true;
}

return false;
}

There is no native isNaN method for BigDecimal.  The thing I don't like about this method is the suppressed warning. I never use the variable but only the constructor to see if it doesn't throw an exception.  If it does, I return the corresponding boolean.

What do you think?


texts:
Is this a practical algorithm for pattern matching in a text? Assume text can be very large, is there anything I can do to speed up the performance?

 public static int match(String pattern, String text) {
    int i = 0;
    int M = pattern.length();
    int N = text.length();
    int ret = -1;
    while (i < N) {
        StdOut.printf("i = %d\n", i);
        int j = 0;
        ret = i;
        while (j < M) {
            if (pattern.charAt(j) == text.charAt(i)) {
                ++i;
                ++j;
                continue;
            } else {
                ++i;
                break;
            }
        }
        if (j == M) return ret;
    }
    return -1;
}


texts: Loading Configurations from plist into singleton

texts:
In my iOS application, I've created a singleton class that reads a configuration plist file and provides accessor methods to easily retrieve the values:

class Configuration{

    struct Key{
        static let searchRadius = "searchRadius"
        static let significantUserMovementThreshold = "movementThreshold"
    }

    enum ConfigurationError : ErrorType{
        case FileNotFound
    }

    static let sharedInstance = Configuration()
    var configDictionary : NSDictionary?

    func loadConfigurationFromPropertyList() throws{

        if let filePath = NSBundle.mainBundle().pathForResource("Config", ofType: "plist"){
            self.configDictionary = NSDictionary(contentsOfFile: filePath)
        }else{
            throw ConfigurationError.FileNotFound
        }

    }

    func searchRadius()-> Double?{
        return configDictionary?.objectForKey(Key.searchRadius) as? Double
    }

    func significantUserMovementThreshold() -> Double?{
        return configDictionary?.objectForKey(Key.significantUserMovementThreshold) as? Double
    }

}

In the AppDelegate, I call Configuration.loadConfigurationFromPropertyList to load the configurations into memory.

I have a number of questions regarding this approach:

Is it a good idea to have accessor method for each property in the configuration file? I think it provides a cleaner and more reliable approach than using subscripts.
Is it better for the Configuration class to read the file in its constructor or that AppDelegate invoke loadConfigurationFromPropertyList()?


texts:
I have some code that is used to convert a decimal currency to an integer with precision being a function of which currency is being converted.

This code is more of a "brute-force" method to do the conversion and just doesn't feel right to me. Is there a better way to achieve the result?

    public static int CurrencyToInt(decimal amount, string currencyCode)
    {
        var precision = 0;

        currencyCode = currencyCode?.ToUpperInvariant();

        if (new[] {
            "BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"
        }.Contains(currencyCode))
        {
            precision = 3;
        }
        else if (new[] {
            "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BMD",
            "BND", "BOB", "BRL", "BSD", "BTN", "BWP", "BZD", "CAD", "CDF", "CHF", "CNY", "COP", "CRC", "CUC", "CUP",
            "CZK", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GGP", "GHS", "GIP",
            "GMD", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "IMP", "INR", "IRR", "JEP", "JMD",
            "KES", "KGS", "KHR", "KPW", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LVL", "MAD", "MDL",
            "MKD", "MMK", "MNT", "MOP", "MUR", "MVP", "MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK",
            "NPR", "NZD", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "QAR", "RON", "RSD", "RUB", "SAR", "SBD", "SCR",
            "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SPL", "SRD", "STD", "SVC", "SYP", "SZL", "THB", "TJS", "TMT",
            "TOP", "TRY", "TTD", "TVD", "TWD", "TZS", "UAH", "USD", "UYU", "UZS", "VEF", "WST", "XCD", "XDR", "YER",
            "ZAR", "ZMW", "ZWD"
        }.Contains(currencyCode))
        {
            precision = 2;
        }
        else if (new[] {
            "MGA", "MRO"
        }.Contains(currencyCode))
        {
            precision = 1;
        }
        else if (new[]{
            "BIF", "BYR", "CLP", "CVE", "DJF", "GNF", "ISK", "JPY", "KMF", "KRW", "PYG", "RWF", "UGX", "VND", "VUV",
            "XAF", "XOF", "XPF"
        }.Contains(currencyCode))
        {
            precision = 0;
        }
        else
        {
            throw new ArgumentException("Unknown currency code " + currencyCode, nameof(currencyCode));
        }

        while (precision > 0)
        {
            amount *= 10;
            precision--;
        }

        return (int)Math.Floor(amount);
    }


texts:
Yes, I know there are plenty of libraries to get this done (Q, step, async), but only for learning I'm wondering if the following code is ok and usable or have major drawbacks and it is only usable at a small programs.

Usage:

var g = new Manager();

g.then (
    function() {
        console.log("hello");
        setTimeout( function () { g.done("hello done") }, 2000 );
    }
);

g.start();

g.then (
    function() {
        console.log("two");
        g.done ("two done");
    }
);

g.then (
    function(resp) {
        console.log("I got: " + resp);
        setTimeout( function () { g.done("happy ending") }, 2000 );
    }
);

g.then (
    function(resp) {
        console.log("last msg: " + resp);
        g.done();
    }
);

Class:

//...............................
// class Manager
//...............................
function Manager () {
    this.functionList = [];
    this.allDone = false;
} // ()

//...............................
//...............................
Manager.prototype.then = function (fun) {
    this.functionList.push (fun);
    if (this.allDone) {
        this.allDone = false;
        this.done(this.previousResult);
        console.log ( "then(): continuing");
    }

} // ()

//...............................
//...............................
Manager.prototype.done = function (prevRes) {
    this.previousResult = prevRes;
    if ( this.where <= this.functionList.length-2 ) {
        this.where++;
        this.functionList [this.where](this.previousResult);
    } else {
        this.allDone = true;
        console.log ( "done(): stopping because allDone: where=" + this.where + " and length = " + this.functionList.length);
    }

} // ()

//...............................
//...............................
Manager.prototype.start = function () {
    this.allDone = false;
    this.where=-1;
    this.done();
} // ()


texts:
I frequently need to obtain some info about coordinates, because I have dynamic elements on a map (in Openlayers). So I use SetInterval and XMLHttpRequest Object to do it.

window.onload = function () {
    var requestURL = "data.geojson";
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState == 4) {
            console.clear();
            console.log(request.response);
        }
    }
    var prueba = setInterval(function () {
        request.open('GET', requestURL, true);
        request.setRequestHeader('authenticated_user', 'terrain');
        request.send();
    }, 2000);
}

Is It the correct way?


texts:
I have been learning programming in Python recently and I got a task to program a library in OOP. You can add books to a library, search for a specific book according to the ISBN, name of the author or search books which cost less than price. Everything seems to be okay, but I am new to OOP so I would like to hear some advice on whether it is programmed a "good way" or not.

class Library(object):
    books = []
    written_by_author = []
    books_under_price = []

    def __init__(self, name, author, isbn, price):
        self.name = name
        self.author = author
        self.isbn = isbn
        self.price = price

    def addBook(self):
        Library.books.append((self.name,self.author,self.isbn,self.price))

    def searchBookISBN(self,isbn):
        for book in Library.books:
            if book[2]==isbn:
                return book

    def searchBookAuthor(self,author):
        for book in Library.books:
            if book[1]==author:
                Library.written_by_author.append(book)
        return Library.written_by_author

    def searchUnderPrice(self,price):
        for book in Library.books:
            if book[3]<price:
                Library.books_under_price.append(book)
        return Library.books_under_price

book = Library('Geometry', 'Jeff Potter', '0596805888', 22)
book.addBook()
book = Library('Math', 'George Harr', '0594805888', 15)
book.addBook()
book = Library('English', 'James Odd', '0596225888', 10)
book.addBook()
book = Library('Physics','Jeff Potter','0597884512',18)
print (book.searchBookISBN('0594805888'))
print (book.searchBookAuthor('George Harr'))
print (book.searchUnderPrice(20))


texts: Count number of occurences of a digit in the range

texts:
Left limit, right limit and the digit to be counted is entered. This code works only for whole numbers i. e. from 0 to n. This code returns the number of occurence of the digit n in the given range. Please review this code and suggest improvements.

#include <iostream>

int count_n(int l, int r, int n)
{
    if (r <= l)
    {
        std::cerr << "Right limit must greater then left limit\n";
        return 0;
    }

    if (l < 0)
    {
        std::cerr << "Only positive integers\n";
        return 0;
    }

    int count = 0;
    for (int i = l; i <= r; ++i)
    {
        int i_copy = i;
        while (i_copy != 0)
        {
            if (i_copy % 10  == n)
            {
                count++;
            }
            i_copy = i_copy / 10;
        }
    }
    return count;
}

int main()
{
    int left_limit, right_limit, num;
    std::cout << "Enter left limit, right limit and the number(Only positive numbers)\n";
    std::cin >> left_limit >> right_limit >> num;

    int result = count_n(left_limit, right_limit, num);
    std::cout << result << "\n";
}

Output:

Enter left limit, right limit and the number(Only for positive numbers)
1 20 0
2


texts:
A purchase order has an order ID, a customer ID, total price and line items. Line items can be a product or membership type.

Business rules:

If the purchase order contains a membership, it has to be activated in the customer account immediately.
If the purchase order contains "Comprehensive First Aid training video," then "Basic First Aid training video" is added to the purchase order

public abstract class Product
{
}
 public class BookClubMembership : Product
{
    public bool IsActivated { get; set; }
}

Using the strategy design pattern, I define the first rule as follows:

public class BookClubMembershipRule : IPurchaseOrderRule
{
    readonly ICustomerActivationService _customerActivationService;

    public BookClubMembershipRule(ICustomerActivationService customerActivationService)
    {
        _customerActivationService = customerActivationService;
    }
    public void Execute(PurchaseOrder order)
    {
        foreach(var product in order.Items) {
            if (product is BookClubMembership)
            {
                _customerActivationService.ActivateBookMembership(order.CustomerId, product as BookClubMembership);
                break;
            }
        }

    }
}

public class PurchaseOrderProcessor
{
    public IList<IPurchaseOrderRule> Rules { get; }

    public PurchaseOrderProcessor(List<IPurchaseOrderRule> rules)
    {
        Rules = rules;
    }

    public void ProcessOrder(PurchaseOrder order)
    {
        foreach (var rule in Rules)
            rule.Execute(order);
    }

I don't feel comfortable using C# is and as above. Is there a better way for me to program these rules. I was thinking of Visitor pattern but given the 2nd rule. I will need to operate on the order and the item as well.

A line item is what I call an item in an order. For example, an order can look like this:

Order No: 3344656
 Total: 48.50
 Customer Id: 4567890
 Line items:
  • Video "Comprehensive First Aid Training"
  • Book "The Girl on the train"
  • Book Club Membership

Added code for the second rule:

public class ComprehensiveVideoRule : IPurchaseOrderRule
{
    public void Execute(PurchaseOrder order)
    {
        bool addNewVideo = false;
        foreach(var item in order.Items)
        {
            if(item is Video)
            {
                var checkItem = item as Video;
                if(checkItem.Title.Contains("Comprehensive"))
                    addNewVideo = true;
            }
        }
        if(addNewVideo) order.Items.Add(new Video("Basic First Aid"));
    }
}


texts: Simple random falling object animation in Java

texts:
I am new to programming but I tried to make my code as readable as possible! Hopefully you can see what it does before you run the program. I did not implement an ups or fps controller, the animation may be fast for some computers and slower for others.

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class App extends JPanel {

    //changing these values will change the size of the game, while still remaining functional
    //within the size limit specified.
    static int windowWidth = 1300;
    static int windowHeight = 800;

    int randNumb = 0;
    int squareWidth = 25;
    int squareHeight = 25;
    int squareYLocation = -squareHeight;
    boolean numberCreated = false;
    static boolean gameRunning = false;

    //generates a random Y value inside the window for the square to spawn at
    public void generateRandomNumber() {
        Random rand = new Random();
        randNumb = rand.nextInt(windowWidth - squareWidth);
        numberCreated = true;
    }

    //paints a black screen, then paints a rectangle on top of the black screen
    public void paint(Graphics g) {
        g.setColor(Color.black);
        g.fillRect(0, 0, windowWidth, windowHeight);
        g.setColor(Color.BLUE);
        g.fillRect(randNumb, squareYLocation, squareWidth, squareHeight);
    }

    public void update() {

        //calls the generateRandomNumber() method which gives the square a random x value inside the screen
        if (!numberCreated) {
            generateRandomNumber();
        }
        //moves the squares y coordinate towards the bottom of the screen and stops once it hits the bottom
        if (squareYLocation <= windowHeight) {
            squareYLocation++;

            //resets the x and y location to a new position
        } else {
            numberCreated = false;
            squareYLocation = -squareHeight;
        }
    }

    //sets the while loop to true to start the game
    public void start() {
        gameRunning = true;
    }

    public static void main(String[] args) throws InterruptedException {

        App game = new App();
        JFrame frame = new JFrame();
        frame.add(game);
        frame.setVisible(true);
        frame.setSize(windowWidth, windowHeight);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Raining Squares");
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);

        game.start();

        //updates square position, repaints square, and slows down update and paint speed.
        while (gameRunning) {
            game.update();
            game.repaint();
            Thread.sleep(1);
        }
    }
}


texts: Project Euler Q2 - Sum of even Fibonacci numbers

texts:
I'm very new at F#, and am using Project Euler to help me learn. Question #2 kept me going for a while, as my initial attempt at an answer was very slow and inelegant. Then I learnt about Seq.unfold, and a whole new vista unfolded in front of me!

The problem statement is as follows (source):

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

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

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

Please can you comment on this code. Bear in mind I'm very new at this, so I may be doing it completely wrong!

let fibEvenSum max =
  let rec fibEven n =
    match n with
    | 0 -> 0
    | 1 -> 2
    | n -> 4 * (fibEven (n - 1)) + (fibEven (n - 2))
  1 |> Seq.unfold (fun n -> Some(fibEven n, n+1))
    |> Seq.takeWhile (fun n -> n < max)
    |> Seq.sum

If I run it like this, I get the right answer:

sumOfEvenFibs 4000000I

Is there a better way to do it?


texts:
I've got a form that needs validating before the data in the form is added to a service queue:

self.ee.on('validateForm', function(formData){

            // Validation
            var isValid = false;
            var validTitle = false;
            var validDescription = false;
            var validObjectives = false;
            var validOutcome = false;
            var validHours = false;

            if(formData.title==null){
                console.log("error on title")
                isValid = false;
            }
            else{
                validTitle = true;
                console.log("title is valid");
            }

            if(formData.description==null){
                console.log("error on description")
                isValid = false;
            }
            else{
                validDescription = true;
                console.log("description is valid");
            }

            if(formData.objectives==null){
                console.log("error on objectives")
                isValid = false;
            }
            else{
                validObjectives = true;
                console.log("objectives is valid");
            }

            if(formData.outcome==null){
                console.log("error on outcome")
                isValid = false;
            }
            else{
                validOutcome = true;
                console.log("outcome is valid");
            }

            if(formData.hours== null){
                console.log("Error on hours")
                isValid = false;

            }
            else{
                validHours = true;
                console.log("hours is valid");
            }

            if(validTitle && validDescription && validObjectives && validOutcome && validHours){
                isValid = true;
            }

            if (isValid) {
                self.ee.emit('formIsValid', formData);
            } else {
                self.ee.emit('formIsInvalid', formData);
            }
        });

It works fine, if all the conditions are met it passes onto my formisvalid function, which creates the message and adds and it to the service queue fine.

Is there a nicer/better way of doing the above?


texts:
What is more readable? value / 60 / 60, value / 3600, or Hours{static_cast<Minutes>(*this).value / 60}? Should I use constants, i.e. SECONDS_IN_HOURS.
Should I use the explicit keyword? Would it actually prevent stupid mistakes/silent bugs? Or would it become annoying to have to cast everything?
It is easy to "glaze" over the following code and miss mistakes (for example, mixing up multiplication and dividing, using 24 instead of 60 when converting hours to minutes). How should it be refactored? I'm not sure if toSeconds, toMinutes is better than Second::operator Minutes() in terms of clarity.
What happens if I add days, and then weeks, and so on? It would require duplicating code and keeping track of what I have already and haven't already implemented. This is basically an extension to number 3 in terms of refactoring: how should I define them in terms of the other to avoid duplication?

#include <iostream>

struct Seconds;
struct Minutes;
struct Hours;
struct Seconds
{
    int value;
    operator Minutes() const;
    operator Hours() const;
};
struct Minutes
{
    int value;
    operator Seconds() const;
    operator Hours() const;
};
struct Hours
{
    int value;
    operator Minutes() const;
    operator Seconds() const;
};
Seconds::operator Minutes() const
{
    return Minutes{value / 60};
}
Seconds::operator Hours() const
{
    return Hours{static_cast<Minutes>(*this).value / 60};
}
Minutes::operator Seconds() const
{
    return Seconds{value * 60};
}
Minutes::operator Hours() const
{
    return Hours{value / 60};
}
Hours::operator Minutes() const
{
    return Minutes{value * 60};
}
Hours::operator Seconds() const
{
    return Seconds{static_cast<Minutes>(*this).value * 60};
}

int main()
{
    Minutes m{60};
    Seconds s{3600};
    Hours h{1};
    std::cout << (static_cast<Seconds>(m).value == s.value);
    std::cout << (static_cast<Seconds>(h).value == s.value);
    std::cout << (static_cast<Minutes>(s).value == m.value);
    std::cout << (static_cast<Minutes>(h).value == m.value);
    std::cout << (static_cast<Hours>(s).value == h.value);
    std::cout << (static_cast<Hours>(m).value == h.value);
    return 0;
}


texts: csvshuf: a tool to shuffle CSV columns written in Python

texts:
Edit: After reading Gareth's answer I have pushed an updated version of the code to github.

I needed to shuffle cells from specific columns in several CSV files. One of the requirements was to be able to do derangement (shuffling that leaves no element in its original place), I read about Sattolo's algorithm.

So I started writing csvshuf this afternoon. Code was originally based in csvcut. I tried to make it good but I am sure it can be improved as I have little experience programming in Python. I would be grateful if I get some code review.

Code:

import csv
import sys
import random
import getopt

# From https://softwareengineering.stackexchange.com/q/218255/149749
def shuffle_kfy(items):
    i = len(items) - 1
    while i > 0:
        j = random.randrange(i + 1)  # 0 <= j <= i
        items[j], items[i] = items[i], items[j]
        i = i - 1
    return items

def shuffle_sattolo(items):
    i = len(items)
    while i > 1:
        i = i - 1
        j = random.randrange(i)  # 0 <= j <= i-1
        items[j], items[i] = items[i], items[j]
    return items

def shuffle(items, mode):
    if mode == 'kfy':
        return shuffle_kfy(items)
    if mode == 'sattolo':
        return shuffle_sattolo(items)

    random.shuffle(items)
    return items

opts, args = getopt.getopt(sys.argv[1:], "c:C:d:o:q:tks", [])
if args:
    i = open(args[0], 'U')
else:
    i = sys.stdin

delimiter = ','
output_delimiter = ','
cols = None
no_cols = None
quotechar = None
search_mode = ''

if opts:
    opts = dict(opts)
    if '-c' in opts:
        cols = map(int, opts['-c'].split(','))
    elif '-C' in opts:
        no_cols = map(int, opts['-C'].split(','))
    if '-k' in opts:
        search_mode = 'kfy'
    elif '-s' in opts:
        search_mode = 'sattolo'
    if '-t' in opts:
        delimiter = "\t"
    elif '-d' in opts:
        delimiter = opts['-d']
    if '-o' in opts:
        output_delimiter = opts['-o']
    if '-q' in opts:
        quotechar = opts['-q']

if cols and 0 in cols or no_cols and 0 in no_cols:
    print("Invalid column 0. Columns are 1-based")
    exit(1)

reader = csv.reader(i, delimiter=delimiter, quotechar=quotechar)
headers = next(reader)

table = []
for c in range(len(headers)):
    table.append([])

for row in reader:
    for c in range(len(headers)):
        table[c].append(row[c])

if not cols and not no_cols:
    cols = range(len(headers))
elif no_cols:
    cols = list(set(range(len(headers))) - set(no_cols))

for c in cols:
    if c > len(headers):
        print('Invalid column {}. Last column is {}').format(c, len(headers))
        exit(1)
    table[c - 1] = shuffle(table[c - 1], search_mode)

table = zip(*table)

writer = csv.writer(sys.stdout, delimiter=output_delimiter)
writer.writerow(headers)
for row in table:
    writer.writerow(row)

Usage:

csvshuf -c1 foobar.csv
(shuffles the first column of each row of foobar.csv using Python's shuffle())

svshuf -c2 -k foobar.csv
(shuffles the second column of each row using Knuth-Fischer-Yeats algorithm.)

svshuf -c3 -s foobar.csv
(shuffles the third column of each row using Sattolo's algorithm.)

csvshuf foobar.csv
(shuffles all the columns of foobar.csv)

csvshuf -C1 foobar.csv
(shuffles all the columns but the first of foobar.csv)

head -10 foobar.csv | csvshuf -c 1,3
(shuffles the first and third columns of the first ten lines of foobar.csv)

csvshuf -c1,3 -d "|" foobar.csv
(shuffles the first and third columns of the pipe-delimited foobar.csv)

csvshuf -c 1,3 -t foobar.csv
(shuffles the first and third columns of the tab-delimited foobar.csv if present, the -d option will be ignored.)

csvshuf -c 1,2,3 -d "|" -o , foobar.csv
(shuffles the first three columns of the pipe-delimited foobar.csv; output will be comma-delimited.)

csvshuf -c 1,2,3 -o "|" foobar.csv
(shuffles the first three columns of the comma-delimited foobar.csv; output will be pipe-delimited.)

csvshuf -c 1,2 -d "," -q "|" foobar.csv
(shuffles the first two columns of the comma-delimited, pipe-quoted foobar.csv.)


texts:
I've implemented the following nub' or "give distinct elements of list" function:

nub' :: (Eq a) => [a] -> [a]
nub' [] = []
nub' xs = nubHelper xs []

nubHelper :: (Eq a) => [a] -> [a] -> [a]
nubHelper []     acc = acc
nubHelper (y:ys) acc = if(contains y acc)
                         then nubHelper ys acc
                         else nubHelper ys (acc ++ [y])
                         where contains match acc =
                            foldl (\as x -> if(y == x) then True else as) False acc

Example:

*Main> nub' [1,2,1,1,1,1,3,4,3,1]
[1,2,3,4]

Surely there must be a cleaner way?


texts: Pure CSS Responsive Show more / Show less

texts:
I have put together a CSS snippet to responsively display a Show more / Show less button if content of list cannot fit 1 line (1em) when you resize the window using pseudo-elements.

Currently, I have added an ul:after element with a solid white bg to hide the Show more/less button when content does not overflow 1 line. Could not think of anything else but my solution seems a walkaround only like when there is a hole in the wall and you just hide it with a picture. Is there a better way to achieve this via CSS only? I am not sure if this solution can be buggy in some cases? Also, if I want to add a background image to the whole website, this item with its solid background would mess things up for example..

http://jsfiddle.net/6sj4e/524/

html:

<input id="toggle" type="checkbox">

Item #1

Item #2

Item #3

Item #4

Item #5

Item #6

css:

nav {
    position: relative;
    border: 1px solid #000;
    overflow: hidden;
}
nav ul {
    overflow: hidden;
    line-height: 1em;
    list-style-type: none;
    margin: 0;
    padding: 0;
    max-height: 1em;
    margin-bottom: 1em;
}
nav ul li{
    display:inline-block;
    padding: 0 1em 0 0;
}

input {
    display: none;
}
label {
    position: absolute;
    top: 100%;
    margin-top:-1em;
}
label:before {
    content: "Show More";
    cursor: pointer;
}
nav ul:after {
    content: '';
    position: absolute;
    display: block;
    height: 1em;
    width: 100%;
    background: white;
}

input:checked ~ ul {
    max-height: 100%;
}
input:checked + label:before {
    content: "Show Less";
}
input:checked ~ ul:after {
    display: none;
}


texts: Display the difference between DataFrames' dtypes?

texts:
I recently updated Pandas and noticed that it is no longer possible to merge DataFrames with mismatched dtypes. I have a script which relied on merging and seemed to work in the past despite having mismatched dtypes. I need to display to the user which columns in two dataframes are causing problems, so the user can then adjust the types accordingly. (Specifically, one dataframe is read in from a database and represents what is currently in the DB, while the second dataframe includes any changes/new data to be applied to the database. Once the the user finds the problem columns they can determine if the DataFrame that contains the changes was meant to change the database's type or whether there is an error in the changes). The following code appears to work, but I feel like pandas must have a built in better way to deal with this problem.

def get_mismatched_dtypes(self, df1, df2):
    mismatch = {}
    for key, val in df1.dtypes.iteritems():
        if key in df2.dtypes and df2.dtypes[key] != val:
            mismatch[key] = (f"df1:{val}, df2: {df2.dtypes[key]}")
    print(mismatch)
    return mismatch


texts: Destroying a process if it takes too much time

texts:
I am executing a shell script from my Java program using Process and I want to kill/destroy that process if my script takes long time.

I came up with this code and wanted to see if there is any better way or anything I can improve on.

public class Test {

    public static void main(String[] args) throws IOException, InterruptedException {

        // Your script
        String script = getScriptTextFromSomewhere();

        // create a temp file and write your script to it
        File tempScript = File.createTempFile("temp_scripts_", "");
        tempScript.setExecutable(true);
        try (OutputStream output = new FileOutputStream(tempScript)) {
            output.write(script.getBytes());
        }

        // build the process object and start it
        List<String> commandList = new ArrayList<>();
        commandList.add(tempScript.getAbsolutePath());
        ProcessBuilder builder = new ProcessBuilder(commandList);
        builder.redirectErrorStream(true);
        builder.environment().put("param1", "abc");
        builder.environment().put("param2", "xyz");
        Process shell = builder.start();

        // read the output and show it
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(shell.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }

        // wait for the process to finish
        WaitingThread thread = new WaitingThread(shell);
        thread.start();
        long timeoutMillis = 20000;
        thread.join(timeoutMillis);
        if(thread.isAlive()) {
            thread.interrupt();
        }

        if(!thread.isFinished()) {
            shell.destroy();
            shell.waitFor();
            System.out.println("PROCESS WAS INTERRUPTED");
        } else {
            // check the exit code (exit code = 0 usually means "executed ok")
            System.out.println("PROCESS FINISHED, EXIT CODE: " + thread.getExitValue());
        }

        // delete temp file
        tempScript.delete();
    }
}

class WaitingThread extends Thread {

    private int exitValue;
    private Process shell;
    private boolean finished = false;

    public WaitingThread(Process shell) {
        this.shell = shell;
    }

    @Override
    public void run() {
        try {
            exitValue = shell.waitFor();
            finished = true;
        } catch (InterruptedException e) {
            finished = false;
        }
    }

    public int getExitValue() {
        return exitValue;
    }

    public boolean isFinished() {
        return finished;
    }

}


texts: php one-time prepared statement execution function

texts:
I use prepared statements often even when I only need to execute the statement once (for security), so I implemented a function to abstract away all the function calls on the mysqli_stmt object, as well as bind_param()'s first argument since as far as my tests show it works identically even when int parameters are marked as strings.

<?php
$conn = new mysqli('localhost', 'name', 'password', 'db');

if ($conn->connect_error)
    die('Connection to database failed: ' . $conn->connect_error);

function stmt($query, $params){

   array_unshift($params, str_repeat('s', sizeof($params)));
   for($i = 1; $i < sizeof($params); $i++){
      $params[$i] = &$params[$i];
   }

   $stmt = $GLOBALS['conn']->stmt_init();
   $stmt->prepare($query);
   $method = new ReflectionMethod('mysqli_stmt', 'bind_param');
   $method->invokeArgs($stmt, $params);
   $stmt->execute();

   if($stmt->error){
      $result = ['error' => $stmt->error];
   } else {
      $result = $stmt->get_result();
   }

   $stmt->close();
   return $result;
}
?>

Usage example:

<?php
   $result = stmt('SELECT * FROM table_name WHERE id IN(?,?,?)', [1,2,3]);
?>


texts: Improved minimal webcrawler - why is it so slow?

texts:
I recently made a webcrawler that I submitted here for a review:

Minimal webcrawler - bad structure and error handling?

With that help, I've made a much cleaner and better(?) webcrawler.

The only problem I have is that this crawler is extremely slow compared to the other one (13.2s for a depth of 5, compared to 1.3s on the old solution).

Why is it so slow?
With cProfile I have gotten this output over the 10 most time consuming functions. With depth 5, 57 links are crawled or scheduled for crawling - while is_valid_link are called 243 times. Could there be some errors in that method?

from bs4 import BeautifulSoup
import httplib
import urlparse
import urllib2
import time

def sanitize(url, parent):
    if is_internal_link(url):
        if parent.endswith("/") or url.startswith("/"):
            return parent + url
        else:
            return parent + "/" + url
    return url

def is_internal_link(url):
    if url.startswith("http"):
        return False
    return True

def hostname(link):
    hostname = urlparse.urlparse(link).hostname
    return hostname

def get_server_status_code(link):
    # http://stackoverflow.com/questions/1140661
    host, path = urlparse.urlparse(link)[1:3]
    try:
        conn = httplib.HTTPConnection(host)
        conn.request('HEAD', path)
        return conn.getresponse().status
    except StandardError:
        return None

def is_valid_link(link):
    link = sanitize(link, hostname(urlsToCrawl_Parent[0]))
    # http://stackoverflow.com/questions/2924422
    good_codes = [httplib.OK, httplib.FOUND, httplib.MOVED_PERMANENTLY]
    return get_server_status_code(link) in good_codes

def fetch_webpage(url):
    webpage = urllib2.urlopen(url)
    return webpage

def fetch_links(webpage):
    html = webpage.read()
    soup = BeautifulSoup(html)
    links = soup.find_all("a", href=True)
    return links

def schedule_link(link):
    if is_valid_link(link):
        if hostname(link) in urlsToCrawl_Parent[0]:
            urlsToCrawl_Parent.append(link)
    else:
        urlsToCrawl_Child.append(link)

def havent_visited(link):
    if link not in urls_Crawled and link not in urlsToCrawl_Parent and link not in urlsToCrawl_Child:
        return True
    else:
        return False

def crawl(url):
    webpage = fetch_webpage(url)
    links = fetch_links(webpage)
    for link in links:
        link = link['href']
        #This is not done on a good way at all, should clearly do this in fetch_links?
        if havent_visited(link):
            schedule_link(link)

if __name__ == "__main__":
    urls_Crawled = []
    urlsToCrawl_Parent = []
    urlsToCrawl_Child = []

    urlsToCrawl_Parent.append("STARTLINK")
    while (len(urls_Crawled) < 5):
        if (len(urlsToCrawl_Parent) > 0):
            crawl(urlsToCrawl_Parent[0])
            urls_Crawled.append(urlsToCrawl_Parent[0])
            urlsToCrawl_Parent.pop(0)

        elif (len(urlsToCrawl_Child) > 0):
            urlsToCrawl_Parent.append(urlsToCrawl_Child[0])
            crawl(urlsToCrawl_Parent[0])
            urls_Crawled.append(urlsToCrawl_Parent[0])
            urlsToCrawl_Parent.pop(0)


texts:
I explain the nonlinear correlation coefficients in this paper and provided the code in this post.  The nonlinear nonparametric regression is an extension of this work and its description can be found in the linked paper.  In short, the subset means are the regression points and we can achieve a better fit by increasing the order and number of partitions.  Below is an example of the progression of orders.

Here is the regression routine which also uses the partition mapping from the nonlinear correlation routine in the linked post:

VN_Regression = function (x, y,order=max(2,ceiling(log10(length(x)))),degree = 1){

  temp_df = data.frame(x=x, y=y)
  temp_df[,'temp_part'] = 'p'
  temp_df[,'master_part'] = 'p'

  regression.points = data.frame(matrix(ncol = 2))
  Regression.Coefficients = data.frame(matrix(ncol=3))

  names(Regression.Coefficients) = c('Coefficient','X Lower Range','X Upper Range')

  if(order==1){return("Please Increase the Order Specification")}

  if(order >1){
    for(i in 1:(order-1)){

      for(item in unique(temp_df$master_part)){
        tmp_xbar = mean(temp_df[temp_df$master_part == item,'x'])
        tmp_ybar = mean(temp_df[temp_df$master_part == item, 'y'])

        temp_df[temp_df$x >= tmp_xbar & temp_df$y >= tmp_ybar & temp_df$master_part == item,'temp_part'] = paste(temp_df[temp_df$x >= tmp_xbar & temp_df$y >= tmp_ybar & temp_df$master_part == item,'master_part'], 0, sep = '')
        temp_df[temp_df$x <= tmp_xbar & temp_df$y >= tmp_ybar & temp_df$master_part == item,'temp_part'] = paste(temp_df[temp_df$x <= tmp_xbar & temp_df$y >= tmp_ybar & temp_df$master_part == item,'master_part'], 1, sep = '')
        temp_df[temp_df$x >= tmp_xbar & temp_df$y <= tmp_ybar & temp_df$master_part == item,'temp_part'] = paste(temp_df[temp_df$x >= tmp_xbar & temp_df$y <= tmp_ybar & temp_df$master_part == item,'master_part'], 2, sep = '')
        temp_df[temp_df$x <= tmp_xbar & temp_df$y <= tmp_ybar & temp_df$master_part == item,'temp_part'] = paste(temp_df[temp_df$x <= tmp_xbar & temp_df$y <= tmp_ybar & temp_df$master_part == item,'master_part'], 3, sep = '')

        if(nchar(item)==order-1){

        regression.points[item,] = cbind(tmp_xbar,tmp_ybar)
            }

      }

      temp_df[,'master_part'] = temp_df[, 'temp_part']
    }

  }

  ###Plotting and regression equation

  plot(x,y)

  ###Endpoints

  x0 = temp_df[order(temp_df$x),][1,2]
  x.max = temp_df[order(temp_df$x),][length(x),2]

  regression.points[1,2] = x0
  regression.points[1,1] = min(x)

  regression.points[length(regression.points[,2])+1,2] = x.max
  regression.points[length(regression.points[,1]),1] = max(x)

  points(na.omit(regression.points[order(regression.points),]),col='red',pch=15)

  lines(na.omit(regression.points[order(regression.points),]),col='red',lwd=3)

  ###Regression Equation

  regression.points = na.omit(regression.points[order(regression.points),])

  for(i in 1:(length(regression.points[,1]-1))){

  rise = regression.points[i+1,2] - regression.points[i,2]
  run = regression.points[i+1,1] - regression.points[i,1]

  Regression.Coefficients[i,] = c((rise/run),regression.points[i,1],regression.points[i+1,1])

  }

  print(na.omit(Regression.Coefficients))

  "Estimate = Difference in X from Lower Range * Coefficient"

}

And here is the example to generate the above image:

set.seed(123)
x=rnorm(1000)
y=x^3
par(mfrow=c(2,3))
for(i in 2:7) (VN_Regression(x,y,i))

Also, by calling the VN_dep function from the "Correlation and Dependence" post you can use the dependence as a weight to the order with:

VN_Regression = function (x, y,
            order=max(2,ceiling(VN_dep(x,y)*ceiling(log10(length(x))))),
            degree = 1){
            ...

Again, any insights on efficiency or improvements to the routine are welcomed.


texts: Better way to write list of places program

texts:
I wrote some code using meteor, which is working, but I don't know if I did it the best way.  I'm asking for opinions on other ways to perform this task.

It's just a list of places.  You can fill the textfield with a place and it'll appear on the list.  You have an option to remove the place by clicking on the "x".

Very simple, but I'm new to meteor.

place_list.js

   Places = new Meteor.Collection('placesNew');
   if(Meteor.isClient){
     Template.places_list.places = function(){
       return Places.find({},{sort:{name: 1}});
      console.log(Template.place_list.place);
     }

   Template.places_list.events({
     'blur .place': function (obj) {
       Places.insert({name: obj.target.value});
     },
     'click .plc_remove': function(obj){
       Places.remove( obj.toElement.attributes['data-ref'].value);
     }
   });
}

place_list.html

  <title>Place List</title>

Place List :

  {{> places_list}}

<template name="places_list">
  <input type="text" placeholder="Insert a place here" class="place" />

  {{#each places}}

 {{ name}} | x |

  {{/each}}

</template>


texts:
I am working on a way to parse data using xml.

The file that I am given contains lines that look like this:

George | Washington | Carver

or someone else can send me someting like  this

Carver | Washington | George

And so on...

No matter what the format is, whoever sends me the file will also send me rules on how to parse the file. In the first example, it's First Name | Middle Name | Last Name. And in the second example, it's Last Name | Middle Name | First Name

Instead of writing a special case for each possibility, I created an XML file to describe the meta data.

<file>
    <first>0</first>
    <middle>1</middle>
    <last>2</last>
</file>

For instance, in this case. The tag first corresponds to 0 indicating that first name occurs at the 0th position.

Intuitively, I thought about creating a dictionary, with the key set to be the tag, and the value to be the text. Like such...

    public static IDictionary<string, string> GetLookupTable(string xmlContents)
{
    XElement xmlElement = XElement.Parse(xmlContents);

    IDictionary<string, string> table = new Dictionary<string, string>();

    foreach (var element in xmlElement.Elements())
    {
        table.Add(element.Name.LocalName, element.Value);
    }

    return table;
}

However, I'm not really familiar with .NET implementation of things, which led me  to question some stuff.

Would it be better to just traverse XElement instead of creating a dictionary? I don't think this is a good idea since I believe that XElement traversal may invovle an unordered tree traversal to get what I need. Doing this for each property (I have more than just 3) would be very inefficient. I am just speculating here...
Is retrieval from dictionary constant time? I know that in Java HashMap has constant get. If that was the case for c# as well, then this would seem like a better route to go as I would just traverse once, and then be able to retrieve whatever I need in constant time.


texts:
I have some pretty basic Regex that scans the output of a HTML file (the whole document source) and attempts to extract all of the absolute links that look like images. Whether they are actually images or not isn't too important, as those checks would be made later.

I am just trying to see if this Regex looks okay, since I kind of hacked it together from various sources.

The Raw Regex Pattern:

\bhttps?:[^)''"]+\.(?:jpg|jpeg|gif|png)

The Regex in Practice (I am coding in Railo - an open source CFML engine):

<cfset variables.getImageURLs = reMatch('\bhttps?:[^)''"]+\.(?:jpg|jpeg|gif|png)', variables.getDocument) />

NOTE: variables.getDocument contains the raw HTML code.

It seems to work great right now and I'm not seeing any issues, but just wanting to know if you can see any potential pitfalls with this method? Is there room for improvement?


texts:
I have made a program that converts Celsius to Fahrenheit and Fahrenheit to Celsius. How is my code?
import java.util.Scanner;
public class TemperatureConversion {
    public static void main(String[] args) {
        double fahrenheit, celsius;
        Scanner input = new Scanner(System.in);
        //  Celsius to Fahrenheit \u2103 degree Celsius symbol
        System.out.println("Input temperature (\u2103): ");
        celsius = input.nextDouble();
        System.out.println(celsius * 1.8 + 32 + " \u2109 \n");

        // Fahrenheit to Celsius \u2109 degree Fahrenheit symbol
        System.out.println("Input temperature (\u2109: ");
        fahrenheit = input.nextDouble();
        System.out.print((fahrenheit - 32) / 1.8 + " \u2103");
    }
}


texts:
I wrote this little program, but I'm not sure if it's properly written.  Actually, it can't handle leap years (every year is 365 days long) and you have to write the earlier date before. It seems to be working correctly.

Can you tell me if it's okay or not, and what should I change in it to make it good?

#include <iostream>
using namespace std;

int first_date_month;
int first_date_days;
int first_date_year;
int second_date_month;
int second_date_days;
int second_date_year;
int days;

int month_days[] = {31,28,31,30,31,30,31,31,30,31,30,31};

int main()
{
    cout << "Enter first date: ";
    cin >> first_date_year >> first_date_month >> first_date_days;
    cout << "Enter second date: ";
    cin >> second_date_year >> second_date_month >> second_date_days;

    if(first_date_year == second_date_year)
    {
        if(first_date_month == second_date_month)
            days = second_date_days - first_date_days;
        else
        {
            for(int i = first_date_month; i < second_date_month-1;i++)
                days += month_days[i];
            days += month_days[first_date_month-1] - first_date_days + second_date_days;
        }
    }
    else
    {
        for(int i = 0; i < second_date_month-1; i++)
            days += month_days[i];
        for(int i = first_date_month; i < 12; i++)
            days += month_days[i];
        if(second_date_year - first_date_year >= 0)
        days += (second_date_year - first_date_year - 1)*365 +
            month_days[first_date_month-1] - first_date_days + second_date_days;
    }

    cout << "Days between the two dates: " << days;

    return(0);
}


texts:
A working example of mine, trying to streamlining my Django views, with absolute inspiration from Laravel:

class BaseController(View):
    template_404 = "404.html"

    def __call__(self, *args, **kwargs):
        return self.view(*args, **kwargs)

    def view(self, request, slug=None):
        method = request.method.lower()
        if hasattr(self, method):
            return getattr(self, method)(request, slug)
        return self.forbidden(request)

    def get(self, request, slug):
        if slug is not None:
            return getattr(self, "show")(request, slug) if hasattr(self, "index") else self.forbidden(request)
        return getattr(self, "index")(request) if hasattr(self, "index") else self.forbidden(request)

    def post(self, request, slug):
        return getattr(self, "store")(request) if hasattr(self, "store") else self.forbidden(request)

    @staticmethod
    def forbidden(request):
        return HttpResponseForbidden("Method not allowed")

    def page_not_found(self, request):
        return render(request, self.template_404)

Inherited by:

class EulerController(BaseController):
    template_name_index = "euler_index.html"
    template_name_show = "euler_show.html"

    def index(self, request):
        euler_posts = EulerPost.objects.all()
        return render(request, self.template_name_index, {"euler_posts": euler_posts})

    def show(self, request, slug):
        euler_post = EulerPost.objects.filter(slug=slug).first()
        return render(request, self.template_name_show, {"euler_post": euler_post})

and called by:

urlpatterns = [
    url(r'^$', EulerController(), name='main'),
    url(r'^(?P<slug>[\w-]+)/$', EulerController(), name='resource'),
]

and the mock model:

class EulerPost(model):
    slug = models.CharField(default=None, max_length=200, blank=False, unique=True)

I left Django for PHP-Laravel, long ago believing myself to be an to unstructured for the freedom of Django.  But now I feel I am on the right track.


texts:
Preface

I was trying to review this question on the same topic, but in the end many points I wanted to make were excellently explained by @ferada so I felt that posting my code and explaining the concepts around such changes would just be repetition.

Instead I am questioning whether my approach is over-engineered considering the simplicity of this task.

Specification

I consider two words to rhyme if they share a certain number of phonemes at the end.

The division of the words into phonemes is already given from input and must only be read into program data.

Data is fetched from the internet on the first run and stored in a local file for successive runs to save internet traffic and execution time.

Code

import doctest
import os
import re
import requests
from collections import namedtuple

URL = "http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b"
LIBRARY = "library.txt"
PHONEMES_TO_MATCH = 3

ReadingData = namedtuple("ReadingData", ["word", "phonemes"])

def first_and_others(xs):
    """
    >>> first_and_others([1, 2, 3])
    (1, [2, 3])
    """
    return xs[0], xs[1:]

def format_data(raw_data):
    '''
    Transforms a list of lines of the format
      WORD [SPACE] PHONEME1 [SPACE] PHONEME2 [SPACE] PHONEME3 ...
    into a list of `ReadingData` classes for easier further processing.

    >>> format_data(["ZURCHER Z ER1 K ER0", "ZUREK Z UH1 R EH0 K"])
    [ReadingData(word='ZURCHER', phonemes=['Z', 'ER1', 'K', 'ER0']), ReadingData(word='ZUREK', phonemes=['Z', 'UH1', 'R', 'EH0', 'K'])]
    '''
    return [ReadingData(*first_and_others(x.strip().replace('\n','').split()))\
             for x in raw_data \
              if not x.startswith(';;;')]

def write_url_to_filename(url, filename):
    response = requests.get(URL, stream=True)

    if not response.ok:
        raise Exception("Error writing {} to {}".format(url, filename))

    with open(filename, 'wb+') as f:
        for block in response.iter_content(4096):
            f.write(block)

def find(predicate, iterable):
    """
    >>> find(lambda x: x % 2 == 0, [1, 2, 3, 4])
    2
    """
    return next(i for i in iterable if predicate(i))

def last_items_match(a, b, how_many):
    """
    >>> last_items_match([1, 2, 3], [7, 2, 3], 2)
    True
    """
    return a[-how_many:] == b[-how_many:]

def find_rhymes(word, data, how_many_phonemes=2):
    """
    Finds all the words in `data` that rhyme with `word`, that is,
    all the words that end in the same `how_many_phonemes` phonemes.

    `word` itself is always included as each word rhymes with itself
    (except when it has less than `how_many_phonemes` phonemes).

    >>> find_rhymes("example", [ReadingData('EXAMPLE', ['IH0', 'G', 'Z', 'AE1', 'M', 'P', 'AH0', 'L']),
    ...                         ReadingData('AMPAL', ['AE1', 'M', 'P', 'AH0', 'L']),
    ...                         ReadingData('HAPPINESS', ['HH', 'AE1', 'P', 'IY0', 'N', 'AH0', 'S'])])
    [ReadingData(word='EXAMPLE', phonemes=['IH0', 'G', 'Z', 'AE1', 'M', 'P', 'AH0', 'L']), ReadingData(word='AMPAL', phonemes=['AE1', 'M', 'P', 'AH0', 'L'])]

    """
    this_phonemes = find(lambda line: line.word == word.upper(), data).phonemes
    return [candidate for candidate in data \
             if last_items_match(candidate.phonemes, this_phonemes, how_many_phonemes)]

def main():
    if not os.path.isfile(LIBRARY):
        write_url_to_filename(URL, LIBRARY)
    with open(LIBRARY) as f:
        data = format_data(f.readlines())
    print(find_rhymes("FORCE", data, PHONEMES_TO_MATCH)[:20])

if __name__ == "__main__":
    doctest.testmod()
    main()