texts: WorkGroup Data Service with JSON / Web based API

texts:
I'm wondering if this code can be made more clear and fluent:

using System;
using System.Threading.Tasks;
using Windows.Data.Json;
using System.Collections.ObjectModel;
using System.Net.Http;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using eTest.Space.Log;
using eTest.Space.Interface;
using eTest.Objects;

namespace eTest.Space.Services
{

    public class WorkGroupDataService : IWorkgroupDataService
    {

        public string WebApiUri
        {
            get { return Constants.ServerAddress; }
        }

        private ObservableCollection<IWorkgroup> Groups;// = new ObservableCollection<IWorkgroup>();

        public async Task<ObservableCollection<IWorkgroup>> GetAllWorkGroups()
        {
            Groups = new ObservableCollection<IWorkgroup>();
            //if (Groups.Count == 0)
            {
                Uri dataUri = new Uri(WebApiUri + "api/workgroup/");

                using (var client = new Windows.Web.Http.HttpClient())
                {
                    var response = await client.GetAsync(dataUri).AsTask(); ;

                    string jsonText = response.Content.ReadAsStringAsync().GetResults();
                    JsonArray jsonArray = JsonArray.Parse(jsonText);

                    foreach (JsonValue groupValue in jsonArray)
                    {
                        JsonObject groupObject = groupValue.GetObject();
                        IWorkgroup group = new Workgroup();
                        group.GroupState = (int)groupObject["GroupState"].GetNumber();
                        group.WorkgroupName = groupObject["WorkgroupName"].GetString();
                        group.WorkgroupSecretary = groupObject["WorkgroupProba"].GetString();
                        group.ObjectID = groupObject["ObjectID"].GetString();
                        Uri dataUri1 = new Uri(WebApiUri + "api/etest/" + group.ObjectID);
                        using (var client1 = new Windows.Web.Http.HttpClient())
                        {
                            var response1 = await client.GetAsync(dataUri1).AsTask();
                            if (response1.StatusCode == Windows.Web.Http.HttpStatusCode.Ok)
                            {
                                string jsonText1 = response1.Content.ReadAsStringAsync().GetResults();
                                List<TestSession> Test = JsonConvert.DeserializeObject<List<TestSession>>(jsonText1);
                                group.Test = Test;
                            }
                        }
                        if (group.Test.Count > 0)
                        {
                            Groups.Add(group);
                        }

                    }
                }
            }
            Groups = new ObservableCollection<IWorkgroup>(Groups.OrderByDescending((x => x.Test.Count)));
            return Groups;
        }
    }
}


texts: Design pattern for logger implementation

texts:
I have two classes ExceptionLog and DebugLog

public class ExceptionLog {
    public static String StackTrace {get; set;}
    public static String ClassName {get; set;}
    public static String MethodName {get; set;}
    public static String LogType {get;set;}
    public static Exception ex {get;set;}

    public Static void Debug(Exception ex)
    {
        logType = 'EXCEPTION';
        ex = ex;
        log();
    }

    public Static void log()
    {
        try
        {
            extractException();
            writeToObject();

        }
        catch(Exception e)
        {
            //new ExceptionLog().Module('LogException').log(e);
        }
    }

    public static void extractException()
    {
        // Logic here
    }

    public static void writeToObject()
    {
        // data save to object logic here
    }
}

and

public class DebugLog {
    public static String LogType {get;set;}
    public static String DebugMessage {get;set;}

    public Static void Debug(String message)
    {
        Debug(null, message);
    }

    public Static void Debug(LoggingLevel level, String message)
    {
        if(level != null )
        {
            LogType = String.valueOf(level);
        }

        DebugMessage = message;

        log();
    }

    public Static void log()
    {
        // Log logic here
    }

}

What I want to achieve is, write a controller class that will make decision of which debug method needs to be called

public class Log {
    public void Debug(String message)
    {
        DebugLog.Debug(message);
    }
    public void Debug(loggingLevel loggingLevel, String message)
    {
        DebugLog.Debug(loggingLevel, message);
    }
    public void Debug(Exception ex)
    {
        ExceptionLog.Debug(ex);
    }
}

That is, if I pass Exception in the debug method, it will call the ExceptionLog.Debug(ex) else it will call the debug method from DebugLog class.

What should be the aprroach here ?


texts:
Just on a chapter 3 of Rust Book so not much good in Rust.
so tried to implement a simple temprature calculator as suggest in this chapter.
so i would like you guys to point anything you feel

use std::io;

fn main() {
    println!("Enter Temperature as 56f or 98c");

    let mut usr_inpt = String::new();

    io::stdin()
        .read_line(&mut usr_inpt)
        .expect("can not read user input");

    let usr_inpt = usr_inpt.trim_end().to_lowercase();

    if usr_inpt.ends_with("f") || usr_inpt.ends_with("c") {
        // remove the last indication 56f -> 56 or 56c -> 56
        let _temp: String = usr_inpt.chars().take(usr_inpt.len() - 1).collect();
        let num: u32 = match _temp.parse() {
            Ok(num) => num,
            Err(_) => 0,
        };

        if usr_inpt.ends_with("f") {
            println!("celcius -> {}", (num - 32) * 5 / 9);
        } else if usr_inpt.ends_with("c") {
            println!("farenheit -> {}", num * 9 / 5 + 32);
        }
    } else {
        println!("invalid input");
    }
}


texts: Read binary serial data and parse integers

texts:
I'm reading serial data in binary format from a stream, and I'm not happy with how I extract the data because it takes so much operations to extract the binary data from a simple line of binary data.

Each line starts with a character indicating the type of data, and afterwards follow a few 16 bit integers (big endian), followed by a checksum character and a newline.

Here's a sample of what line would be after reading:

line = "F{3x 16 bit int big endian}{checksum character}\n"

This is the simplified code in question:

  byte[] b = new byte[2];
  System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

  // Check that the port is open. If not skip and do nothing
    if (SerialPort.IsOpen)
    {
        while(SerialPort.BytesToRead > 50){

            // read line and turn string in byte array
            string line = SerialPort.ReadLine();
            byte[] encoded = enc.GetBytes(line);

            if (line[0]=='F'){

                // copy 16 bit int into byte-array
                Array.Copy(encoded, 1, b, 0, 2);
                // -> big endian
                Array.Reverse(b);

                // turn into integer
                short value1 = BitConverter.ToInt16(b, 0);

                Array.Copy(encoded, 3, b, 0, 2);
                Array.Reverse(b);
                short value1 = BitConverter.ToInt16(b, 0);

                Array.Copy(encoded, 5, b, 0, 2);
                Array.Reverse(b);
                short value3 = BitConverter.ToInt16(b, 0);
            }

        }
        this.bytesAvailable = SerialPort.BytesToRead;

Is there a smarter way to accomplish the result of my code above?


texts:
I'm learning Go, so I decided to make a Brain-flak interpreter for practice.

package main

import (
    "fmt"
    "strings"
    "bufio"
    "os"
)

var openToClose map[rune]rune = map[rune]rune {
    '(': ')',
    '[': ']',
    '{': '}',
    '<': '>',
    '&': '^',
}

var bracketNames map[rune]string = map[rune]string {
    '(': "round",
    '[': "square",
    '{': "curly",
    '<': "angle",
    '&': "internal",
}

type bracket struct {
    bracketType rune
    subExprs []bracket
}

func (b bracket) String() string {
  var stringSubs []string
  for _, subExpr := range b.subExprs {
    stringSubs = append(stringSubs, subExpr.String())
  }
  return bracketNames[b.bracketType] + "(" + strings.Join(stringSubs, ", ") + ")"
}

type stack []int

func (s *stack) push(val int) {
    *s = append(*s, val)
}

func (s *stack) pop() int {
    var size int = len(*s)
    if size == 0 {
        return 0
    } else {
        var val int = (*s)[size - 1]
        *s = (*s)[:size - 1]
        return val
    }
}

func (s stack) peek() int {
  var size int = len(s)
  if size == 0 {
    return 0
  } else {
    return s[size - 1]
  }
}

type environment struct {
    active stack
    inactive stack
}

func (e *environment) swap() {
    e.active, e.inactive = e.inactive, e.active
}

func (e *environment) push(val int) {
    e.active.push(val)
}

func (e *environment) pop() int {
    return e.active.pop()
}

func (e environment) peek() int {
  return e.active.peek()
}

func (e environment) size() int {
    return len(e.active)
}

func (e *environment) EvalArgs(args []bracket) int {
  var result int = 0
  for _, arg := range args {
    result += e.EvalArg(arg)
  }
  return result
}

func (e *environment)EvalArg(arg bracket) int {
  var nilad bool = len(arg.subExprs) == 0
  var name string = bracketNames[arg.bracketType]
  var args = arg.subExprs
  switch name {
  case "round":
    return e.round(args, nilad)
  case "square":
    return e.square(args, nilad)
  case "curly":
    return e.curly(args, nilad)
  case "angle":
    return e.angle(args, nilad)
  case "internal":
    return e.EvalArgs(args)
  default:
    panic("Tried to execute bad command " + name)
  }
}

func (e *environment) round(args []bracket, nilad bool) int {
  if nilad {
    return 1
  } else {
    var result int = e.EvalArgs(args)
    e.push(result)
    return result
  }
}

func (e *environment) square(args []bracket, nilad bool) int {
  if nilad {
    return e.size()
  } else {
    return -e.EvalArgs(args)
  }
}

func (e *environment) curly(args []bracket, nilad bool) int {
  if nilad {
    return e.pop()
  } else {
    var result int = 0
    for e.peek() != 0 {
      result += e.EvalArgs(args)
    }
    return result
  }
}

func (e *environment) angle(args []bracket, nilad bool) int {
  if nilad {
    e.swap()
  } else {
    e.EvalArgs(args)
  }
  return 0
}

func (e *environment) Interpret(code string) int {
  return e.EvalArgs(Parse(code))
}

func parseHelper(code []rune, index int) (bracket, int) {
    var openingBracket rune = code[index]
    var closingBracket rune = openToClose[openingBracket]
    var subExprs []bracket = []bracket{}
    var currInd int = index + 1
    var newExpr bracket
    for code[currInd] != closingBracket {
        newExpr, currInd = parseHelper(code, currInd)
        subExprs = append(subExprs, newExpr)
    }
    return bracket{openingBracket, subExprs}, currInd + 1
}

func Parse(code string) []bracket {
  parsed, _ := parseHelper([]rune("&" + code + "^"), 0)
  return parsed.subExprs
}

func main() {
    var e environment
    codeReader := bufio.NewReader(os.Stdin)
    for {
      code, _ := codeReader.ReadString('\n')
      code = strings.Trim(code, "\n")
      fmt.Println(code)
      fmt.Println(e.Interpret(code))
    }
}

My main questions are:

Is there a better way to implement that switch statement? It doesn't
really follow DRY.
Would it be better to replace the "internal" bracket system with
the loop in parseHelper?
How could I make this shorter and more readable?


texts: Implement bash auto completion in Python

texts:
I created a script supposed to use python to autocomplete Python commands. The full code is available here, however, I can give you an example. For instance, let's consider:

command, the command I want to give completion to (it does not have to actually exist).
script.py, the auto completion script.

import os, shlex

def complete(current_word, full_line):
    split = shlex.split(full_line)
    prefixes = ("test", "test-中文", 'test-한글')
    items = list(i + "-level-" + current_word for i in prefixes)
    word = "" if len(split) - 1 < int(current_word) else split[int(current_word)]
    return list(i for i in items if i.startswith(word))

if __name__ == "__main__":
    os.sys.stdout.write(" ".join(complete(
            *os.sys.argv.__getitem__(slice(2, None)))))
    os.sys.stdout.flush()

The following script can be executed directly into the shell, or added in the .bashrc to keep the changes persistent.

__complete_command() {
    COMPREPLY=($(python3 script.py complete $COMP_CWORD "${COMP_LINE}"));
};
complete -F __complete_command command

Tested on Ubuntu 18.04 with python 3.8.
If you want, you can type the following in a new console

cd $(mktemp -d)
__complete_command() {
    COMPREPLY=($(python3 script.py complete $COMP_CWORD "${COMP_LINE}"));
};
complete -F __complete_command command
echo '
import os, shlex

def complete(current_word, full_line):
    split = shlex.split(full_line)
    prefixes = ("test", "test-中文", "test-한글")
    items = list(i + "-level-" + current_word for i in prefixes)
    word = "" if len(split) - 1 < int(current_word) else split[int(current_word)]
    return list(i for i in items if i.startswith(word))

if __name__ == "__main__":
    os.sys.stdout.write(" ".join(complete(
            *os.sys.argv.__getitem__(slice(2, None)))))
    os.sys.stdout.flush()' > script.py

Is it the most efficient way to do this?


texts: How well or poorly structured are my routes in this NodeJS app?

texts:
This is for an app built with Express. One of my concerns is the routes ending with / which I did because our previous site was an ASP app. So they named the folders that way for SEO purposes, then the page would be index.aspx .But in my case I just did, for example

science.jade and routed it from /science-bruxzir-zirconia-dental-crown/

Here is what I got for routes

app.js

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon(path.join(__dirname, 'public/images/template/favicon.ico')));
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', function(req, res){
  res.render('home', {
    title: 'Home'
  });
});

app.get('/features-bruxzir-zirconia-dental-crown/', function(req, res){
  res.render('features', {
    title: 'BruxZir Features'
  });
});

app.get('/science-bruxzir-zirconia-dental-crown/', function(req, res){
  res.render('science', {
    title: 'Scientific Validation'
  });
});

app.get('/video-bruxzir-zirconia-dental-crown/', function(req, res){
  res.render('videos', {
    title: 'BruxZir Video Gallery'
  });
});

app.get('/cases-bruxzir-zirconia-dental-crown/', function(req, res){
  res.render('cases', {
    title: 'Before & After Case Gallery'
  });
});

app.get('/testimonials-bruxzir-zirconia-dental-crown/', function(req, res){
  res.render('testimonials', {
    title: 'Bruxzir Testimonials'
  });
});

app.get('/authorized-bruxzir-labs-zirconia-dental-crown/', function(req, res){
  res.render('labs', {
    title: 'Authorized BruxZir Labs'
  });
});

app.get('/contact-bruxzir-zirconia/', function(req, res){
  res.render('contact', {
    title: 'Bruxzir Contact Form'
  });
});

app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});


texts:
I need some opinion if my code below is proper for an async process. This code only reformats text. Please let me know if this implementation is not proper or needs some improvement.

static void Main(string[] args)
{
    Task.Factory.StartNew(() => ReadCharacter("File 1.txt"));
    Task.Factory.StartNew(() => ReadCharacter("File 2.txt"));
    Console.WriteLine("Main Task");
    Console.ReadLine();
}

static void ReadCharacter(string inputFile)
{
    string result;
    using (StreamReader sr = new StreamReader(inputFile))
    using (StreamWriter sw = new StreamWriter(string.Format("C:\\Out--{0}",inputFile)))
    {
        Console.WriteLine("Opening file : {0}", inputFile.ToString());
        while (!sr.EndOfStream)
        {
            result = sr.ReadLine();
            sw.WriteLine(string.Format("{0} --> {1}",result,Task.CurrentId.ToString()));
        }
        Console.WriteLine("Finish {0}", inputFile);
        sr.Close(); sw.Close();
    }
}


texts: Determining whether a loop iterated at least one element in generator function

texts:
I have a case in which I need to determine whether a for loop yielded at least one element:

@property
def source_customers(self):
    """Yields source customers"""
    for config in RealEstatesCustomization.select().where(
            RealEstatesCustomization.customer == self.cid):
        yield config.source_customer
    # Yield self.customer iff database
    # query returned no results
    try:
        config
    except UnboundLocalError:
        yield self.customer

Is this a pythonic way to go or shall I rather use a flag for that like so:

@property
def source_customers(self):
    """Yields source customers"""
    yielded = False
    for config in RealEstatesCustomization.select().where(
            RealEstatesCustomization.customer == self.cid):
        yield config.source_customer
        yielded = True
    # Yield self.customer iff database
    # query returned no results
    if not yielded:
        yield self.customer

What is preferable?


texts: Output JavaScript object into HTML table of key-value pairs using jQuery

texts:
This function is meant to take an object, loop through the key-values and generate/build a HTML table at a particular ID:

function insertBasicTable(basic_data, insert_id) {
  /* Insert the key/value pairs into a table element on the DOM.

  basic_data = object containing key/value pairs
  insert_id  = the id on the DOM to insert the table into

  Intentionally not including closing tags in the jquery requests;
  http://stackoverflow.com/a/14737115/2355035 */

  table_id = '#' + insert_id;
  var array_length = Object.keys(basic_data).length;
  var array_obj_names = Object.keys(basic_data);

  // create the table header
  $(table_id).empty();
  $(table_id).append('
');
  $(table_id).find('thead:last').append('Tag');
  $(table_id).find('thead:last').append('Data');

  // begin the table body and iterate through key/value pairs
  $(table_id).append('
');
  for (var i = 0; i < array_length; i++) {
    var attr_name = array_obj_names[i];
    var tag       = '' + array_obj_names[i];
    var data      = '' + basic_data[attr_name];

    $(table_id).find('tbody:last').append('
' + tag + data);
  }
}

This function is then used, along with a number of D3 scripts, to populate elements on the DOM:

linePlot.render(someObject.modules.qual.quintiles);
boxPlot.render(someObject.modules.qual.quintiles);
insertBasicTable(someObject.modules.basic, 'basic-stats-table');
// etc, etc...

Any comments about how this is being achieved? Am I overlooking either a basic tenant of how JS "should" be used (this is a huge side-effect for instance, should I be returning a formatted string then placing that string into the DOM for instance) or over-complicating things by jQuery'ing a bunch of times?


texts:
Right now I'm creating a community. You can register and create your own profile and post on a forum etc. I'm just doing this for fun and learning. I'm not planning on becoming a professional programmer this is just a hobby of mine.

Anyway, I want do it right though. Please review my script and tell me if it seems OK and safe. And please if you have a suggestion or anything go ahead.

This is the login (I use sessions):

// Trim values sent from form
$username = trim($_POST['username']);
$password = trim($_POST['password']);

// Get user info and their rights matching login attempt
$stmt = $db->prepare("SELECT id, username, g_can_delete_users, g_can_edit_post, g_can_handle_reports FROM users LEFT JOIN groups ON groups.g_id = users.group_id WHERE users.username = ? AND SHA1(CONCAT(users.salt, ?)) = users.password");
$stmt->execute(array($username, $password));
$row = $stmt->fetch();

// Did we find a match?
if ($row) {
    $_SESSION['user'] = $row;
    header("Location: index.php");
    exit;
} else {
header("Location: index.php");
exit;
}

And the registration part:

// Example of a generated salt: &O93Wrl`x#iY

$username = trim($_POST['username']);
$email = strtolower(trim($_POST['email']));
    $password1 = trim($_POST['password1']);
    $password2 = trim($_POST['password2']);

    // Validate the username
    if (strlen($username) < 4)
        $errors[] = "Username must be at least 4 characters.";
    // ... and the password
    else if (strlen($password1) < 4)
        $errors[] = "Password too short";
    else if ($password1 != $password2)
        $errors[] = "Passwords do not match";
    else

$stmt = $db->prepare("INSERT INTO users (username, password, email, salt, registered, registration_ip) VALUES (:username, :password, :email, :salt, :registered, :registration_ip)");
        $stmt->execute(array(':username'=>$username, ':password'=>sha1($salt.$password1), ':email'=>$email, ':salt'=>$gen_salt, ':registered'=>time(), ':registration_ip'=>$_SERVER['REMOTE_ADDR']));


texts: Searching a Join List for an index Attempt #2

texts:
Originally I posted this incorrect attempt - Searching a Join List for an index.

Given a JoinList:

data JoinList m a = Empty
                  | Single m a
                  | Append m (JoinList m a) (JoinList m a)
    deriving (Eq, Show)

where m represents the size of the JoinList, find the element (Maybe a) at the given index in the JoinList structure.

indexJ :: (Sized b, Monoid b) => Int -> JoinList b a -> Maybe a
indexJ _ Empty             = Nothing
indexJ i (Single _ x)
  | i == 0                 = Just x
  | otherwise              = Nothing
indexJ i (Append _ left right)
  | leftHt > i             = indexJ i left
  | (rightHt + leftHt) > i = indexJ (i-leftHt) right
  | otherwise              = Nothing
  where leftHt  = (getSize. size . tag) left
        rightHt = (getSize. size . tag) right

where tag =

tag :: Monoid m => JoinList m a -> m
tag Empty          = mempty
tag (Single x _)   = x
tag (Append x _ _) = x

Testing

Data

jlIndex2 :: JoinList Size String
jlIndex2 = Append (Size 3)
                       (Single (Size 1) "foo")
                       (Append (Size 2)
                             (Single (Size 1) "bar")
                             (Single (Size 1) "baz"))

jlIndex3 :: JoinList Size String
jlIndex3 = Append (Size 4) (Single 1 "biz") jlIndex2

Tests

*JoinList> indexJ 3 jlIndex3
Just "baz"
*JoinList> indexJ 0 jlIndex3
Just "biz"
*JoinList> indexJ 100 jlIndex3
Nothing

Note - I would've used QuickCheck, but I'm not sure how to use it with algebraic data types.


texts: C function to find and delete a node from a singly linked list

texts:
I'm looking for the most commonly used style for writing the delete_item() function of a singly linked list, that find a matching item and deletes it. Is what I have the 'typical' or 'normal' solution? Are there more elegant ones?

What seems inelegant to me about my solution below, although I don't know a better way to express it, is that the code needs to check the first record individually (i.e. a special case), then as it goes through the iteration, it's not checking iter, it's checking iter->next, ahead of the iterator's present location, because in a singly linked list you can't go backwards.

So, is there a cleaner way to write the delete_item() function?

#include <stdio.h>
#include <stdlib.h>

struct node {
    int x;
    struct node *next;
};

struct node *head;

struct node *create_item(int x);
void print_list();
void delete_item(int x);

int main(int argc, int argv) {

    struct node *n;
    int i;

    // initialise a linked list with a few items
    head = create_item(1);
    n = head;

    for (i = 2; i < 10; i++) {
        n->next = create_item(i);
        n = n->next;
    }

    // before
    print_list();

    // delete 7.
    delete_item(7);

    // after
    print_list();

    // lets delete all odd numbers for effect.
    delete_item(1);
    delete_item(3);
    delete_item(5);
    delete_item(9);

    print_list();
}

struct node *create_item(int x) {
    struct node *new;

    new = (struct node *) malloc (sizeof(struct node));
    new->x = x;
    return new;
}

void print_list() {
    struct node *iter;

    iter = head;

    while (iter != NULL) {
        printf("num: %i\n", iter->x);
        iter = iter->next;
    }
}

//We're looking for the best way to right this.
//This is _my_ standard solution to the problem.
// (that is, to test the first element explicitly
// the use current->next != NULL to be one behind
// the search).
//I wondered what other people's is or if there
//is a convention?
void delete_item(int x) {

    struct node *iter;
    iter = head;

    if (iter == NULL) {
        printf("not found\n");
        return;
    }

    if (iter->x == x) {
        printf("found in first element: %i\n", x);
            head = head->next;
        return;
    }

    while (iter->next != NULL) {
        if (iter->next->x == x) {
            printf("deleting element: %i\n", x);
            iter->next = iter->next->next;
            return;
        }

        iter = iter->next;
    }

    printf("not found\n");
}

This is a complete example that can be compiled and tested. The output:

23:28: ~$ gcc -o ll linked_list.c
23:28: ~$ ./ll
num: 1
num: 2
num: 3
num: 4
num: 5
num: 6
num: 7
num: 8
num: 9
deleting element: 7
num: 1
num: 2
num: 3
num: 4
num: 5
num: 6
num: 8
num: 9
found in first element: 1
deleting element: 3
deleting element: 5
deleting element: 9
num: 2
num: 4
num: 6
num: 8


texts: Streaming floating point data in Python2

texts:
I am in the process of creating a brain-computer interface, and one task is to stream electroencephalograph (EEG) data into a Python script for real-time analysis. Included in this question are two Python scripts: (1) to generate and stream fake EEG data (32 random floating points for testing purposes), and (2) to receive the EEG data and convert it to a numpy array of the shape (n_channels, n_samples). The second script extracts a sliding window of the last X seconds of data.

Generate and stream synthetic EEG data

# file is named "stream_eeg_realtime.py"
import random, threading, time

nominal_srate = 500.  # sampling rate in Hz. Must be float.
sleep_time = 1/nominal_srate

# Define all of the channel names.
channels = ['Fp1','Fp2','AF3','AF4','F3','F4','F7','F8','FC5','FC6','T7','T8',
'FC1','FC2','C3','C4','CP5','CP6','P7','P8','CP1','CP2','P3','P4','01','02',
'PO3','PO4','Oz','Pz','Cz','Fz']

one_sample = [round(random.uniform(-4.,4.), 5) for _ in channels]
data = []

datalock = threading.RLock()
def synthesize_data():
    while True:
        with datalock:
            data.append(one_sample)
        time.sleep(sleep_time)

t1 = threading.Thread(target=synthesize_data, name="EEG")
t1.daemon = True
t1.start()
print("Now streaming synthetic data...")

Receive and convert data to Numpy array (Jupyter Notebook)

In [1]:
import numpy as np
import stream_eeg_realtime as ser

DATA_DURATION = 20
sfreq = float(ser.nominal_srate)
last_rows_index = int(DATA_DURATION*sfreq)
thread_lock = ser.datalock
def get_data(raw_data, index, thread_lock, full_data=False):
    # Data comes in as array-like with shape (n_samples, n_channels).
    with thread_lock:
        if full_data==False:
            d = [row[:] for row in raw_data[-index:]]
        # If we want all of the data, instead of the X-second window.
        elif full_data==True:
            d = [row[:] for row in raw_data]
    data = np.array(d, dtype="float64").T
    return data

In [2]:
raw_array = get_data(ser.data, last_rows_index, thread_lock, full_data=False)
print raw_array.shape

This code has to be as fast as possible. I optimized the code as much as I could as an advanced-beginner, but can I make it faster? Is it OK to use threading in this case, or would multiprocessing be better? (I have no idea how to use multiprocessing)

Here are some things I tried before arriving at the code I posted. At first, I tried to append "columns" to the nested lists with list comprehension. That was fast, but it turns out it is much faster to append "rows" (no list comprehension needed) and then transpose. I also tried to deepcopy the list in the second script, and then I used nested list comprehension to make a copy. Using the slicing syntax in the list comprehension was the fastest method to copy the list.


texts: Given two vectors of ints, determine whether one vector is a prefix of the other

texts:
Given two vectors of ints, write a program to determine whether one vector is a prefix of the other.

For vectors of unequal length, compare the number of elements of the smaller vector.
For example, given the vectors containing 0, 1, 1, 2, and 0, 1, 1, 2, 3, 5, 8, respectively, your program should return true.

#include <vector>
#include <iostream>

int main()
{
    const std::vector<int> ivec1 = { 0, 1, 1, 2 };
    const std::vector<int> ivec2 = { 0, 1, 1, 2, 3, 5, 8 };

    const decltype(ivec1.size()) size = ivec1.size() < ivec2.size() ? ivec1.size() : ivec2.size();
    const std::vector<int>& smallVec = ivec1.size() < ivec2.size() ? ivec1 : ivec2;
    const std::vector<int>& bigVec = smallVec == ivec1 ? ivec2 : ivec1;

    bool bPrefix = true;
    for(decltype(ivec1.size()) i = 0; i < size; ++i)
    {
        if(smallVec[i] != bigVec[i])
        {
            bPrefix = false;
            break;
        }
    }

    std::cout << "small vector:\n";
    for (const auto i : smallVec)
        std::cout << i << ", ";
    std::cout << "\nIs prefix of big vector:\n";
    for (const auto i : bigVec)
        std::cout << i << ", ";
    std::cout << "\n" << (bPrefix ? "true" : "false") << std::endl;
}


texts:
I found myself needed zip but for dictionaries, and wanted to know if there is any way I can make this shorter and more concise, and/or faster. Also I cannot figure out what the type hinting might be for the return (I would like to put it in the reStructuredText).

def dict_zip(*args):
    """The zip utility but for dictionaries

    :param args:
        A bunch of **identical** dicts
    :type args:
        dict
    :return:
        A dict of all the keys in the input dict,
        mapped to a list of all the values fro that key
    :rtype:
        dict
    """
    out = {i: [] for i in args[0]}
    for dic in args:
        for key in out:
            out[key].append(dic[key])
    return out

if __name__ == "__main__":
    dict1 = {"first": True, "name": "John"}
    dict2 = {"first": False, "name": "sue"}
    print dict_zip(dict1, dict2)

Output:

{'name': ['John', 'sue'], 'first': [True, False]}


texts: Selecting one MySQL date with month reduced by one

texts:
I was thinking in a way to improve the following query if possible:

SELECT CONCAT(DATE_FORMAT(start_date, '%Y'), ',',
       (MONTH(start_date) -1), ',', DATE_FORMAT(start_date, '%d')) as start_date
FROM PROJECTS

I need start_date in this format: dd/mm-1/yyyy.

Note: I am using an API that use month from 0 to 11, and MySQL uses 1 to 12 – that's why I need month - 1.


texts:
I have a script that makes use of datetime in order to name files.

Only business days (Mon - Fri) are used.

Here is my part of the code that finds the last business day:

lastBusDay = datetime.datetime.today()
shift = datetime.timedelta(max(1,(lastBusDay.weekday() + 6) % 7 - 3))
lastBusDay = lastBusDay - shift
yesterday = lastBusDay.strftime('%d%m%y')

These variables are outside of any function and are the first part of my script after the imports. I've heard that global variables are bad, and I understand why.

But does this fall under the same category?

Only the yesterday variable is used later on in the script and is used to specify the new name in an the os.renames function.


texts:
A covering array is an \$N \times k\$ array in which each element is a from a set of \$v\$ symbols, and for every \$t\$ columns, every possible set of \$v^t\$ choices of the symbols appears at least once. The covering array number \$\mathrm{CA}(t,k,v)\$ is the smallest \$N\$ for which a covering array exists, given \$t\$, \$k\$, and \$v\$. A list of known covering array numbers (CANs) is available here.

I want to parse all of the known CANs from these pages and to find how "efficient" they are—what I mean by this is the ratio of \$\mathrm{CA}(t,k,v)\$ compared to \$v^t\$.

I developed Python code that access every covering array page, and parses the tables. I then sort the list of covering arrays by this ratio, and plot it using matplotlib.pyplot (using a log-scale for the y axis).

from urllib.request import urlopen
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt

# covering array object
class CAElement:
    def __init__(self, N, t, k, v):
        self.N = N
        self.t = t
        self.k = k
        self.v = v
    def set_ratio(self, ratio):
        self.ratio = ratio
    def __str__(self):
        return "CA(N=%d; t=%d, k=%d, v=%d) -> %f" % (self.N, self.t, self.k, self.v, self.ratio)

CAArray = []

# iterate over v, t in the known table ranges
for v in range(2, 26):
    for t in range(2, 7):
        # download the webpage and find the elements
        url = "http://www.public.asu.edu/~ccolbou/src/tabby/%d-%d-ca.html" % (t, v)
        response = urlopen(url)
        soup = BeautifulSoup(response)
        tables = soup.findChildren('table')
        table = tables[0]
        rows = table.findChildren('tr')

        # iterate over all rows in the one table
        for row in rows:
            cells = row.findChildren('td') # has all of the table's elements
            elements = []
            for cell in cells:
                value = cell.string
                if value is not None and value != "k" and value != "N" and value != "Source":
                        elements.append(value)
            if len(elements) >= 2:
                kParsed = int(elements[0])
                NParsed = int(elements[1])
                element = CAElement(NParsed, t, kParsed, v)
                ratio = element.N / pow(element.v, element.t)
                element.set_ratio(ratio)
                CAArray.append(element)

# sort by N/(v^t)
CAArray.sort(key=lambda x: (x.ratio, x.N, x.v, x.t, x.k), reverse=True)

# print each element (in sorted order)
for element in CAArray:
    print(element)

# plotting - using log scale for y axis
# each point is colored according to t (i.e., the "strength" of the CA)
xs = range(0, len(CAArray))
ys = [y.ratio for y in CAArray]
colors = {2:"red", 3:"blue", 4:"green", 5:"yellow", 6:"orange"}
plt.scatter(xs, ys, c=[colors[x.t] for x in CAArray])
plt.axis([min(xs), max(xs), min(ys), max(ys)])
plt.yscale('log')
plt.show()

This code does exactly what I want it to do. However, there are some problems:

Accessing the webpages is somewhat slow, and could be faster.
The code does not seem very Pythonic (and by making it so could make iterating over the array much faster).

Any suggestions are welcome!


texts: Size improvements for cat reimplementation

texts:
I have written a reimplementation of cat that will be compliant with most scripts, and that is as small and fast as possible. Can anybody suggest some size improvements for it?

#include <stdio.h>              /* we need printf, fprintf, FILE,
                         * fopen, fclose and that sort of
                         * stuff */
#include <stdlib.h>             /* for exit, EXIT_SUCCESS, and
                         * EXIT_FAILURE */

int main(int argc, char *argv[])
{
    FILE *fp;               /* file to cat */
    short int ch;               /* character to print */
    unsigned short int cp;          /* currently printing argv[?] */
    unsigned short int failed = 0;      /* how many failed to print */

    if (argc < 2) {             /* if not enough args act as pipe */
        for (;;) {          /* infinite loop */
            if ((ch = fgetc(stdin)) == EOF) {
                exit(EXIT_SUCCESS);
            } else {
                printf("%c", ch);
            }
        }
    }

    for (cp = 1; cp <= argc - 1; cp++) {    /* for each file in cli args */
        fp = fopen(argv[cp], "r");  /* open the file */

        if(fp == NULL) {
            fprintf(stderr, "%s: cannot open %s\n", argv[0], argv[cp]);
            failed++;       /* increment the number of failed */
            continue;       /* go back to beginning */
        }

        while ((ch = fgetc(fp)) != EOF) {
            printf("%c", ch);
        }

        fclose(fp);         /* close the file */
    }

    exit(failed);               /* exit with the number of files */
}                       /* that failed */

I'm sorry that the indentation is messed up, I use tabs in my code.

In clang version 3.5.0 on Ubuntu the generated binary size is 5200 bytes with these options:

-Oz -fomit-frame-pointer -s

Improvements

I added some more error checking, added -u and - and also wrote a function that writes out a file to avoid repeating myself. Also changed short int to int, printf to putchar, and some other things.

#include <stdio.h>              /* we need printf, fprintf, FILE,
                         * fopen, fclose and that sort of
                         * stuff */
#include <stdlib.h>             /* for exit, EXIT_SUCCESS, and
                         * EXIT_FAILURE */
#include <string.h>             /* need strcmp */

void write_file(char *file, char *progname) /* function to print individual file */
{
    FILE *fp;               /* file to write */
    int ch;                 /* temporary variable */

    if (strcmp(file, "-") == 0) {       /* check if using stdin */
        fp = stdin;         /* use standard input */
    } else {
        fp = fopen(file, "r");      /* open file for writing */
    }

    if (fp == NULL) {           /* error in opening file */
        fprintf(stderr, "%s: cannot open %s\n", progname, file);
        exit(EXIT_FAILURE);
    }

    while ((ch = fgetc(fp)) != EOF) {
        if (putchar(ch) == EOF) {
            fprintf(stderr, "%s: can't read %s\n", progname, file);
            exit(EXIT_FAILURE);
        }
    }

    if (ferror(fp) != 0) {          /* IO error, perhaps? */
        fprintf(stderr, "%s: error reading %s\n", progname, file);
        exit(EXIT_FAILURE);
    }

    if (strcmp(file, "-") != 0) {       /* close the file unless stdin */
        fclose(fp);
    }

    return;
}

int main(int argc, char *argv[])
{
    unsigned short int cp = 1;      /* currently printing argv[?] */

    if (argc < 2) {             /* act as pipe */
        write_file("-", argv[0]);
        exit(EXIT_SUCCESS);
    }

    if (strcmp(argv[1], "-u") == 0) {   /* support -u option for SUS compat */
        cp++;               /* increment the argv pointer var */
    }

    for (; cp <= argc - 1; cp++) {      /* for each file in cli args */
        write_file(argv[cp], argv[0]);  /* print the file */
    }

    exit(EXIT_SUCCESS);
}


texts: Login Script Utilising List Comprehension

texts:
This a fairly basic script I made for use in some other projects, nothing too complex or sophisticated and obviously lacking in some features (Password/Username encryption, Missing file contingencies etc.).

It loads a text file (formatted as USERNAME, PASSWORD\nUSERNAME, PASSWORD\n) into a 2D array, then checks the inputs against it, until 2 separate logins are used.

I'm what I'd consider intermediate in terms of python competency, but there are always things to be improved upon: any suggestions? I tend to use something similar to this for all projects that require a login, so any improvements or areas to look into, no matter how minor, would be greatly appreciated.

def login():
    player_count, details = 0, [[data.strip() for data in line.split(",")] for line in open("username_password.txt", "r").read().splitlines()]
    while player_count != 2:
        username, password = input("USERNAME"), input("PASSWORD")
        for data in details:
            if username == data[0] and password == data[1]:
                print("LOGIN CORRECT")
                details.pop(details.index(data))
                player_count += 1
                break
        else:
            print("INCORRECT")
    main()

def main():
    print("LOGGED IN\nMAIN")

login()


texts:
It seems odd that state must be passed around all the time. Can't State module hold itself, so I could do something like

state = %State{size: size}
case state.is_full? do
    ...

Here state is always passed. I suppose this is how it is in FP?

defmodule Chatter.Room do
  use GenServer

  defmodule State do
    defstruct size: 3, players: []

    def is_full?(state) do
      Enum.count(state.players) >= state.size
    end

    def add_player(state, player) do
      case State.is_full?(state) do
        true -> {:room_is_full, state}
        _    -> {:ok, append_player(state, player)}
      end
    end

    defp append_player(state, player) do
      %{state | players: state.players ++ [player]}
    end
  end

  def open(size) do
    {:ok, pid} = GenServer.start_link(__MODULE__, %State{size: size})
    pid
  end

  def join(room, user) do
    GenServer.call(room, {:join, user})
  end

  def players(room) do
    GenServer.call(room, :players)
  end

  def init(state) do
    {:ok, state}
  end

  def handle_call(:players, _from, state) do
    {:reply, state.players, state}
  end

  def handle_call({:join, player}, _from, state) do
    case State.add_player(state, player) do
      {:ok, state} -> {:reply, :ok, state}
      {error, state} -> {:reply, error, state}
    end
  end
end


texts: Using phantom types to represent amounts and exchange rates of currencies

texts:
I posted the following snippet to StackOverflow, and someone said there was much to be improved.

{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}

class (Show a) => Currency a where unphantom :: a

data USD = USD deriving Show
data EUR = EUR deriving Show

instance Currency USD where unphantom = USD
instance Currency EUR where unphantom = EUR

data Amount a where
  Amount :: Currency a => Float -> Amount a
instance Show (Amount a) where
  show (Amount x) = show x ++ show (unphantom :: a)

data Rate a b where
  Rate :: (Currency a, Currency b) => Float -> Rate a b
-- ...

Having to define an unphantom function for each currency is a bit annoying but I don't really see a way around it. Also, note that my use of Float to represent monetary values is just a placeholder.

How can I improve this code?


texts: I was wondering if there was a better way to improve my XNA joystick code? (Vb. Net)

texts:
I'm on a high school robotics team and I'm trying to code a Xbox 360 controller so that it'll controller the motors with variable speed. So far it works alright, but where I'm quite the novice coder I'd like to have more experienced eyes peer at my code and see if they can find a better way, or more effective way to do the same thing. As of now, as the code shows, when the sticks are moved it causes the value (-1 to 1) to be multiplied by 100 and sent to the motor controller as a value for its speed. A timer is also attached to continuously update the values to have the most accuracy possible. So far the only issue I've encountered is a minor dead zone at each perfect diagonal. I've pondered just coding in the diagonals just like the other directions but I've had little luck. Any pointers would be appreciated! Here's the current code:

Private Sub JoySticks()
    'Left Joystick drive motor controls.
    Dim LY As Integer
    Dim LX As Integer
    LY = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.Y * 100
    LX = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X * 100
    HScrollLX.Value = LX
    VScrollLY.Value = LY
    If LY > 0 Then
        MC1.Velocity(0) = LY
        MC1.Velocity(1) = LY
    ElseIf LY < 0 Then
        MC1.Velocity(0) = LY
        MC1.Velocity(1) = LY
    ElseIf LX > 0 Then
        MC1.Velocity(0) = LX
        MC1.Velocity(1) = LX * -1
    ElseIf LX < 0 Then
        MC1.Velocity(0) = LX
        MC1.Velocity(1) = LX * -1
    ElseIf LX Or LY = 0 Then
        MC1.Velocity(0) = 0
        MC1.Velocity(1) = 0
    End If
End Sub

Private Sub TimerJoysticks_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerJoysticks.Tick
    JoySticks()
End Sub


texts:
We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return true if it is possible to make the goal by choosing from the given bricks.

bool make_bricks(int small,int big,int goal)
{
    if(big > 0)
    {
        double test = (double)goal/((double)big*5.0);//The above if statement eliminates the possibility of division by zero
        if(test > 1.0)//This means we cannot make the row with big bricks alone
        {
            if(small >= (goal-big*5))//If we have enough small bricks after using all our big bricks
            {
                return true;
            }
            else//If we don't have enough small bricks to finish the row
            {
                return false;
            }
        }
        else if(test == 1)//If we have exactly enough big bricks to make the row
        {
            return true;
        }
        else//We have enough big bricks to make the row, but perhaps not enough small bricks
        {
            if(small >= (goal%5))//If we have enough small bricks after using as many big bricks as possible
            {
                return true;
            }
            else//We do not have enough small bricks after using as many big bricks as possible
            {
                return false;
            }
        }
  }
  else//If the big is not greater than 0, we depend solely on small bricks to make the row.
  {
      if(small >= goal)//If we have enough small bricks to make the row or more than enough
      {
          return true;
      }
      else//We do not have enough small bricks to make the row
      {
          return false;
      }
  }
}


texts: Python Pandas - finding duplicate names and telling them apart

texts:
(Somewhat) new to python and coding in general! Using python 3.7 and pandas, I'm running code to create a searchable list of people in my dataframe, and I feel like my way of telling duplicates apart is very roundabout. I would love some advice on making it simpler and more efficient.

I have a database in pandas, 'df2', which has three relevant rows: 'First Name', 'Last Name' and 'People ID'. Some people will have the same name, and these can be told apart by their 'People ID'. I start by making the 'Name' column as thus:

df2['Name'] = df2['First Name'] + ' ' + df2['Last Name']

Now I make a Dict, nameid, to find out how many different People IDs are associated to each unique 'Name' string.

nameid = {}
for i in df2.index:
    try:
        nameid[df2.loc[i, 'Name']].append(df2.loc[i, 'People ID'])
    except:
        nameid[df2.loc[i, 'Name']] = [df2.loc[i, 'People ID']]

There are multiple occurences of each person in the spreadsheet, so I want to just have each unique instance of a different 'People ID' using set().

for i in nameid.keys():
    nameid[i] = list(set(nameid[i]))

Now I create a second dict, namead, which is a "filtered" version of nameid where we've removed all reviewer names with just one ID value associated (those are fine as they are).

namead = {}

for i in nameid.keys():
    paceholder = ['Nothing']
    try:
        paceholder.append(nameid[i][1])
        namead[i] = nameid[i]
    except:
        pass

Finally, I use namead to make dupes, the list of index values of df2 where there are names belonging to different reviewers. I then pass that through df2 to add the 'People ID' to those names and ensure there is no confusion.

dupes = [i for i in df2.index if df2.loc[i, 'Name'] in namead.keys()]
for i in duperevs:
    df2.loc[i, 'Name'] += ' ' + str(df2.loc[i, 'People ID'])

Whew! I feel like I added several layers of complexity here but I'm not sure where to start - help would be much appreciated!

EDIT - I'm not sure how to put an extract of the dataframe in this textbox. Clarification: each row of data has information, and I need it to be searchable by name for the end user, with a placeholder to differentiate identical names (the People ID). The resulting data looks like: "Frank Jones / 14498", "Mitin Nutil / 35589", "Maveh Kadini 1433 / 1433" (indicating that there's more than one Maveh Kadini in the data). Each person (by People ID) will appear in many different rows of data.


texts: Reducing code with two identical objects

texts:
I have two identical objects on the page, so I get more of the same lines of code.  Can anything be made simpler, perhaps with merging?

for(var i=0;i<ticks.length,i<ticks2.length;i++) {

  var tick = ticks[i];
  var tick2 = ticks2[i];
  var tickCenter = tick.offsetWidth / 2
  var offset = (i - currentTick) * pixelsPerTick;
  var percent = 1-(Math.abs(i-currentTick)/10);

  tick2.style.top = ((offset + center - tickCenter)|0) + "px";
  tick2.style.opacity = percent;

  tick.style.top = ((offset + center - tickCenter)|0) + "px";
  tick.style.opacity = percent;
}


texts: Design for a protocol based software in C++

texts:
I want a good design to implement a master-slave protocol. The protocol is proprietary and similar to cctalk.
We have:

Master: HEADER [ DATA ] CHECKSUM
Slave: HEADER [ DATA ] CHECKSUM

My choice was to have concrete base classes for request and for response:

class PacketReq {
public:
    typedef std::vector<uint8_t>       container;
    typedef container::const_iterator  const_iterator;

    PacketCommand command() const
    {
        return static_cast< PacketCommand >( mBuffer[ 2 ] );
    };

    const container& data() const
    {
        return mBuffer;
    }

    const_iterator begin() const
    {
        return mBuffer.begin();
    }

    const_iterator end() const
    {
        return mBuffer.end();
    }

protected:
    container mBuffer;
};

class PacketOut1 : public PacketReq {
public:
    PacketOut1()
    {
        mBuffer.reserve( PacketHeaderHelper::HEADER_SIZE );
        mBuffer.push_back( /* something. */ );
        mBuffer.push_back( /* something. */ );
        mBuffer.push_back( /* something. */ );
        mBuffer.push_back( /* something. */ );
    }
};

The response can be a good response or a NACK (an error). My Implentation is:

class PacketRes {
public:
    PacketRes(const std::vector<uint8_t>& buffer)
    {
        if (!checkChecksum( buffer ))
        {
            throw Error("invalid checksum");
        }

        PacketHeaderHelper header( buffer );
        mCommand = header.command();

        if (header.len() > PacketHeaderHelper::HEADER_SIZE)
        {
            const size_t bodySize = header.len() - PacketHeaderHelper::HEADER_SIZE;

            mData.reserve( bodySize );

            mData.insert(
                mData.end(),
                buffer.begin() + PacketHeaderHelper::HEADER_SIZE - 1,
                buffer.end() - 1
                );
        }
    }

    virtual ~PacketReq() {}

    PacketCommand command() const
    {
        return mCommand;
    }

    const std::vector<uint8_t>& body() const
    {
        return mData;
    }

private:
    bool checkChecksum(const std::vector<uint8_t>& buffer) const
    {
        /* calc checksum. */
    }

private:
    std::vector<uint8_t> mData;
    PacketCommand mCommand;
};

class PacketInAck : public PacketReq {
public:
    PacketInAck(const std::vector<uint8_t>& buffer) : PacketReq( buffer )
    {
    }
};

So if I want make a request the sequence is:

lock_guard
send( const PacketOut& p )
std::unique_ptr< PacketRes > read();

But I don't like this design, but it works.

Is there some other way to implement this?


texts: MultiThreaded TCP Server with high CPU usage

texts:
I wrote simple C# TCP Server application and my program use a lot of cup, i was wondering anyone can review my code and would be grateful for any hints and suggestion.

This is my code.

public class Program
    {
        static void Main(string[] args)
        {
            int _Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TCPPort"]);
            string _IP = System.Configuration.ConfigurationManager.AppSettings["TCPIP"];
            TcpServer server = new TcpServer(_Port);
        }
    }

  public class TcpServer
    {
        private TcpListener _server;
        private Boolean _isRunning;
        private static int defaultMax = 8;
        public TcpServer(int port)
        {
            _server = new TcpListener(IPAddress.Any, port);
            _server.Start();
            _isRunning = true;
            LoopClients();
        }

public void LoopClients()
    {
        while (_isRunning)
        {

            TcpClient newClient = _server.AcceptTcpClient();
            SentFirstTimeData_New(newClient);
            Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
            t.Start(newClient);
        }
    }

    public void HandleClient(object obj)
    {

        int requestCount = 0;
        byte[] bytesFrom = new byte[209666];
        string dataFromClient = null;
        Byte[] sendBytes = null;
        requestCount = 0;
        int byteread = 0;
        string respdata = string.Empty;
        byte[] buffer = new byte[4096];
        int numberOfBytesRead;

        TcpClient client = (TcpClient)obj;
        NetworkStream networkStream = client.GetStream();
        IPAddress address = ((IPEndPoint)client.Client.RemoteEndPoint).Address;

        Boolean bClientConnected = true;
        int id = Thread.CurrentThread.ManagedThreadId;
        while (bClientConnected)
        {

            try {
                if (networkStream.DataAvailable)
                {
                    byteread = networkStream.Read(bytesFrom, 0, (int)client.ReceiveBufferSize);
                    dataFromClient = Encoding.ASCII.GetString(bytesFrom).TrimEnd('\0');
                    System.Text.Encoding.ASCII.GetString(bytesFrom);

                    XmlDocument doc = new XmlDocument();
                    string xml = Encoding.UTF8.GetString(bytesFrom).TrimEnd('\0');
                    doc.LoadXml(xml);
                    XElement incc = XElement.Load(new XmlNodeReader(doc));
                    respdata = AysncTCPIncomeString(incc);

                    sendBytes = Encoding.ASCII.GetBytes(respdata);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();

                }

            }
            catch (Exception ex)
            {
                Helper.WriteLog("Exception=" + ex.Message);
            }

        }
    }

    public void SentFirstTimeData_New(TcpClient tc)
    {
        try
        {
            int threadid = Thread.CurrentThread.ManagedThreadId;
            string Msg = HLStatusResponse.FirstTimeStatusSuccessfulResponse("STATUS", "1");
            NetworkStream _NetworkStream = tc.GetStream();
            if (_NetworkStream != null)
            {
                byte[] data = Encoding.ASCII.GetBytes(Msg);
                _NetworkStream.Write(data, 0, data.Length);

                Helper.WriteLog("ThreadId=" + threadid.ToString() + ";SentFirstTimeData :\t " + Msg);
            }

        }
        catch (Exception ex)
        {
            Helper.WriteLog("Sent Though Tcp Eror :" + ex.ToString());

        }
    }

}


texts:
So I'm writing a program to format names to title case and display them in alphabetic order.  Any advice please?  And how can i add more methods?

public static void main (String [] args)
{
    //local variables
    string name1;
    string name2;

     myLib = new Library();

     /********************   Start main method  *****************/

     //prompt user for first Name
     System.out.print("Enter First Name : ");
     name1 = Keyboard.readChar();

     //prompt user for second
     System.out.print("Enter Second Name : ");
     name2 = Keyboard.readChar();

     //Format names to Title Case
     name1.replace(0, name1.length(), name1.toString().toLowerCase());
     name2.replace(0, name2.length(), name2.toString().toLowerCase());

     name1.setCharAt(0, Character.toTitleCase(name1.charAt(0)));
     name2.setCharAt(0, Character.toTitleCase(name2.charAt(0)));

     //clear the screen
     myLib.clrscr();

     //Display names in alphabet order
     if (name1.toString().compareTo(name2.toString()) >= 0) {
         System.out.println(name2 + " " + name1);
     } else {
         System.out.println(name1 + " " + name2);
     }

     //pause the screen
     //myLib.pause();

  } //end main method

} //end


texts:
After the tips from my previous review. I have come up with these changes:

Changed my braces to start on a new line
Used the Single Responsibility Principle
Return early whenever possible
Use a namespace that doesn't start with an underscore

I'm not entirely sure I have used the namespace correctly. If it's wrong, can you please give me a push in the right direction? Any other comments would be appreciated.

namespace Difficult.StopWatch0002
{
    public partial class StopWatchForm : Form
    {
    StateEnum state;
    Stopwatch stopWatch;
    TimeSpan timeSpan;
    string elapsedTime;
    List<string> times = new List<string>();

    public StopWatchForm()
    {
        InitializeComponent();
        state = StateEnum.Stoped;
    }

    private void StartAndLapButton_Click(object sender, EventArgs e)
    {
        if (state == StateEnum.Stoped)
        {
            stopWatch = Stopwatch.StartNew();
            state = StateEnum.Started;
            ChangeButtonText(StartAndLapButton, "Lap");
            ChangeFormTitle("Started");
            timer1.Enabled = true;
        } else if (state == StateEnum.Started)
        {
            times.Add(elapsedTime);
        }
    }

    private void StopButton_Click(object sender, EventArgs e)
    {
        if (state == StateEnum.Started)
        {
            ChangeButtonText(StartAndLapButton, "Start");
            ChangeFormTitle("Stop Watch");
            stopWatch.Stop();
            times.Add(elapsedTime);
            state = StateEnum.Stoped;
            timer1.Enabled = false;
        }
    }

    private void FileButton_Click(object sender, EventArgs e)
    {
        if (!times.Any())
        {
            return;
        }
        var filename = PromtSaveAsFileName();
        if (filename == null)
        {
            return;
        }
        WriteResultsToFile(filename);
        times.Clear();
    }

    private void WriteResultsToFile(string filename)
    {
        System.IO.File.WriteAllLines(filename, times);
    }

    private string PromtSaveAsFileName()
    {
        var dialog = new SaveFileDialog
        {
            DefaultExt = "txt",
            Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*",
            FilterIndex = 2,
            RestoreDirectory = true
        };

        if (dialog.ShowDialog() == DialogResult.OK)
        {
            return dialog.FileName;
        }

        return null;
    }

    void ChangeButtonText(Button button, string text)
    {
        button.Text = text;
    }

    private void ChangeFormTitle(string text)
    {
        this.Text = text;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        timeSpan = stopWatch.Elapsed;
        elapsedTime = String.Format("{0:00}:{1:00}:{2:00}", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
        TimeKeeperText.Text = elapsedTime;
    }
}
}


texts:
I'm trying to find the local maxima in a 3D numpy array, but I can't seem to find an easy way to do that using numpy, scipy, or anything else.

For now I implemented it using scipy.signal.argrelexrema. But it's very long to process large arrays, and only works on separated axes.

import numpy as np
from scipy.signal import argrelextrema

def local_maxima_3D(data, order=1):
    """Detects local maxima in a 3D array

    Parameters
    ---------
    data : 3d ndarray
    order : int
        How many points on each side to use for the comparison

    Returns
    -------
    coordinates : ndarray
        coordinates of the local maxima
    values : ndarray
        values of the local maxima
    """
    # Coordinates of local maxima along each axis
    peaks0 = np.array(argrelextrema(data, np.greater, axis=0, order=order))
    peaks1 = np.array(argrelextrema(data, np.greater, axis=1, order=order))
    peaks2 = np.array(argrelextrema(data, np.greater, axis=2, order=order))

    # Stack all coordinates
    stacked = np.vstack((peaks0.transpose(), peaks1.transpose(),
                         peaks2.transpose()))

    # We keep coordinates that appear three times (once for each axis)
    elements, counts = np.unique(stacked, axis=0, return_counts=True)
    coords = elements[np.where(counts == 3)[0]]

    # Compute values at filtered coordinates
    values = data[coords[:, 0], coords[:, 1], coords[:, 2]]

    return coords, values

I know this solution is far from optimal and only works with order=1. Is there any better way to find local maxima in a 3D array in Python?


texts: Nested switch to return configuration for combination of 3 database types and 4 domains

texts:
I am currently doing a code review for a coworker.

I have encountered something like this:

switch (type)
{
    case DatabaseType.Type1:
        switch (domain)
        {
            case DOMAIN_1:
                return DatabaseConfigType.Type1Domain1;
            case DOMAIN_2:
                return DatabaseConfigType.Type1Domain2;
            case DOMAIN_3:
                return DatabaseConfigType.Type1Domain3;
            case DOMAIN_4:
                return DatabaseConfigType.Type1Domain4;
            default:
                Trace.Error("Undefined Type1 domain :" + domain);
                throw new ArgumentOutOfRangeException("domain", domain, null);
        }
    case DatabaseType.Type2:
        switch (domain)
        {
            case DOMAIN_1:
                return DatabaseConfigType.Type2Domain1;
            case DOMAIN_2:
                return DatabaseConfigType.Type2Domain2;
            case DOMAIN_3:
                return DatabaseConfigType.Type2Domain3;
            case DOMAIN_4:
                return DatabaseConfigType.Type2Domain4;
            default:
                Trace.Error("Undefined Type2 domain :" + domain);
                throw new ArgumentOutOfRangeException("domain", domain, null);
        }
    case DatabaseType.Type3:
        switch (domain)
        {
            case DOMAIN_1:
                return DatabaseConfigType.Type3Domain1;
            case DOMAIN_2:
                return DatabaseConfigType.Type3Domain2;
            case DOMAIN_3:
                return DatabaseConfigType.Type3Domain3;
            case DOMAIN_4:
                return DatabaseConfigType.Type3Domain4;
            default:
                Trace.Error("Undefined Type3 domain :" + domain);
                throw new ArgumentOutOfRangeException("domain", domain, null);
        }
    default:
        Trace.Error("Undefined type :" + type);
        throw new ArgumentOutOfRangeException("type", type, null);
}

Obviously, Types and Domains have actual wordy names, I just changed them for the question because they are irrelevant and probably sensitive information. On the other hand, the actual names for the DatabaseConfigType Enum are literally of the format TypeDomain, with the actual names of the type and domain instead of my numbered version.

I see this code, and it just feels wrong. There is some obvious redundancy by having three times (possibly more in the future) the exact same switch conditions inside each "outer" switch case, but since they return an Enum with different values, I just can't figure out a way to actually make this better.

The enum is in no particular order, and can't be expected to stay the same, so I can't do some math-ish unreadable but fast solution, not that I think it would be better anyway.

The code is probably as fast as it can be while still being readable, I'm mostly looking for a way to reduce the copy-paste aspect, therefore the lines of code, because I can't shake the feeling that there has to be a better way. If there isn't, feel free to tell me that.


texts:
As practice with the (ever so painful) C Strings I wrote a string reversal program. I am new to C, so I wanted to make sure that I am not using bad coding practices. It runs just fine (at least with expected input), but I am not sure if the logic is as good as it could be.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* strreverse(char* c)
{
    char input[500], output[500] = {}, buffer[2] = {' ', '\0'};
    strcpy(input, c);
    int i;
    for(i = strlen(input); i >= 0; i--)
    {
        buffer[0] = input[i];
        strcat(output, buffer);
    }
    return (char*) output;
}

int main(void)
{
    char* in = malloc(256);
    printf("Enter a string: ");
    scanf("%s", in);
    char* out = strreverse(in);
    printf("%s", out);
    return 0;
}


texts:
The following works as intended, however is there a more concise way to write this script without changing it too much? It's a simple menu with sub-levels which have a plus/minus icon when each li opens/closes.

jQuery:

$(document).ready(function() {
    $li = $('#main > li.expand');
    $li.click(function(){
        $ul = $(this).find('ul.sub-level').delay(200).slideDown(400);
        $(this).removeClass('expand').addClass('minus');
        $('#main > li > ul').not($ul).slideUp('slow');
        $('#main > li.minus').not($(this)).removeClass('minus').addClass('expand');

    })

    $li2 = $('.sub-level > li.expand');
    $li2.click(function(){
        $(this).find('ul.sub-level2').delay(200).slideToggle(400);
        $li2.toggleClass('minus').toggleClass('expand');
    })
});

HTML:

test-1

sub-test-1

sfasfasf

sfafasf

test-2

test-3

sub-test-2

test-4


texts:
I'm working on a PHP extension in an attempt to learn some C. I've implemented a variation of the internal PHP hashtable, which uses a lookup table and a separate bucket table. The lookup table simply points to the head of the collision chain (an index in the bucket table), and the next index in the chain is embedded in each bucket. Buckets are inserted into the table in insertion order.

#define INVALID_INDEX ((uint32_t) -1)

typedef struct _HBucket {

    zval          key;
    zval          value;  // Collision chain index in here
    zend_ulong    hash;

} HBucket;

typedef struct _HTable {

    HBucket   *buckets;
    uint32_t  *lookup;
    uint32_t   next;      // Index at which the next bucket will be created
    uint32_t   size;      // Number of actual items in the table
    uint32_t   capacity;  // Power of two size buffer

} HTable;

HBucket *htable_lookup_or_create(HTable *table, zval *key)
{
    HBucket *bucket;
    HBucket *buckets = table->buckets;

    const zend_ulong hash = get_hash(key);

    uint32_t l_index = hash & (table->capacity - 1);  // Lookup index
    uint32_t b_index = table->lookup[l_index];        // Bucket index

    if (b_index == INVALID_INDEX) {

        // Lookup should point to the head of the collision chain,
        // which is where the new entry will be.
        table->lookup[l_index] = table->next;

    } else {

        // Traverse the collision chain...
        for (;;) {

            bucket = &buckets[b_index];

            // If the bucket's key is a match, we've found the bucket.
            if (bucket->hash == hash && is_identical(&bucket->key, key)) {
                return bucket;

            } else {

                // Index of the next bucket in the chain
                uint32_t next = Z_NEXT(bucket->value);

                // Check to see if we're at the end of the chain,
                // and set that bucket's next as the new entry.
                if (next == INVALID_INDEX) {
                    Z_NEXT(bucket->value) = table->next;
                    break;
                }

                b_index = next;
            }
        }
    }

    // Initialize the new bucket
    bucket = &buckets[table->next];

    bucket->hash = hash;
    ZVAL_COPY(&bucket->key, key);
    ZVAL_NULL(&bucket->value);

    // New bucket doesn't have a next
    Z_NEXT(bucket->value) = INVALID_INDEX;

    table->size++;
    table->next++;

    if (table->next == table->capacity) {
        htable_increase_capacity(table);
        return &table->buckets[table->size - 1];  // Address may have changed.
    }

    return bucket;
}

I realise that there are multiple zend macros, but their effects are negligible for the sake of this question. I'd be happy to expand them all if required.

I'm developing on OS X, and I've been profiling adding millions of values to determine where things might be slowing down, and it comes down to this function almost entirely.

Is there anything obvious that I could do or try to improve the performance?


texts: Upload csv file to sqlserver with python

texts:
I have to weekly upload a csv file to sqlserver, and I do the job using python 3.
The problem is that it takes too long for the file to be uploaded (around 30 minutes), and the table has 49000 rows and 80 columns.

Here is a piece of the code, where I have to transform the date format and replace quotes as well. I have already tried it with pandas, but took longer than that.

import csv
import os
import pyodbc
import time
srv='server_name'
db='database'
tb='table'
conn=pyodbc.connect('Trusted_Connection=yes',DRIVER='{SQL Server}',SERVER=srv,DATABASE=db)
c=conn.cursor()

csvfile='file.csv'

with open(csvfile,'r') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
    cnt=0
    for row in reader:
        if cnt>0:
            for r in range(0,len(row)):
                #this is the part where I transform the date format from dd/mm/yyyy to yyyy-mm-dd
                if (len(row[r])==10 or len(row[r])==19) and row[r][2]=='/' and row[r][5]=='/':
                    row[r]=row[r][6:10]+'-'+row[r][3:5]+'-'+row[r][0:2]

                #here I replace the quote to nothing, since it is not important for the report
                if row[r].find("'")>0:
                    row[r]=row[r].replace("'","")

        #at this part I query the index to increment by 1 on the table
        qcnt="select count(1) from "+tb
        resq=c.execute(qcnt)
        rq=c.fetchone()
        rq=str(rq[0])

        #here I insert each row into the table that already exists
        insrt=("insert into "+tb+" values("+rq+",'"+("', '".join(row))+"')")
        if cnt>0:
            res=c.execute(insrt)
            conn.commit()
        cnt+=1
conn.close()

Any help will be appreciated. Thanks!


texts: Basic templating engine in F# using F# syntax

texts:
I've been working on a rough idea for a templating engine (mostly as a learning project) using the F# syntax. How "correct" is my code in terms of being idiomatic F#? Are there F# features which would make the code simpler? More easily understood?

The template files are loaded at runtime using a script I've not posted here The code is also provided as a gist for easier reading.

Template

#r "program.exe"
open System
open Lib

let intToText i = div [] [Text((sprintf "I is %i" i))]

Template (
    html [] [
        div [("id", "123");("class", "me")] [
            div [] [
                Text "SOME TEXT"
            ]
            div [] [
                Text "SOME MORE TEXT"
            ]
            foreach [1;2;3] intToText
            input [("type", "text"); ("value", "1")]
        ]
    ]
)

Lib

module Lib
open System
open System.Text

type Attributes = (string * string) list

type Element =
    | Tag of (string * Attributes * Element list)
    | TagSelfClosing of (string * Attributes)
    | Collection of (Element list)
    | Text of string

let html (attrs:Attributes) el:Element = Tag("html", attrs, el)
let div (attrs:Attributes) el:Element = Tag("div", attrs, el)
let input (attrs:Attributes) = TagSelfClosing("input", attrs)
let foreach data fn =
    let elems = data |> List.map fn
    Collection(elems)

type Token =
    | OPEN_TAG of (string * Attributes)
    | CLOSE_TAG of string
    | SELF_CLOSING_TAG of (string * Attributes)
    | TEXT of string

let Template el =
    let rec expandTree el output =
        match el with
        | Tag(tagName, attrs, children) ->
            let childContent =
                children
                |> List.fold (fun state item -> state @ (expandTree item [])) []

            let addition = [OPEN_TAG(tagName, attrs)]@childContent@[CLOSE_TAG(tagName)]
            output@addition
        | TagSelfClosing(tagName, attrs) ->
            let addition = [SELF_CLOSING_TAG(tagName, attrs)]
            output@addition
        | Collection(elements) ->
            let collectionContent =
                elements
                |> List.map (fun e -> expandTree e output)
                |> List.fold (fun state item -> state@item) []
            output @ collectionContent
        | Text(string) ->
            output@[TEXT(string)]

    let tokenWriter token =
        let attributeWriter (tuple:string*string) =
            let (name, value) = tuple
            sprintf " %s=\"%s\"" name value

        let foldAttributes attrs =
            attrs
            |> List.map attributeWriter
            |> List.fold (fun state item -> state+item) ""

        match token with
        | OPEN_TAG(name, attrs) ->
            let attributes = foldAttributes attrs
            sprintf "<%s%s>" name attributes
        | CLOSE_TAG(name) -> sprintf "</%s>" name
        | SELF_CLOSING_TAG(name, attrs) ->
            let attributes = foldAttributes attrs
            sprintf "<%s%s />" name attributes
        | TEXT(content) -> sprintf "%s" content

    let expandedTree = expandTree el []
    let content =
        expandedTree
        |> List.map tokenWriter
        |> List.fold (fun state item -> state+item) ""

    printf "%s" content


texts:
Below is a Singleton that I designed as a piece of sample code for a website I'm working on for fun. The goal is to use the Singleton to hold an Earth object since Earth is unique and there is only 1 of them. Please let me know your thoughts on the implementation.

Singleton.java

package design.patterns;

 /**
  * This class is a Singleton, we can only have 1 instance of it no matter what!
  *
  * We mark the class final so that no other classes try to extend it. Some
  * designs would want the Singleton to be extendable but we do not!
  */
public final class Earth {

    // A static instance of an Earth object
    private static Earth earth;

    // Some earthly variables
    private long ageInYears = 4500000000L;
    private float daysForFullOrbit = 365.26f;
    private float degreesOfAxisTilt = 23.4f;
    private long population = 7046000000L;

    // Prevent client from instantiating new Earth objects
    private Earth() {
    }

    /**
     * Global access point (no pun intended :)
     *
     * Synchronized so its thread safe.
     */
    public static synchronized Earth getInstance() {

        // "Lazy load" an Earth Object
        if (earth == null) {
            earth = new Earth();
        }

        return earth;
    }

    // Basic getters and setters
    public double getAgeInYears() {
        return ageInYears;
    }

    public void setAgeInYears(long ageInYears) {
        this.ageInYears = ageInYears;
    }

    public float getdaysForFullOrbit() {
        return daysForFullOrbit;
    }

    public void setdaysForFullOrbit(float daysForFullRotation) {
        this.daysForFullOrbit = daysForFullRotation;
    }

    public float getDegreesOfAxisTilt() {
        return degreesOfAxisTilt;
    }

    public void setDegreesOfAxisTilt(float degreesOfAxisTilt) {
        this.degreesOfAxisTilt = degreesOfAxisTilt;
    }

    public double getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public static void setEarth(Earth earth) {
        Earth.earth = earth;
    }
}

Client.java

package design.patterns;

public class Client {

    public static void main(String args[]){

        Earth earth = Earth.getInstance();

        //Invoke Earth's methods from the instance created on line 7
        System.out.printf("Earth is over %1$,.0f Days old. \n", earth.getAgeInYears());

        //Invoke Earth's methods from the Singleton directly
        System.out.println("Earth's orbit takes " + Earth.getInstance().getdaysForFullOrbit() + " days to complete.");

        //Invoke Earth's methods both ways
        System.out.println("Earth sits on a " + earth.getDegreesOfAxisTilt() + " degree tilt.");
        System.out.printf("As of 1/20/2014, there are %1$,.0f people on Earth!", + Earth.getInstance().getPopulation());
    }
}


texts:
I'm currently trying to create a travel blog using Django whereby users will be able to create a travel plan with the following features:

Each user can create a travel event based on the start date and end date for specific locations, with some meaningful description
He/She can also upload images for associated with specific travel event
A travel plan can consists of multiple travel events of various date

Will the following model be an efficient design?

    from django.db import models
    import datetime

    from __future__ import unicode_literals
    from django.core.urlresolvers import reverse
    from django.core.exceptions import ValidationError
    from django.utils import timezone
    from django.utils.translation import ugettext_lazy as _
    from django.conf import settings
    from django.utils.encoding import python_2_unicode_compatible

    # Create your models here.

    auth_user_model = getattr(settings, "AUTH_USER_MODEL", "auth.User")

    class Entry(models.Model):
        title = models.CharField(max_length=100)
        start_date = models.DateTimeField(_("start date"))
        end_date = models.DateTimeField(_("end date"))
        description = models.TextField(_("description"))
        accomodation = models.TextField(_("accomodation"))
        location = models.TextField(_("location"))
        images = models.ManyToManyField("Image", verbose_name=_("images"), blank=True, null=True)
        post_entry = models.ForeignKey(Post_Entry)

    class Post_Entry(models.Model):
        author = models.ForeignKey(User)
        created_by = models.ForeignKey(auth_user_model, verbose_name=_("created by"))
        categories = models.ManyToManyField("Category", verbose_name=_("categories"), blank=True)
        created_on = models.DateTimeField(auto_now_add = True)
        remarks = models.TextField(_("Remarks"))

    @python_2_unicode_compatible
    class Image(models.Model):
        title = models.CharField(max_length=60, blank=True, null=True)
        image = models.FileField(upload_to="images/")
        width = models.IntegerField(blank=True, null=True)
        height = models.IntegerField(blank=True, null=True)

        def __str__(self):
            return self.image.name

    @python_2_unicode_compatible
    class Category(models.Model):
        title = models.CharField(_('title'), max_length=255)

        def __str__(self):
            return self.title

        class Meta:
            verbose_name_plural = 'Categories'


texts: Should I put a JavaScript function in a local or global scope?

texts:
I have many pages with functions that appear only once, which I am sure is really typical.  I read that it's the best idea to use the local scope for functions when possible because the local scope is searched first, thereby making the function found sooner.

If I have no intention of reusing a function, is this the best way to create and use this function?

var doCancel = function doCancel() {
    // DO SOME CANCELLING TYPE STUFF
}

Or is this a better way?

function doCancel() {
    // DO SOME CANCELLING TYPE STUFF
}


texts:
Let's say I have three files: a page that is used for searching data called search, a file that handles requests called controller, and a file that has functions which the controller calls based on what POST parameter is passed. From the search page, I post some data and specify my action (search) via AJAX to the controller. The controller then takes that and calls a function that returns the data (which is inserted into the appropriate place in the DOM) which looks something like this:

<?php
function fetchStudentData($search, $roster) {

    //If a user is not logged in or the query is empty, don't do anything
    if(!isLoggedIn() || empty($search)) {
        return;
    }
    global $db;

    //Placement roster search
    if($roster == "placement") {
        $query = $db->prepare("SELECT t1.id,
                t2.placement_date,
                t2.placement_room,
                t1.student_id,
                t1.student_type,
                t1.last_name,
                t1.first_name,
                t1.satr,
                t1.ptma,
                t1.ptwr,
                t1.ptre,
                t1.ptlg,
                t1.waiver,
                t2.tests_needed,
                t2.blackboard_id
                FROM student_data AS t1
                JOIN additional_data AS t2
                ON t1.id = t2.student_data_id
                WHERE t2.placement_date = :search
                ORDER BY t1.last_name ASC");
        $query->bindParam(":search", $search);
        $query->execute();

        if($query->rowCount() == 0) {
            return;
        }

        echo "

Placement Roster For $search

            Placement Room
            Student ID
            Student Type
            Last Name
            First Name
            SATR
            PTMA
            PTWR
            PTRE
            PTLG
            Waiver
            Tests Needed
            Blackboard ID

";
        while($row = $query->fetch()) {
            echo "

                {$row['placement_room']}
                {$row['student_id']}
                {$row['student_type']}
                {$row['last_name']}
                {$row['first_name']}
                {$row['satr']}
                {$row['ptma']}
                {$row['ptwr']}
                {$row['ptre']}
                {$row['ptlg']}
                {$row['waiver']}
                {$row['tests_needed']}
                {$row['blackboard_id']}

";
        }
    }
}
?>

This is obviously working very well for me but I wanted to know if there's a better way I should be doing this? Should I be returning the raw data from the database and encoded as JSON and then have my JavaScript take care of creating elements/structure? I see that a lot with various API's but this is something internal to my company and not something that other developers will be using. Is there anything wrong with my approach?


texts:
This is my player rotation script. I just want to make sure my naming conventions are right. If there is any way to make this code more readable I'm open to suggestions. This is also my 3rd post about along the same line so please be brutal.

public class ShipRotation : MonoBehaviour
{
    [SerializeField] Canvas canvas;
    ShipManager shipControls;
    GameObject ship;
    DebugController debugController;
    Camera shortHandCamera;
    [SerializeField] GameObject mainCamera;
    float distFromCamera;

    void Start()
    {
        shortHandCamera = Camera.main;
        shipControls = GetComponent<ShipManager>();
        debugController = canvas.GetComponent<DebugController>();
        ship = GameObject.Find("Player");
        distFromCamera = Mathf.Abs(mainCamera.transform.position.z);
        target = new Vector3(0f, 2f, ship.transform.position.z);
    }

    enum StateOfRotation
    {
        waiting,
        rotating
    }

    public LayerMask touchInputMask;
    Vector3 target;
    void Update()
    {
        foreach (Touch touch in Input.touches)
        {
            Ray ray = Camera.main.ScreenPointToRay(touch.position);
            RaycastHit hit;
            if (!Physics.Raycast(ray, out hit, touchInputMask)) { continue; }

            GameObject recipient = hit.transform.gameObject;
            if (recipient.tag != "Player")
            {
                target = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, ship.transform.position.z + distFromCamera));
            }
        }
        ship.transform.LookAt(target);
        debugController.ChangeText(6, target.ToString());
    }
}


texts: Counting occurrences of Char8s in a file

texts:
To learn some Data.Map and Control.Monad.State, I have written the following code, which should count the occurrences of Char8 in a given file.

module Main where

import           Control.Monad.State
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.Map              (Map)
import qualified Data.Map              as M
import           Data.Maybe
import           System.Environment

type Counter = ([Char], (Char, Integer), (Char, Integer), Map Char Integer)

main :: IO ()
main = do
  file <- liftM head getArgs
  string <- B.readFile file
  let (chars, seldom, often, counter) = execState (countChars string) ([], (' ', 10^12), (' ', 0), M.empty)
  mapM_ (\k -> putStrLn ('\'':k:"' " ++ show (fromJust $ M.lookup k counter))) chars
  putStrLn $ "minimum occurence: " ++ show (fst seldom) ++ ", " ++ show (snd seldom)
  putStrLn $ "maximum occurence: " ++ show (fst often)  ++ ", " ++ show (snd often)
  putStrLn $ "overal chars     : " ++ show (B.length string)

countChars :: B.ByteString -> State Counter ()
countChars bs | B.null bs = return ()
              | otherwise = do
  let c  = B.head bs
  let cs = B.tail bs
  unless (not . isPrint $ c) $ do
    (pre, minOcc, maxOcc, counter) <- get
    newPre <- return $ if (c `elem` pre)
                         then pre
                         else pre ++ [c]
    newCounter <- return (M.insertWith (+) c 1 counter)
    let newMinOcc = (\ (k1, v1) (k2, v2) -> if v2 < v1 then (k2, v2) else (k1, v1)) minOcc (c, newCounter M.! c)
    let newMaxOcc = (\ (k1, v1) (k2, v2) -> if v2 > v1 then (k2, v2) else (k1, v1)) maxOcc (c, newCounter M.! c)
    put (newPre, newMinOcc, newMaxOcc, newCounter)
  countChars cs

This code works as I want it for small files, counting and displaying the stats of the file, but it fails when the file gets bigger:

$ ls -l 46000.txt.utf-8
-rw-r--r-- 1 nobbz nobbz 156315 Jun 16 20:33 46000.txt.utf-8

$ ./Main 46000.txt.utf-8
Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize -RTS' to increase it.

I don't grasp why a file of about 150kiB can overflow an 8Mib stack. If I increase to 10 MiB (./Main 46000.txt.utf-8 +RTS -k10M) it works, but using also -sstderr shows that the Program consumes 107 MiB in total.

How could I decrease memory usage, so it would work with large files and default stack-size?

Edit

Just to mention:

I want to keep the list of chars and their count of occurrence in the order of occurrence of the corresponding char, also I want that on equal count for most often and most seldom used chars that one "wins" that has occurred first.

Also I am aware of the fact that I have a file that states to be UTF-8 encoded and my program can only "see" ASCII, but I just took a random book from gutenberg.org to have a real text and not some "random" bytes in huge binarys or something comparable.


texts: Trigger breakpoint when string is not a Google-owned domain

texts:
Basically, I want the code to break when strLink doesn't contain any domains in the googleDomains link.

The code seems to be very awkward. I wonder if there is a way to make this more elegant.

Dim googleDomains = {"google.com", "blogger.com", "youtube.com"}
Dim pass = False
For Each domaingoogle In googleDomains
    If strLink.Contains(domaingoogle) Then
        pass = True
    End If
Next
If Not pass Then
    Dim hello2 = 1 'set breakpoint here.
End If


texts:
i have 3 method which do almost the same thing,they different models to achieve the same      goal.I did small refactoring but its still not looks like
   ruby,can we improve it?
   Thanks in advance.

after:

def get_list(id,list_name,attribute_id,attribute,locale_string)
  map={ "resentact" => ResenAct }, "stageact" => StageAct , "payact" => PayAct" }
  @temp=""
  @list=map[list_name.downcase].find(:all, :conditions => {'id' => "#      {id}".chop_space})
   @list.each do |item|
      @temp = @temp + get_data(item.attribute_id,item) + " " + item.attribute + " " +   locale_string+ ", "
   end
   return  @temp.pop(2) if @temp.length > 1
  end

method call : get_list(id,payact,payact_id,date,"some_string")

before:

 def get_resentact_list(id)
 @temp=""
  @resentacts=ResentAct.find(:all, :conditions => {'product_id' => "#{id}".chop_space})
   @resentacts.each do |item|
      @temp = @temp + get_data(item.shop_id,"resentact") + " " + item.cost.to_s + " " + "string1" + ", "
   end
   @temp = @temp[0,@temp.length-2] if @temp.length > 1
   return @temp

end

 def get_stageact_list(id)
  @temp=""

    @stageacts=StageAct.find(:all, :conditions => {'product_id' => "#{id}".chop_space})
    @stageacts.each do |item|
       @temp = @temp + "string1" + ": " + get_data(item.type_id,"type") + ", " + "str2" + ": " + item.summ + " " + "str3" + ", "
    end
    @temp = @temp[0,@temp.length-2] if @temp.length > 1
    return @temp
 end

def get_payact_list(id)
  @temp=""

   @payacts=PayAct.find(:all, :conditions => {'product_id' => "#{id}".chop_space})
      @payacts.each do |item|
         @temp = @temp + "str1" + ": " + item.date + ", " + "str2" + ": " + item.summ + " " + "str3" + ", "
      end
      @temp = @temp[0,@temp.length-2] if @temp.length > 1
      return @temp
  end


texts: Compare multiple values of an array in the same time in Javascript

texts:
As of now the below code working As expected. But in future if the newFilterArr have new record again I want to reedit this functionality. So how to overcome this?

function Optimiz() {
    let courseFilter = this.newFilterArr.find(k => k.key === 'courseId'),
        rateTypeFilter = this.newFilterArr.find(k => k.key === 'rateTypeId');

    this.rateSetupDataUI = this.originalRateSetupDataUI.filter(x => {
        if (courseFilter && rateTypeFilter) {
            return x['courseId'] === courseFilter.filtered.id && x['rateTypeId'] === rateTypeFilter.filtered.id;
        } else if (courseFilter && !rateTypeFilter) {
            return x['courseId'] === courseFilter.filtered.id
        } else if (!courseFilter && rateTypeFilter) {
            return x['rateTypeId'] === rateTypeFilter.filtered.id;
        }
    });
}


texts:
I have a handful of objects that don't have references to each-other that all need to receive an update.

From what I've read, it seems like a Publish-Subscribe Messaging Channel is an appropriate pattern. Searching for an existing solution mainly turned up messaging libraries for application integration (between processes). Those solutions were much more than what I needed, so I wrote this simple Publisher.

Questions:

Is there already something simple like this in the .NET framework that I overlooked? Or another light-weight library?
Is this an appropriate implementation and application of the Pub/Sub pattern? What might be done to improve it?
What gotchas are there? For example, I presume I need to Unsubscribe in the subscriber's finalizer.

public interface ISubscriber
{
    void SubscriptionUpdate(object message);
}

public interface IPublisher
{
    void Subscribe(ISubscriber subscriber, string channel);
    void Unsubscribe(ISubscriber subscriber, string channel);
    void Publish(string channel, object message);
}

public class Publisher : IPublisher
{
    static Publisher _instance = new Publisher();
    public static Publisher Instance { get { return _instance; } }
    Dictionary<string, List<ISubscriber>> _subscribers = new Dictionary<string, List<ISubscriber>>();

    public void Subscribe(ISubscriber subscriber, string channel)
    {
        if (!Exists(channel))
            _subscribers[channel] = new List<ISubscriber>();
        if (!_subscribers[channel].Contains(subscriber))
            _subscribers[channel].Add(subscriber);
    }

    public void Unsubscribe(ISubscriber subscriber, string channel)
    {
        if (Exists(channel))
            _subscribers[channel].Remove(subscriber);
    }

    public void Publish(string channel, object message)
    {
        if (!Exists(channel)) return;
        foreach (var subscriber in _subscribers[channel])
            subscriber.SubscriptionUpdate(message);
    }

    bool Exists(string channel)
    {
        return _subscribers.ContainsKey(channel);
    }
}


texts:
Currently I'm using these three functions, that in the end produces a JSON array. I went this way so that I could fetch data from a specific table. But now it just seems bloated and poorly written, mixed with stdClass and arrays.

public static function getFraga($quiz_id = false)
{
    $database = DatabaseFactory::getFactory()->getConnection();
    $sql = "SELECT * FROM questions";
    $arg = false;
    if($quiz_id) {
        $sql .= " WHERE quiz_id = :quiz_id";
        $arg  = array(':quiz_id' => $quiz_id);
    }
    $query = $database->prepare($sql);
    if($arg) {
        $query->execute($arg);
    } else {
        $query->execute();
    }
    $data = $query->fetchAll();
    $data = json_decode(json_encode($data), true);
    $out = array();
    foreach($data as $key => $row) {
        $out[$row['id']] = $row;
    }
    return $out;
}

public static function getAnswers()
{
    $database = DatabaseFactory::getFactory()->getConnection();
    $sql = "SELECT * FROM choices";
    $query = $database->prepare($sql);
    $query->execute();
    $data = $query->fetchAll();
    $data = json_decode(json_encode($data), true);
    $out = array();
    foreach($data as $key => $row) {
        $out[$row['id']] = $row;
    }
    return $out;
}

public static function qAndA($quiz_id = false)
{
    $questions = Self::getFraga($quiz_id);
    $answers = Self::getAnswers();
    $combined  = array();
    foreach($answers as $answer) {
        if(!isset($questions[$answer['question_id']])) continue;
        $q_key = 'question-'.$answer['question_id'];
        if(!isset($combined[$q_key])) {
            $combined[$q_key] = $questions[$answer['question_id']];
        }
        $combined[$q_key]['answer'][$answer['id']] = $answer;
    }
    return $combined;
}

And I call the qAndA() to get this result, with json_encode():

{
  "question": {
    "question-5": {
      "id": "5",
      "content": "Har jag laddad upp en bild?",
      "source": "99",
      "image_url": "156ebc02fd6281_kljqpiohfngme.jpeg",
      "lastmodified": "2016-03-18 09:45:35",
      "quiz_id": "1",
      "answer": {
        "17": {
          "id": "17",
          "content": "Nej",
          "correct": "1",
          "question_id": "5"
        },
        "18": {
          "id": "18",
          "content": "ja",
          "correct": "0",
          "question_id": "5"
        },
        "19": {
          "id": "19",
          "content": "kanske",
          "correct": "0",
          "question_id": "5"
        },
        "20": {
          "id": "20",
          "content": "vet inte",
          "correct": "0",
          "question_id": "5"
        }
      }
    }
  }
}

Narrow it down to one function? Other improvements?


texts:
I am a beginner in C. I have just written this program to find the factors of a provided number \$n\$ where \$1\leq n \leq 10^9\$. However, when I input large numbers (e.g. the maximum, \$10^9\$), the program takes a long time to finish finding the larger factors. How do I reduce its time taken? Also, are there any possible improvements for this code?

#include<stdio.h>
int main(){
    int a,i;
    scanf("%d",&a);
    for(i=1;i<(a/2+1);i++){
        if(a%i==0){
            printf("%d\n",i);
        }
    }
    printf("%d\n",a);
    return 0;
}


texts: Storing realm objects using Kotlin extensions

texts:
I am a Java Android Developer and I'm approaching Kotlin.

I have defined the following class:

open class Player : RealmObject() {
    ...
}

And I defined the following two extensions, one for the generic RealmObject class and one for the specific Player class:

fun RealmObject.store() {
    Realm.getDefaultInstance().use { realm ->
        realm.beginTransaction()
        realm.copyToRealmOrUpdate(this)
        realm.commitTransaction()
    }
}

fun Player.store(){
    this.loggedAt = Date()
    (this as RealmObject).store()
}

What I want is if I call .store() on any RealmObject object, the RelamObject.store() extension will be called BUT if i call .store() on a Player instance the extension that will be called will be Player.store().
(No problem for now)
I don't want to copy paste the same code, i love to write less reuse more.
So i need that internally the Player.store() will call the generic RealmObject.store()

I got it. The code I wrote up there is actually working as expected :D

Is this the good way? Or there is some better way?


texts: Returning items which are different from their preceding items from a list

texts:
I have a list of tuples (key, value1, value2, ...). I simplify the tuple here so it is only of length 2. Keys contain duplicated figures.

xs = zip([1,2,2,3,3,3,4,1,1,2,2], range(11)) # simple to input

[(1, 0),
 (2, 1),
 (2, 2),
 (3, 3),
 (3, 4),
 (3, 5),
 (4, 6),
 (1, 7),
 (1, 8),
 (2, 9),
 (2, 10)]

Now, I would like to build a function, which takes the list as input, and return a list or generator, which is a subset of the original list.

It must captures all items where the keys are changed, and include the first and last items of the list if they are not already there.

f1(xs) = [(1, 0), (2, 1), (3, 3), (4, 6), (1, 7), (2, 9), (2, 10)]
f1([]) = []

The following is my code, it works, but I don't really like it:

xs = zip([1,2,2,3,3,3,4,1,1,2,2], range(11))

def f1(xs):
    if not xs:
        return
    last_a = None # I wish I don't have to use None here.
    is_yield = False
    for a, b in xs:
        if a != last_a:
            last_a = a
            is_yield = True
            yield (a, b)
        else:
            is_yield = False
    if not is_yield:
        yield (a, b) # Ugly...in C# a, b is not defined here.

print list(f1(xs))
print list(f1([]))

What's a better (functional or nonfunctional) way of doing this?