texts: Modern CMake/c++ and vcpkg project setup for large projects

texts:
I am starting up a project with some people, because there will be developed for and on multiple platforms  we chose to use CMake to build our project. Because the project will get quite large we are trying to have a good setup but we lack the experience needed in CMake to make well thought out decisions.
We are using vcpkg for installing and using package as described as best practice to use it as submodule in combination with cmake.
We are mostly looking for the following answers.

Does the directory structure hold up when the project gets larger.
Should all header files be in the includes directory or only the public ones.
Does this project use the proper modern CMake conventions.
Is vcpkg a the right choice for these kind of projects(multi-platform)
for now we have 2 libraries(Cheetah.Engine and Cheetah.Editor) we suspect it will be a lot more, could it be smart to seperate these libraries to their own projects?

Our directory structure:

Root CMakeLists.txt:
# CMakeList.txt : Top-level CMake project file, do global configuration
# and include sub-projects here.
#
cmake_minimum_required (VERSION 3.18)

project ("Cheetah")

# Platform defines for all projects
IF (WIN32)
  add_compile_definitions(CH_PLATFORM_WINDOWS)
ELSE()
  # set stuff for other systems
ENDIF()

# Set ouput projects so no need to copy dll's after build
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

# Include sub-projects.
add_subdirectory ("Cheetah.Engine")
add_subdirectory ("Cheetah.Editor")
add_subdirectory ("Sandbox")

Subdirectory CMakeLists.txt of Cheetah.Engine:
cmake_minimum_required (VERSION 3.18)

add_library (Cheetah.Engine SHARED "")

# add sources
add_subdirectory("src")
add_subdirectory("includes")

# add includes
target_include_directories(Cheetah.Engine PRIVATE "${CMAKE_CURRENT_LIST_DIR}/includes")

# add macros
target_compile_definitions(Cheetah.Engine PRIVATE "CH_BUILD_DLL")

# add libraries
find_package(glad CONFIG REQUIRED)
target_link_libraries(Cheetah.Engine PRIVATE glad::glad)

find_package(glfw3 CONFIG REQUIRED)
target_link_libraries(Cheetah.Engine PRIVATE glfw3)

Example of includes folder CMakeLists.txt:
cmake_minimum_required (VERSION 3.18)

target_sources(Cheetah.Engine
    INTERFACE
        "Application.h"
        "EntryPoint.h"
     PRIVATE
        "Core.h"
     )

We are still debating if the core.h should be with the source files outside of the includes folder because it is a private header file.
Example of source folder CMakeLists.txt:
cmake_minimum_required (VERSION 3.18)

target_sources(Cheetah.Engine PRIVATE "Application.cpp")


texts:
I know that multiple functions are already available. However, I thought of writing my own because I wanted to learn the logic (and also because I thought there wasn't enough confusion :P). Please review the function I wrote and suggest me efficient changes.

Without further ado, here I go:

scan(string,size)
char** string;
size_t size;
{
    string[0]=(char*)malloc(sizeof(char));
    char keystroke=' ';
    while((keystroke=getc(stdin))!='\n') {
        string[0][size++]=keystroke;
        string[0]=(char*)realloc(string[0],size+1);
    }
    string[0][size]='\0';
    return size;
}


texts: C Garbage Heap aka simplest memory management tool

texts:
The idea is to init garbage heap in the beginning of main, use gmalloc, gcalloc and grealloc wrappers and free all allocated memory in the end of main. It helps to avoid memory leaks when writing programs for ejudge systems. Would like to hear general feedback on the idea and advices on how to improve the code (beginner in C).

main.c

/*
Example of usage of garbage heap.
No free() call but no memory leak.
*/

#include "garbage_heap.h"

int main() {
    init_garbage_heap();
    for (int i = 0; i < 1000; ++i)
    {
        char* str = gmalloc(1000*sizeof(char));
        str = grealloc(str, 2000*sizeof(char));
    }
    free_garbage_heap();
    return 0;
}

garbage_heap.h

#ifndef GARBAGE_HEAP_H
#define GARBAGE_HEAP_H

#include <stddef.h>

void init_garbage_heap (void);
void free_garbage_heap (void);
void* gmalloc (size_t sizemem);
void* gcalloc (size_t number, size_t size);
void* grealloc (void* ptrmem, size_t sizemem);

#endif // GARBAGE_HEAP_H

garbage_heap.c

#include <stdlib.h>

#include "garbage_heap.h"

typedef struct
{
    void** buffer;
    int len;
    int capacity;
}
GarbageHeap;

static GarbageHeap garbage_heap;

void init_garbage_heap(void)
{
    int len = 32;
    garbage_heap.len = 0;
    garbage_heap.capacity = len;
    garbage_heap.buffer = (void**)malloc(sizeof(void*)*len);
    for (int i = 0; i < len; ++i)
        garbage_heap.buffer[i] = NULL;
}

void free_garbage_heap(void)
{
    for (int i = 0; i < garbage_heap.len; ++i)
        if (garbage_heap.buffer[i] != NULL)
            free(garbage_heap.buffer[i]);
    free(garbage_heap.buffer);
}

void resize_garbage_heap(void)
{
    garbage_heap.capacity *= 2;
    garbage_heap.buffer = (void**)realloc(garbage_heap.buffer, sizeof(void*) * garbage_heap.capacity);
    for (int i = garbage_heap.len; i < garbage_heap.capacity; ++i)
        garbage_heap.buffer[i] = NULL;
}

void* gmalloc(size_t sizemem)
{
    if (garbage_heap.len == garbage_heap.capacity)
        resize_garbage_heap();
    garbage_heap.buffer[garbage_heap.len] = malloc(sizemem);
    ++garbage_heap.len;
    return garbage_heap.buffer[garbage_heap.len - 1];
}

void* gcalloc(size_t number, size_t size)
{
    if (garbage_heap.len == garbage_heap.capacity)
        resize_garbage_heap();
    garbage_heap.buffer[garbage_heap.len] = calloc(number, size);
    ++garbage_heap.len;
    return garbage_heap.buffer[garbage_heap.len - 1];
}

void* grealloc(void* ptrmem, size_t sizemem)
{
    if (ptrmem == NULL)
        return gmalloc(sizemem);
    int i = 0;
    while (garbage_heap.buffer[i] != ptrmem)
        ++i;
    void* tmp_ptr = realloc(ptrmem, sizemem);
    if (tmp_ptr != NULL)
        garbage_heap.buffer[i] = tmp_ptr;
    return tmp_ptr;
}


texts: Giving an alternative Async method to a service

texts:
I have an interface, implemented by a service, that I inject here and there in my codebase.
I would like to give the opportunity to use either the normal method or its async equivalent.
public interface IServiceDoStuff
{
    void DoSomeHeavyWork();
    Task DoSomeHeavyWorkAsync();
}

In my implementation I just do it like this
public class Service: IServiceDoStuff
{
    public void DoSomeHeavyWork(){ ... }

    public Task DoSomeHeavyWorkAsync()
    {
        return Task.Run(() => { DoSomeHeavyWork();});
    }
}

So my consumers just go
await injectedService.DoSomeHeavyWorkAsync();

My question is simply : is that a correct way to offer those two alternatives ?
Tasks, async and await have been giving me headaches forever, as it has always been one of the most obscure .NET features I work with. I can never feel confident about the code I write using those features.


texts:
Problem statement

  Write an IIFE in which we have to validate the input provided from a form using closures. The form consists of name, email, phone, address in which name, email and phone number should not be left blank. Also validate that the given email is a valid email id using JavaScript.

  Objective

  This assignment will help you to master the following concepts:

  function
  closures

Solution

<!DOCTYPE html>

        <title>Form validation</title>
        <meta charset="UTF-8">

Fill the form

            <form action="javascript:void(0)" method="POST" enctype="multipart/form-data">
                Last Name: <input type="text" placeholder="Last name" id="lastname" required >

                First Name: <input type="text" placeholder="First name" id="firstname" required >

                Email: <input type="email" placeholder="Email" id="email" required
                                        onblur="(function(id){
                                            var email_id = document.getElementById(id).value;
                                            function validate(){
                                                var regpat = /^[a-zA-Z_\.\-]+@[a-zA-Z_\-\.]+?\.[a-zA-Z]{2,4}$/;
                                                return regpat.test(email_id);
                                            }
                                            alert(validate());
                                        })('email');">

                Phone: <input type="tel" placeholder="Phone" id="phone" required>

                address: <input type="text" placeholder="Address" id="address">

                <input type="submit" value="Submit form">
            </form>

Can this solution be improved by avoiding inline JS?

Note: IIFE -Immediately-Invoked Function Expression


texts:
We have a list.
divide the list element into two groups such that when the product of the numbers  of two groups is taken and their GCD is calculated, it came out to be 1. Answer the number of ways in which the list element can be divided into two groups following the property.

Note: The value of a group is the product of the numbers in that group. The output can be very large, so you need to take the modulo 10^9 + 7 of the answer and print it.

sample Input :

2
3
2 3 5
4
2 4 6 8

Constraints

1<= T <=5

1<= N <=10^5

1<= list_element <=10^6

Input Format

The first line consists of the number of test cases, T.

The first line of each test case consists of the number of element, N.

The second line of each test case consists of the N space-separated integers of the list.

My code is working fine but it is consuming too much time. Please help.

Below is my code.

public static List<long> GroupList = new List<long>();
    static long G_Counter = 0;
    static void Main(string[] args)
    {
        int TestCases = int.Parse(Console.ReadLine());
        List<List<long>> groupMember = new List<List<long>>();
        for (int i = 0; i < TestCases; i++)
        {
            string People = Console.ReadLine();
            groupMember.Add(Console.ReadLine().TrimEnd().Split(' ').ToList().Select(arrTemp => Convert.ToInt64(arrTemp)).ToList());
        }
        CreateGroup(groupMember);
    }
    static void CreateGroup(List<List<long>> Group)
    {
        int count=Group.Count();
        List<long> GroupCount = new List<long>();
        for (int k = 0; k < count; k++)
        {
            int lenght = Group[k].Count();
            G_Counter = 0;
            heapPermutation(Group[k].ToArray(), lenght, lenght);
            GroupList.Add(G_Counter);
        }
        int GC = GroupList.Count();
        for (int i = 0; i < GC; i++)
        {
            Console.WriteLine(GroupList[i]);
        }
            Console.ReadLine();
    }
    static bool printArr(long[] a, int n)
    {
        var k = 2;
        bool val = false;
        var res = Enumerable.Range(0, (a.ToList().Count - 1) / k + 1)
                .Select(i => a.ToList().GetRange(i * k, Math.Min(k, a.ToList().Count - i * k)))
                .ToList();

        for (int i = 0; i != res.Count(); i++)
        {

            var result1 = res[i].Aggregate((c, b) => b * c);

            for (int j = i + 1; j != res.Count(); j++)
            {
                var result2 = res[j].Aggregate((c, b) => b * c);

               long gcd_val= gcd(result1, result2);
               if (gcd_val == 1)
               {
                   val = true;

                   break;

               }
               else {
                   break;
               }
            }
        }
        return val;
    }
    static void heapPermutation(long[] a, int size, int n)
    {
        // if size becomes 1 then prints the obtained
        // permutation
        if (size == 1)
        {
         var result= printArr(a, n);
         if (result == true)
         {
             G_Counter++;
         }
        }

        for (int i = 0; i < size; i++)
        {
            heapPermutation(a, size - 1, n);

            // if size is odd, swap first and last
            // element
            if (size % 2 == 1)
            {
                long temp = a[0];
                a[0] = a[size - 1];
                a[size - 1] = temp;
            }

            // If size is even, swap ith and last
            // element
            else
            {
                long temp = a[i];
                a[i] = a[size - 1];
                a[size - 1] = temp;
            }
        }
    }
    static long gcd(long a, long b)
    {
        if (a == 0)
            return b;

        return gcd(b % a, a);
    }


texts:
As this is pure Python so using loop with big files make the code very slow
any improvements or suggestions.

Hide Code

 # Consts
HEADER_SIZE = 54
DELIMITER = "$"

class LSBEncrypter(object):
    def __init__(self):
        self.image_byte_counter = 0
        self.new_image_data = ''
        self.original_image = ''
        self.text_to_hide = ''

    def open_image(self):
        with open(ImageFile, "rb") as f:
            self.original_image = ''.join(map(chr, f.read()))
    def read_header(self):
        for x in range(0, HEADER_SIZE):
            self.new_image_data += self.original_image[x]
            self.image_byte_counter += 1
    def hide_text_size(self):
        sz = len(self.text_to_hide)
        s_sz = str(sz)
        s_sz += DELIMITER
        self.do_steg(s_sz)

    def do_steg(self, steg_text):

        for ch in range(0, len(steg_text)):

            current_char = steg_text[ch]
            current_char_binary = '{0:08b}'.format(ord(current_char))
            for bit in range(0, len(current_char_binary)):
                new_byte_binary = ''

                current_image_binary = '{0:08b}'.format(ord(self.original_image[self.image_byte_counter]))

                new_byte_binary = current_image_binary[:7]

                new_byte_binary += current_char_binary[bit]

                new_byte = chr(int(new_byte_binary, 2))

                self.new_image_data += new_byte
                self.image_byte_counter += 1
    def copy_rest(self):
        self.new_image_data += self.original_image[self.image_byte_counter:]

    def close_file(self):
        with open(StegImageFile, "wb") as out:
            out.write(bytearray(map(ord, self.new_image_data)))

    def run(self, stega_text):
        self.text_to_hide = stega_text
        self.open_image()
        self.read_header()
        self.hide_text_size()
        self.do_steg(self.text_to_hide)
        self.copy_rest()
        self.close_file()

    def hide_(self, Texte, image, steg):
        global TextToHide, ImageFile, StegImageFile
        TextToHide = Texte
        ImageFile = image
        StegImageFile = steg
        stega_instance = LSBEncrypter()
        stega_instance.run(TextToHide)

Reveal Code

 import binascii

HEADER_SIZE = 54
DELIMITER = "$"

class LSBDecrypter:
    def __init__(self):
        self.StegImageFile = ''
        # self.fh = open(StegImageFile, 'rb')
        self.number_of_chars_in_text = 0
        self.original_text = ''

    def read_header(self):
        self.fh = open(StegImageFile, 'rb')
        for i in range(0, HEADER_SIZE):
            byte = self.fh.read(1)

    def get_char(self):
        new_byte = ''

        for bit in range(0, 8):
            byte = self.fh.read(1)

            new_byte += str(ord(byte) & 0x01)

        n = int(new_byte, 2)
        desteg_char = binascii.unhexlify('%x' % n)
        desteg_char = ''.join(map(chr, desteg_char))
        return desteg_char

    def get_text_size(self):
        curr_ch = self.get_char()

        s_sz = ''

        while curr_ch != DELIMITER:
            s_sz += curr_ch
            curr_ch = self.get_char()

        if (s_sz != ''):
            self.number_of_chars_in_text = int(s_sz)

    def read_stega_text(self):
        decoded_chars = 0;
        while decoded_chars < self.number_of_chars_in_text:
            self.original_text += self.get_char()
            decoded_chars += 1

    def close_file(self):
        self.fh.close();

    def get_text(self):
        self.read_header()
        self.get_text_size()
        self.read_stega_text()
        self.close_file()
        return self.original_text

    def reveal_(self, stego):
        global StegImageFile
        StegImageFile = stego
        destag_insta = LSBDecrypter()
        text = destag_insta.get_text()
        print (text)


texts: Working with Classes (inheriting), @ properties and Initialization

texts:
I'm working on this Objective C programming assignment I found online.  I'm not sure if I have met all the requirements, especially part C. Any help or suggestion will be appreciated.

  Part 6

  a) Implement class A with properties a1, a2, and a3 (int,
  string, int).

  b) New objects are automatically initialized to 1, "hello", 1.

  c) Also provide initializer to any data and constructor (called
  without alloc) to do the same.

  d) Make sure %@ ob object of A will print all data.

  e) Then implement B inheriting from A. B adds property b (string).

  f) Make sure B works as A, that is new object is initialized to 1, "hello", 1, and 3 (the new data). The rest also must work on B.

   //classA.h file
#import <Foundation/Foundation.h>

@interface ClassA : NSObject
// Part 6a
@property int a1;
@property NSString *a2;
@property int a3;

-(NSString *) description;
-(id) initWithA1: (int) x andA2: (NSString *) s andA3: (int) y;
-(id) init;
@end

//classA.m file
#import "ClassA.h"

@implementation ClassA

-(id) initWithA1:(int)x andA2:(NSString *)s andA3:(int)y {
    self = [super init];
    if (self) {
        self.a1 = x;
        self.a2 = s;
        self.a3 = y;
    }
    return self;
}

// part 6b
- (id) init {
    return [self initWithA1:1 andA2:@"hello" andA3:1];
}

// part 6d
-(NSString *) description {
    return [NSString stringWithFormat:@"ClassA a1 = %d , a2 = %@ , a3 = %d", self.a1, self.a2, self.a3];
}

@end

//classB.h file
#import "ClassA.h"

@interface ClassB : ClassA
@property int a1;
@property NSString *a2;
@property int a3;
@property NSString * b;

-(NSString *) description;
-(id) initWithA1:(int)x andA2:(NSString *)s andA3:(int)y andB: (NSString *) z;
-(id) init;
@end

//classB.m file
#import "ClassB.h"

@implementation ClassB

-(id) initWithA1:(int)x andA2:(NSString *)s andA3:(int)y andB:(NSString *)z {
    self = [super init];
    if (self) {
        self.a1 = x;
        self.a2 = s;
        self.a3 = y;
        self.b = z;
    }
    return self;
}

-(id) init {
    return [self initWithA1:1 andA2:@"hello" andA3:1 andB:@"3"];
}

-(NSString *) description {
    return [NSString stringWithFormat:@"ClassB a1 = %d , a2 = %@ , a3 = %d , b = %@" , self.a1, self.a2, self.a3, self.b];
}

@end

//viewController.m file
#import "ViewController.h"
#import "ClassA.h"
#import "ClassB.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    ClassA * a = [ClassA new];
    NSLog(@"%@", a);

    ClassB * j = [ClassB new];
    NSLog (@"%@", j);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


texts:
I've read the docs online explaining Log N and I do understand that the basic concept of it, but I'm still not sure I've managed to nail it.

  The problem

  This exercise is called "Complementary Pairs" and given an array A
  and an integer K, how many pairs of A, sum to K.

  For example, with this input:

k = 6 a = [1, 8, -3, 0, 1, 3, -2, 4, 5]

  we would have 7 possibilities, like i, j = (5, 5) to add 3 + 3, then the
  pairs that add 1 + 5 (and the reverse), etc.

  Naive solution

  A first very naive solution is to for a \$O(N^2)\$ complexity
  loop where you just bluntly search the array in two nested loops.

\$N * Log N\$ Solution

From my understanding a proper \$Log N\$ solution has to include a binary search like quicksort or mergesort, so I applied a divide and conquer algorithm where I split the array in two, until it's down to one element, then I assemble back again, and I for a \$N*N\$ search on array, checking which elements of the first added with the second add to constant K.

Although this is very similar to mergesort, it just doesn't feel a \$N * Log N\$ solution, because the worst case, the last recursion step, I'm doing \$N/2 * N/2\$ and for me that's just \$N*N\$ over time.

Here is the working solution:

var complementary_pairs = function (input, k) {

  // Base scenario
  if (input.length == 1) {
    return input[0] * 2 == k ? 1 : 0
  }

  // Recursion
  var middle = Math.ceil(input.length / 2)
    , firstArray = input.slice(0, middle)
    , secondArray = input.slice(middle)

  var count = complementary_pairs(firstArray, k)
    + complementary_pairs(secondArray, k)

  // Problem condition
  for (var i = 0; i < firstArray.length; i++) {
    for (var j = 0; j < secondArray.length; j++) {
      if (firstArray[i] + secondArray[j] == k) {
        count += 2
      }
    }
  }

  return count

}

console.log(complementary_pairs([1, 8, -3, 0, 1, 3, -2, 4, 5], 6))


texts:
Can someone tell me if my code is okay so far? I've read quite some resources online for responsive webdesign but it seems like everyone's opinion on best practices is different.

The page I'm working on is this. It's a very simple page with very little content. Right now it works quite well on smaller devices but I want to be sure my approach is correct. In particular, I'm not sure whether my use of the units is correct.

html, body { height: 100% }
body { margin: 0; padding: 0; font-family: 'Lato', sans-serif; background-color: #eee; overflow: hidden;}

/* Content */

.container {
  position: relative;
  height: 80%;
}

img[alt="Pikachu"] {
  width: 198px;
  height: 198px;
  border: 1px solid #000;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

/* Footer */

footer {
  position: absolute;
  bottom: 0;
  left: 0;

  width: 100%;
  border-top: 1px solid #cbcbcb;
  height: 20%;
  max-height: 100px;
  min-height: 60px;
  background-color: #eee;
  text-align: center;
}

footer:after {
  content: '';
  border-top: 1px solid #fff;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}

footer > div {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  white-space: nowrap;
}

/* Footer Images */

a > img {
  width: 45px;
  vertical-align: middle;
  margin-right: 15px;
}

  img[alt="Twitch"] {
    margin-right: 0;
  }

/* Typography */

h1 {
  line-height: 48px;
  margin: 24px 0;

  color: #fff;
  text-shadow: hsl(15, 84%, 10%) 1px 1px, hsl(15, 84%, 10%) 2px 2px, hsl(15,             84%, 10%) 3px 3px, hsl(15, 84%, 10%) 4px 4px;
    text-transform: uppercase;
    text-align: center;
    white-space: nowrap;
  }

    h1::selection {
      color: hsl(15, 84%, 10%);
      background-color: #fff;
      text-shadow: none;
    }

  p {
    line-height: 24px;
    margin: 24px 0;
  }


texts:
My application has a fairly important query that is used in a lot of places. Unfortunately it takes about 14 seconds to run, so I'd like to find a way of possibly improving it.

The application receives incidents (right now there's about 70,000 total incidents, and about 16,000 incidents in this query), with each incident having a range of different flags. The purpose of the query is to get a monthly trend of the incidents and their flags.

For example:

Month |  Flagged  |  Falls  |  FallsWithInjury  | ....
-------------------------------------------------------
Jan        10          3            1
Feb        15          6            0
Mar        14          2            2
....

which I can then graph client side.

In the following query, FacilityIds are a list of facilities I want to load incidents for (about 80 IDs in the array). The start and end filters are 6 months apart.

var query = from i in Db.Incidents.Where(x => FacilityIds.Contains(x.FacilityId))
            where i.IncidentDate >= start && i.IncidentDate <= end
            group i by new { i.IncidentDate.Year, i.IncidentDate.Month } into incidentsByMonth
            let date = incidentsByMonth.Key
            select new MonthlyStat
                        {
                            Year = date.Year,
                            Month = date.Month,
                            AllIncidents = incidentsByMonth.Count(),
                            Flagged = incidentsByMonth.Count(ibm => ibm.IsSerious),
                            SentToHospital = incidentsByMonth.Count(x => x.Treatments.Any(it => it.TreatmentTypeId == (int)TreatmentTypes.Senttohospital)),
                            FallsWithInjuries = incidentsByMonth.Count(ibm => ibm.IncidentTypes.Any(it => it.IncidentTypeId == (int)IncidentTypes.Fall) && ibm.InjuryTypes.Any(inj => inj.InjuryTypeId != (int)InjuryTypes.None)),
                            FallsWithFracture = incidentsByMonth.Count(ibm => ibm.IncidentTypes.Any(it => it.IncidentTypeId == (int)IncidentTypes.Fall) && ibm.InjuryTypes.Any(inj => inj.InjuryTypeId == (int)InjuryTypes.Fracture)),
                            IncidentTypes = incidentsByMonth.SelectMany(ibm => ibm.IncidentTypes).GroupBy(it => new { it.IncidentTypeId, it.Description }).Select(it => new IncidentProperty<IncidentTypes>
                            {
                                Key = (IncidentTypes)it.Key.IncidentTypeId,
                                Count = it.Count()
                            }),
                            InjuryTypes = incidentsByMonth.SelectMany(ibm => ibm.InjuryTypes).GroupBy(it => new { it.InjuryTypeId, it.Description }).Select(it => new IncidentProperty<InjuryTypes>
                            {
                                Key = (InjuryTypes)it.Key.InjuryTypeId,
                                Count = it.Count()
                            }),
                            DayOfWeek = incidentsByMonth.GroupBy(ibm => SqlFunctions.DatePart("weekday", ibm.IncidentDate)).Select(ibm => new Aggregate<DayOfWeek> { Key = (DayOfWeek)ibm.Key.Value, Count = ibm.Count() }),
                            IncidentsByHour = incidentsByMonth.GroupBy(ibm => ibm.IncidentDate.Hour).Select(h => new Aggregate<int> { Key = h.Key, Count = h.Count() }),
                            PotentialIncurredMedian = incidentsByMonth.Select(x => x.PotentialIncurredMedian * .4).DefaultIfEmpty(0).Sum(),
                        };

Profiling different components, it looks like the IncidentTypes and InjuryTypes properties account for about 6 seconds of the 14 seconds totals. I've tried rewriting it a few different ways, but all seem to be worse in terms of performance.

I've started writing the query in native T-SQL, but I think it's a bit complex for my abilities right now.

Any suggestions would be greatly appreciated.


texts: Count of request per second, minute in java

texts:
I want to count number of requests per second, minute. I want do it fast and thread-safe. I have 2 variables to count:
private AtomicInteger count;
private AtomicInteger minutesCount;

And 2 variables for last second and minute:
private AtomicInteger currentSecond;
private AtomicInteger currentMinute;

Constructor of my service:
public StatisticServiceImpl() {
   final Calendar calendar = Calendar.getInstance();

   this.currentSecond = new AtomicInteger(calendar.get(Calendar.SECOND));
   this.currentMinute = new AtomicInteger(calendar.get(Calendar.MINUTE));

   this.count = new AtomicInteger();
   this.minutesCount = new AtomicInteger();
}

And my method to count:
public void count() {
   final Calendar calendar = Calendar.getInstance();
   int newSecond = calendar.get(Calendar.SECOND);
   int newMinute = calendar.get(Calendar.MINUTE);

   currentSecond.getAndUpdate(prev -> {
      //if it is new second, then clear second count and set new current second
      if (newSecond != prev) {
         count = new AtomicInteger();
         return newSecond;
      } else {
         count.incrementAndGet();
         return prev;
      }
   });

   currentMinute.getAndUpdate(prev -> {
      //if it is new minute, then clear minute count and set new current minute
      if (newMinute != prev) {
         minutesCount = new AtomicInteger();
         return newMinute;
      } else {
         minutesCount.incrementAndGet();
         return prev;
      }
   });
}

So, is it better (in a sense of performance and accuracy) then solution from this post?
(use LinkedList)
Or suggest better solution for this, please.


texts:
I am creating instance of the same object to populate its properties twice. I need to give this object to another developer who just don't need constructor at all, as he is sending me object through WCF service.

var a = new Earth();
a.ID= 11;
a.UpdateUniverse= true;
a = new Earth(a); // use age and Taxrate to populate rest of Earth's properties
// and call dataAccess as well to get some records
ManagerEarth.Add(a);

Here is the class you want to see:

[DataContract(Name = "Earth")]
public class Earth
{
    [DataMember]
    public int ID;
    [DataMember]
    public int PlanetID;
    [DataMember]
    public string PlanetUrl;
    [DataMember]
    public string UserID;
    [DataMember]
    public string Environment;
    [DataMember]
    public string Status;

    [DataMember(Name = "StartDate")]
    public string StartDateString
    {
        get
        {
            if(this.StartDate.HasValue)
                return this.StartDate.Value.ToString(Utils.C_DateFormat);
            else
                return null;
        }
        set
        {
            this.StartDate = Utils.ToNullableDateTime(value);
        }
    }
    public DateTime? StartDate;

    [DataMember(Name = "EndDate")]
    public string EndDateString
    {
        get
        {
            if(this.EndDate.HasValue)
                return this.EndDate.Value.ToString(Utils.C_DateFormat);
            else
                return null;
        }
        set
        {
            this.EndDate = Utils.ToNullableDateTime(value);
        }
    }
    public DateTime? EndDate;

    [DataMember]
    public bool UpdateUniverse;
    [DataMember]
    public string AuditAddress;

    public Earth()
    {

    }

    public Earth(Earth m)
    {
        if(SPContext.Current == null || SPContext.Current.Web == null)
            return;

        var planetX = new EarthDataAccess().GetByURL(SPContext.Current.Web.Site.Url);
        if(planetX == null || planetX.PlanetID < 1)
            return;

        this.PlanetID = planetX.PlanetID;
        this.PlanetUrl = planetX.PlanetHomeURL;
        this.AuditAddress = planetX.GoHomeUrl;

        this.ID = m.ID;
        this.StartDate = m.StartDate;
        this.EndDate = m.EndDate;

        this.Status = !string.IsNullOrEmpty(m.Status) ? m.Status : "Active";
        if(this.Status != "Destroyed" && this.EndDate != null)
            this.Status = "Ended";

        this.Environment = !string.IsNullOrEmpty(m.Environment) ? m.Environment : "1";
        this.UserID = m.UserID;
        this.UpdateUniverse = m.UpdateUniverse;
    }
}

Some other methods:

public static string C_DateFormat = "dd/MM/yyyy HH:mm:ss";

public static DateTime? ToNullableDateTime(string dateTime)
{
    if(string.IsNullOrEmpty(dateTime))
        return (DateTime?) null;

    var ci = CultureInfo.InvariantCulture;
    var formats = new[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "M-d-yyyy", "dd-MM-yyyy", "dd/MM/yyyy", "dd/MM/yyyy HH:mm:ss", "MM-dd-yyyy", "M.d.yyyy", "dd.MM.yyyy", "MM.dd.yyyy" }
            .Union(ci.DateTimeFormat.GetAllDateTimePatterns()).ToArray();
    var dt = DateTime.ParseExact(dateTime, formats, ci, DateTimeStyles.None);

    return dt;
}


texts:
This is the question; https://www.hackerrank.com/challenges/ctci-ransom-note/problem

I have solved this hacker rank challenge but i feel like the complexity is pretty inefficient because i use two nested loops which causes my program to run in quadratic time, i guess... I am sure there there is a better solution. Can someone tell me a better solution than what i have done. I'd also appreciate if i could get any feedback regarding my coding style or if there should be made any improvement to make it look more readable, better etc. Thank you.

function checkMagazine(magazine, note) {
  let isRansom=true
  note=note.split(' ')
  magazine=magazine.split(' ')

  for(let i of note){
    if(isRansom===false){
      console.log('No')
      return false;
    }
    else{
      for(let j of magazine){
        if(i===j){
          var index=magazine.indexOf(j)
          if(index>-1){
            magazine.splice(index,1)
          }
          isRansom=true;
          break;
        }
        else{
          isRansom=false;
        }
      }
    }
  }

  if(isRansom){
    return true
  }
}

checkMagazine('give me one grand today night','give me one grand today')


texts:
I'm starting using hooks, and I have a specific scenario that I'm thinking useEffectis appropriate for.

Essentially what I'm doing is:

I have some ssiData in the redux store.
If that data has an invite code, and the invite isn't already accepted, then I want to display a QR code
If the invite is accepted, then this component will not be displayed.
If I am displaying the QR code, then I want to dispatch an action that is going to poll for updates to the ssiData
But if the user navigates away - I want to cancel the polling.
If the connection is accepted while the QR is displayed, I want to stop polling, and the QR to disappear.

The idea is - the QR is displayed to the user, they use their phone to scan it to accept the invite.

So the way I've done this is:

function SsiQrCodeRender({ ssiData, pollForChanges, cancelPolling }) {
    const classes = useStyles();
    const image = "data:image/png;base64," + qrImage.imageSync(JSON.stringify(ssiData.invite)).toString('base64');
    useEffect(() => {
        pollForChanges(ssiData.ssiId)
        return () => {
            cancelPolling();
        }
    })
    return <Card
        component="section"
    >
        <img src={image} className={classes.root} />

    </Card>;
}

const mapStateToProps = (
    state,
    ownProps
) => {
    return {
        ssiData: ssiInitConnectionRedux.dataSelector(state)
    };
};

const mapDispatchToProps = dispatch => {
    return {
        pollForChanges: (ssiId) => dispatch(ssiPollForConnectionChangeRedux.actionFn(ssiId)),
        cancelPolling: () => dispatch(ssiCancelPolling.actionFn()),
    };
};
export const SsiQrCode = connect(
    mapStateToProps,
    mapDispatchToProps
)(SsiQrCodeRender);

And the parent component (simplified):

function SsiStudentLinkPanelRender({ ssiData, doDisplayQr }) {
    const classes = useStyles();
    return <Card
        component = "section"
        className={classes.root}>

        {doDisplayQr && <SsiQrCode />}

    </Card>;
}

const doDisplayQrSelector = (ssiData) => {
    return  ssiData.invite && ssiData.connectionState !==4 ;
}

const mapStateToProps = (
    state,
    ownProps
) => {

    const ssiData = ssiInitConnectionRedux.dataSelector(state);

    return {
        ssiData,
        doDisplayQr: doDisplayQrSelector(ssiData),
    };
};

const mapDispatchToProps = dispatch => {
    return {

};
export const SsiStudentLinkPanel =  connect(
    mapStateToProps,
    mapDispatchToProps
)(SsiStudentLinkPanelRender);

Am I going about this the right way? What I've got so far seems to work ok (although I haven't actually implemented the start polling/stop polling actions).

There's something that seems a bit complicated and flakey with this.

Is this code written such that it will necessarily have a one to one mapping of 'start polling' to 'stop polling' actions?


texts:
I am trying to learn kTurtle (slightly different from Logo) so that I can help my daughter learn to write code.  I have decided that I would write a program that would play Tic-Tac-Toe with a user.  So far, all I have is the Game board, and I make it more than just a single board to add to the intensity of my learning.  Hopefully I can get this figured out before my daughter graduates high school.

I am using kTurtle on Ubuntu which is similar to Logo but open source (free).

What I really want to know is if I am following good programming standards as this is a little different than what I am used to coding.

#Game board 1
$CanvasX = 300
$CanvasY = 300
#$x = ask "how big do you want the canvas to be?"
canvassize $CanvasX, $CanvasY

$x=$CanvasX/2
$y=$CanvasY/2

learn gameboard $a, $b, $x, $y {
    $TwoThirdsX = ($x/3)*2
    $OneThirdX = $x/3
    go $a, $b
    dir 180
    penup
    forward $OneThirdX
    turnleft 90
    pendown
    forward $x
    penup
    turnright 90
    forward $OneThirdX
    turnright 90
    pendown
    forward $x
    penup
    turnleft 90
    forward $OneThirdX
    turnleft 90
    forward $OneThirdX
    turnleft 90
    pendown
    forward $x
    penup
    turnright 90
    forward $OneThirdX
    pendown
    turnright 90
    forward $x
}
penwidth 1
gameboard 0, 0, $x, $y
$a=$x
$b=0
gameboard $a,$b,$x,$y
$a=$x
$b=$y
gameboard $a,$b,$x,$y
$a=0
$b=$y
gameboard $a,$b,$x,$y
penwidth 5
go $x, 0
forward 2*$x
go 0, $y
turnleft 90
forward 2*$y

Here is the finished product:


texts:
There's a new version of this as v2 - Adding a duplicate entry randomly into a list in haskell using random monad

I wrote this trying to set up a Haskell testcase.  The aim is to take a list and add a single duplicate from any place in the list to anywhere else in the list.

I'm trying to learn to use the Random Monad properly so the main aims should be clear, simple, idiomatic and pure code.  However any recommendations for improvement are appreciated.

-- duplicate-to-list-randmonad.hs by Michael De La Rue 2014
-- licensed to StackEschange under cc by-sa 3.0
-- may also be used under AGPLv3
-- N.B. Trivial copying of code fragments does not normally require any license.

import Data.List
import Control.Monad.Random

main :: IO ()
main = do putStrLn $ "list comparison " ++ prettyList list
          g <- getStdGen
          let shuffled = evalRand (infiniteDuplicateLists list) g
          putStrLn $ "lists after \n" ++ intercalate "\n" ( map prettyList (take 5 shuffled))
          where
            list = ["a","b","c"]

infiniteDuplicateLists genlist = do
   firstelt <- addRandomDuplicate genlist
   restoflist <- infiniteDuplicateLists genlist
   return $ firstelt : restoflist

prettyList :: (Show a) => [a] -> String
prettyList list = " [ " ++ intercalate "," (map show list) ++ " ] "

addRandomDuplicate :: MonadRandom m => [a] -> m [a]
addRandomDuplicate genlist = do
     frompos <- getRandomR (0 ,length genlist - 1)
     topos   <- getRandomR (0 ,length genlist)
     let  newlist = listEntryDuplicate (fromIntegral frompos) (fromIntegral topos) genlist
     return newlist

listEntryDuplicate from to list =
      start ++ [repeat] ++ end
    where
      repeat = list !! from
      (start, end) = splitAt to list

(edited to move fixed code to a new question version for neatness)


texts: Removing list of words from a text file in Ruby

texts:
I have two files.

File 1. Has a list of all the dictionary words
File 2. Has a list of
all prepositions.

I want to remove all the prepositions from the dictionary.
I want to reduce the number of lines in my code and also make it more elegant, idiomatic and readable.

    #!/usr/bin/env ruby

    path = "/Users/../Desktop/";

    file_original_wordlist = File.open("#{path}"  + "dictionary.txt",  "r")
    file_remove_wordlist = File.open("#{path}"  + "prepositions.txt", "r")

    # Need to initialize the variables else I get errors
    delete_word = false
    word_orig =  ''
    word_rem  =  ''
    count = 0
    file_original_wordlist.each_line do |line1|
      file_remove_wordlist.each_line do |line2|
        word_orig =  line1
        word_rem  =  line2
        if word_orig.eql?(word_rem)
          puts "Deleting the word " + word_rem
          delete_word = true
          count++
        end
      end
      if delete_word == false
        File.open(path + "scrubbed_list.txt", "a") {|f| f.write(word_orig) }
      end
  # Need to reopen the file otherwise after the first iteration to start from the beginning
      file_remove_wordlist = File.open("#{path}"  + "prepositions.txt", "r")
      delete_word = false
    end

    puts "Deleted " + count + " words in total"


texts:
Is it better to have only one class color and include the functions from the second class in the 1st one? Or leave them apart?

Why is one better than the other or vice versa? The design pattern is important to me, so why choose one over the other?

Is there a problem if, let's say, we have the function create_color in which we instantiate the class itself like new color()?

class color
{
private $id = NULL;
private $name = '';
private $rgb = NULL;
private $cmy = NULL;
private $wavelength = NULL;
private $frequency = NULL;

public function __construct($name, $rgb, $cmy, $wavelenght, $frequency)
{
setName($name);
setRGB($rgb);
setCMY($cmy);
setWavelength($wavelength);
setFrequency($frequency);
}

public function __destruct()
{
}

public function setName($name)
{
$this->name=$name;
}

public function setRGB($rgb)
{
$this->rgb=$rgb;
}

public function setCMY($cmy)
{
$this->cmy=$cmy;
}

public function setWavelength($wavelength)
{
$this->wavelength=$wavelength;
}

public function setFrequency($frequency)
{
$this->frequency=$frequency;
}

public function getId()
{
return $this->id;
}

public function getName()
{
return $this->name;
}

public function getRGB()
{
return $this->rgb;
}

public function getCMY()
{
return $this->cmy;
}

public function getWavelength()
{
return $this->wavelength;
}

public function getFrequency()
{
return $this->frequency;
}

public function toJSON()
{
return "{'id':'".$this->id."', 'name':'".$this->name."', 'rgb':'".$this->rgb."', 'cmy':'".$this->cmy."', 'wavelength':'".$this->wavelength."', 'frequency':'".$this->frequency."'}";
}

public function toCSV()
{
return $this->id . ", " . $this->name . ", " . $this->rgb . ", " . $this->cmy . ", " . $this->wavelength . ", " . $this->frequency;
}

public function toHTML()
{
return "
ID: " . $this->id . "

Name: " . $this->name . "

RGB: " . $this->rgb . "

CMY: " . $this->cmy . "

Wavelength: " . $this->wavelength . "

Frequency: " . $this->frequency . "
";
}
}

Second class:

class CRUD_color
{
public function create_color($parameters)
{
   $color=new color();
   $color->setName($parameter['name']);
   $color->setRGB($parameter['rgb']);
   $color->setCMY($parameter['cmy']);
   $color->setWavelength($parameter['wavelength']);
   $color->setFrequency($parameter['frequency']);

   $entitymanager->persist($color);
   $entitymanager->flush();
}
public function request_color($parameters)
{
   $color=$entitymanager->find($parameter['id']);
   echo $color->toJSON($parameter['name']);
}
public function update_color($parameters)
{
   $color=$entitymanager->find($parameter['id']);
   $color->setName($parameter['name']);
   $color->setRGB($parameter['rgb']);
   $color->setCMY($parameter['cmy']);
   $color->setWavelength($parameter['wavelength']);
   $color->setFrequency($parameter['frequency']);

   $entitymanager->persist($color);
   $entitymanager->flush();
}
public function delete_color($parameters)
{
   $color=$entitymanager->delete($parameter['id']);
}
}


texts: Kattis, Speed limit; read irregular input

texts:
I am able to solve this challenge but when look at my code I know it is not good.
The challenge:

Bill and Ted are taking a road trip. But the odometer in their car is broken, so they don’t know how many miles they have driven. Fortunately, Bill has a working stopwatch, so they can record their speed and the total time they have driven. Unfortunately, their record keeping strategy is a little odd, so they need help computing the total distance driven. You are to write a program to do this computation.
For example, if their log shows
Speed in miles per hour | Total elapsed time in hours
20                     | 2
30                     | 6
10                     | 7
this means they drove 2 hours at 20 miles per hour, then 6−2=4 hours at 30 miles per hour, then 7−6=1 hour at 10 miles per hour. The distance driven is then 2⋅20+4⋅30+1⋅10=40+120+10=170 miles. Note that the total elapsed time is always since the beginning of the trip, not since the previous entry in their log.
Input:
The input consists of one or more data sets. Each set starts with a line containing an integer n, 1≤n≤10, followed by n pairs of values, one pair per line. The first value in a pair, s, is the speed in miles per hour and the second value, t, is the total elapsed time. Both s and t are integers, 1≤s≤90 and 1≤t≤12. The values for t are always in strictly increasing order. A value of −1 for nsignals the end of the input.
Output:
For each input set, print the distance driven, followed by a space, followed by the word “miles”.

Sample input:
3
20 2
30 6
10 7
2
60 1
30 5
4
15 1
25 2
30 3
10 5
-1

Sample output:
170 miles
180 miles
90 miles

I try to split the input to case-by-case group and solve it using calculate but end-up with deep nested list.
import Data.List.Split

main :: IO ()
main = do
  as <- map words . lines <$> getContents
  let bs = filter (not.null) $ splitWhen ((==1).length) as
  let cs = map (map (map (read :: String -> Int))) bs
  let ds = map calculate cs
  mapM_ putStrLn ds

calculate :: [[Int]] -> String
calculate xs = z
  where as = map head xs
        bs = map last xs
        cs = head bs : zipWith (flip (-)) bs (tail bs)
        ds = zipWith (*) as cs
        z = show (sum ds) ++ " miles"

The code is ugly especially on line 7: map (map (map (read :: String -> Int)))
There are lot of let and meaningless bindings (as, bs, ...) because I need to insert print xs to see what the list is look like after each step.
Reading code again without print output, I hardly get the picture what the list structure is. This can't be good.
How should I make it better?


texts: View programming pattern in C++ without raw pointers

texts:
I'm trying to achieve, for lack of a better term, a "view" pattern in C++. It's probably most comparable to "views" in the Database world, where one can make a query, and then perhaps aggregate the data, or turn otherwise interact with it without actually duplicating the data.

I've tried to reduce it down to a simple example, where the Data is any integer, and the View is the opposite of that integer (x, -x). This example is pretty contrived, but when we're talking about matrices or other complex forms of data, I could see this pattern become quite useful, especially with respect to generic programming

The code compiles, and fundamentally, works. Unfortunately, there are alternative implementations of this pattern, and that's why I'm asking for a code review. In the long term, are there any reasons that I should be concerned about using this design pattern in my code? Perhaps with respect to:

Avoiding, Identifying Bugs
Class Flexibility
Code Readability

Some alternative implementations I can think of:

Using raw pointers instead of const references for the Data class
Using inheritance and implementing the "view" functions within the Data class

There are some important things to note about this code as well. The View class can not be copied or moved, meaning that its lifespan is identical to that of the Data class. There is also the flexibility of being able to mutate the View class when Data::view() is called, for example, setting a scalar. The two classes are mutual friends, but the Data only really has a use for the constructor of the View.

Data.h

#ifndef DATA_H
#define DATA_H

#include "View.h"

class Data {
public:
  Data(const int value) :
    view_(*this),
    value_(value)
  {}

  const View& view() const { return view_; }

  int value() const { return value_; }

private:
  friend View;

  const int value_;

  const View view_;

};

#endif // DATA_H

View.h

#ifndef VIEW_H
#define VIEW_H

class Data;

class View {
public:
  View() = delete;
  View(const View&) = delete;
  View(View&&) = delete;
  View operator=(const View&) = delete;
  View operator=(View&&) = delete;

  int value() const;

private:
  friend class Data;

  const Data& data_;

  View(const Data& data) : data_(data) {}

};

#endif // VIEW_H

View.cpp

#include "View.h"

#include "Data.h"

int View::value() const {
  return -data_.value_;
}

Example.cpp

#include "Data.h"

#include <iostream>

int main() {
  Data data{ 5 };

  const View& view = data.view();

  std::cout << data.value() << std::endl;
  std::cout << view.value() << std::endl;
}


texts:
(Homework alert)

Working my way through "The Haskell Road...", not sure about my solution to exercise 2.15 on page 48 of the second edition:

  A propositional contradiction is a formula that yields false for every combination of truth values for its propositional letters. Write Haskell definitions of contradiction tests for propositional functions with one, two, and three variables.

I somehow gather from the way the question is asked that they expect something along the lines of:

contradiction_1 :: (Bool -> Bool) -> Bool
contradiction_1 f = (f True) == False && (f False) == False

and so on.

However, previously in the text it has been shown how to use a type class to implement validity and logical equivalence:

{-# LANGUAGE FlexibleInstances #-}

class TF p where
  valid :: p -> Bool
  lequiv :: p -> p -> Bool

instance TF Bool where
  valid = id
  lequiv f g = f == g

instance TF p => (Bool -> p) where
  valid = valid (f True)
       && valid (f False)
  lequiv f g = lequiv (f True) (g True)
            && lequiv (f False) (g False)

This above is all in the textbook.

So I thought that I can simply add the definition for contradiction as follows:

class TF p where
  valid :: p -> Bool
  contradiction :: p -> Bool -- added
  lequiv :: p -> p -> Bool

instance TF Bool where
  valid = id
  contradiction f = f == False -- added
  lequiv f g = f == g

instance TF p => (Bool -> p) where
  valid = valid (f True)
       && valid (f False)
  contradiction f = contradiction (f True) -- added
                 && contradiction (f False) -- added
  lequiv f g = lequiv (f True) (g True)
            && lequiv (f False) (g False)

This now is the code from the textbook, still unchanged, only with my additions.

It seems to work, in the sense that it only returns true for actual contradictions for what I've tried so far, for example, with GHCI:

*Main> contradiction (\p -> p && (not p))
True
*Main> contradiction (\p q -> (p || q) && ((not p) && (not q)))
True
*Main> contradiction (\p q r -> p && q && ((not p) && r))
True

But I have to admit that I really don't understand what exactly the code I wrote is doing (I did it with "pattern matching", if you know what I mean).

PS: I cannot tag the question as I would like because I don't have enough rep to create new tags.


texts:
I have made this program which simulates a slot machine.

import random, time, os

def input_verify(message):
    while True:
        user_input = input(message).lower()
        if user_input in ("yes", "no"):
            return user_input
        print("Invalid Input")

def win(number_of_matches, fruit):
    global balance
    print("Well done! You got", number_of_matches, "of the same fruit!")
    time.sleep(0.5)
    reward = fruits[fruit][1] * number_of_matches
    print("You won £{}!".format(reward))
    balance += reward

fruits = {"apple": [10000, 1], "banana": [7000, 1.5], "lemon": [6000, 1.75], "orange": [5000, 2], "kiwi": [4000, 4],
          "peach": [3000, 6], "avocado": [2000, 10], "grapes": [1000, 20], "mango": [500, 100], "melon": [1, 10000]}
weighted_fruits = [fruit for fruit in fruits for i in range(fruits[fruit][0])]

print("Welcome to my slot machine! Each turn costs £1.")
balance = 10
if os.path.exists("One Armed Bandit.txt"):
    with open("One Armed Bandit.txt", "r") as f:
        contents = f.readlines()
    continue_saved_game = input_verify("Do you want to continue your saved game?")
    if continue_saved_game == "yes":
        balance = float(contents[1].strip())

time.sleep(0.5)
print("\nYour current balance is £{}.\n".format(balance))
time.sleep(1)
while True:
    balance -= 1
    reward = 0
    a, b, c = [random.choice(weighted_fruits) for i in range(3)]
    print("Spinning...")
    for fruit in (a, b, c):
        time.sleep(0.5)
        print(fruit)
    time.sleep(0.5)
    if a == b == c:
        win(3, a)
    elif a == b or a == c or b == c:
        if b == c:
            win(2, c)
        else:
            win(2, a)
    else:
        print("Unlucky. None of your fruits matched each other.")
    time.sleep(0.5)
    print("\nYour current balance is £{}.\n".format(balance))
    time.sleep(0.5)
    replay = input_verify("Do you want to play again?")
    if replay == "no":
        save = input_verify("Do you want to save your game?")
        if save == "yes":
            name = input("What is you name?")
            with open("One Armed Bandit.txt", "w") as f:
                f.write("{}'s Balance:\n{}".format(name, balance))
        break

I don't like how there are so many time.sleep() calls scattered throughout my code. Is there a way to achieve the same thing but in a cleaner way. Moreover, could you suggest some ways to make it more efficient?


texts: Print a word, one character per line, backwards

texts:
I have a problem that I solved in 2 different ways and I would like to know which one is better, cleaner and easier to read.
Problem:
Write a while loop that starts at the last character in the
string and works its way backwards to the first character in the string,
printing each letter on a separate line.
Example 1:
char = 'Wednesday'
cont = -1
cont2 = len(char)
cont3 = len(char) + 1
while cont < cont2:
    print(char[cont2:cont3])
    cont2 = cont2 - 1
    cont3 = cont3 - 1

Example 2:
char = 'Wednesday'
cont = len(char) - 1
while cont >= 0:
    cont2 = char[cont]
    print(cont2)
    cont -= 1


texts: Unit testing legacy code with static classes

texts:
I am adding new functionality into a legacy application. For my new classes I have introduced Unit Testing. I still need to work with the existing code.

One of the problems I face is that a lot of static methods have been used.

Below is an example of a class I need to use:

public class HelperClass
{
    public static bool ReturnSomething()
    {
        return true;
    }
}

My fix for making this testable:

public interface IHelperClass
{
    bool ReturnSomething();
}

public class HelperClass : IHelperClass
{
    public static bool ReturnSomething()
    {
        return true;
    }

    bool IHelperClass.ReturnSomething()
    {
        return ReturnSomething();
    }
}

A class that used to use the static method, but by introducing a property (initialized by the constructor), that now uses the testable class. I can inject a mock using this property.
Note that I could have used a factory for injecting the mock, however I wanted to keep it simple for the example.

public class UserClass
{
    public UserClass()
    {
        // Initialize with default
        HelperClass = new HelperClass();
    }

    public IHelperClass HelperClass { get; set; }
}

My advantages:

No need to modify existing code that is using the static class
Code can be migrated from static to a testable instance
I can reuse the existing concrete class

My disadvantages:

Needed to modify legacy code that needs to be tested. Not always possible when in external assembly.
PropertyName is the same as the class Name

I welcome any feedback!


texts: Replacing every letter in a string with the letter following it in the alphabet

texts:
I am working through some of the exercises at Coberbyte. The instructions for this exercise are to replace every letter in a string with the letter following it in the alphabet (i.e., c becomes d, z becomes a), then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.

Is there a better way to advance characters alphabetically than converting to ASCII, adding one, and converting back?
Is there a way to do this with one loop?
In general, are there ways to shorten/improve the code?

var txt = prompt("Please enter some text: ");
var newTxt = "";
var newTxt2= "";

for (var i = 0; i<txt.length; i++){
  if (txt.charAt(i).contains(" ")){
    newTxt = newTxt.concat(" ");//checks for spaces
  }else if (txt.charAt(i) === "z"){
    newTxt = newTxt.concat("a");//checks for "z" and sets to "a"
  }else{
    newTxt = newTxt.concat(String.fromCharCode(txt.charAt(i).charCodeAt(0)+1));
  }//converts letter to the next letter in the alphabet
}

// checks for vowels and sets to upper case
for (var i=0; i < newTxt.length; i++){
  switch(newTxt.charAt(i)){
    case "a":
    case "e":
    case "i":
    case "o":
    case "u":
    newTxt2 = newTxt2 + (newTxt.charAt(i).toUpperCase());    break;
    default:
    newTxt2 = newTxt2 + newTxt.charAt(i);
    break;
 }
}

console.log(newTxt2);


texts:
The question is: There is a set An, and it consists of integers from 1 to n.

An={1, 2, 3, ..., n}

Print all subsets of size K in An. It must be generated in order like the example below.

So for example, n=5 k=3

{1, 2, 3} {1, 2, 4} {1, 2, 5} {1, 3, 4} {1, 3, 5} {1, 4, 5} {2, 3, 4} ... {3, 4, 5}

I am not sure about if there is another way that doesn't use recursion. I did this with recursion but the problem is that all test cases should be done within 1 sec. When N and K are like 5, 3 and 12, 6 it is okay but when it comes to like 50, 48 or 100, 95, it takes too long. I am having a real struggle with this problem.

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

void subset(int n, int k, int arr[], int pos[], int index, int start){
    int i, j;

    if(index == k){
        for(j=0; j<k; j++){
            if(j==k-1)
                printf("%d\n", pos[j]);
            else{
                printf("%d ", pos[j]);
            }
        }
        return;
    }

    for(i=start; i<n; i++){
        pos[index] = arr[i];
        subset(n, k, arr, pos, index+1, i+1);
    }
}

int main(){
    int n, k, arr[100], index=0, start=0;

    scanf("%d %d", &n, &k);

    // 1<=n<=100 ; 1<=k<=n
    if(n>100||n<1 && k>n||k<1)
        return 0;

    int i;
    for(i=0; i<n; i++)
        arr[i]=i+1;

    int *pos = (int*)malloc(sizeof(int)*k);

    time_t clockstart=0, clockend=0;
    float gap;
    clockstart = clock();
    subset(n, k, arr, pos, index, start);
    clockend = clock();
    gap = (float)(clockend-clockstart)/(CLOCKS_PER_SEC);

    printf("%f\n", gap);

    return 0;
}

I think i should use something like tail recursion or vector in C++ but I can't figure out how to work with those.


texts: Create path to file under 64-bit %programfiles% from 32-bit process

texts:
I have a process that runs as 32-bits regardless of the architecture.  In it, I want to be able to spawn a process from the 64-bit program files menu (e.g. c:\program files instead of c:\program files (x86)\).

I tried using System.Environment.GetFolderPath, but for a 32 bit process, both SpecialFolders.ProgramFiles and SpecialFolders.ProgramFilesX86 returned the x86 folder.  Ditto trying to use System.Environment.ExpandEnvironmentVariables("%programfiles%").

Instead I put together this mess:

Path.Combine(System.Environment.ExpandEnvironmentVariables("%systemdrive%") + @"\", @"Program Files\...");

The Path.Combine seems pretty useless since I've already put every '\' in there, so I simplified it to:

System.Environment.ExpandEnvironmentVariables("%systemdrive%") + @"\Program Files\...";

In my environment(s), the program files folder is always on the system drive, but the system drive has varying drive letters.  Is there any better way to write this?


texts: Handling request errors in snap with haskell

texts:
I'm currently taking a look at Snap with Haskell. I'm pretty new to Haskell and functional programming in general and am working out the best way to handle errors. Currently I have something like this

createReport :: Handler b Api ()
createReport = do
report <- readRequestBody 65536
modifyResponse $ setHeader "Content-Type" "application/json"
case (decode report :: Maybe Report) of
  Just x -> do
    execute "INSERT INTO \"Reports\" (name) VALUES (?)" [name x]
    -- Do some other stuff and return a response
  Nothing -> badRequest

badRequest :: Handler b Api()
badRequest = do
 modifyResponse . setResponseCode $ 400
 writeLBS "Bad Request"

I'm really wondering if this is the best way to go about errors or is there a better way to handle errors, specifically within Snap. Also any other comments you may have would be great.

Full code here https://github.com/elliotstokes/report-generator


texts: Inserting and updating record using LINQ by calling a common function

texts:
I have a function named InserUpdateRecords(int flag) to which I pass integer variable which indicates the type of operation it has to perform , if flag==1 then insert , if flag==2 then update. Here is my code:

public void InsertUpdateRecords(int flag)
{
    Data_Customer_Log customer_log=new Data_Customer_Log();
    try
    {
        if(flag==2)
        {
            customer_log = (from cust in dt.Data_Customer_Logs
                            where cust.cApplicationNo == Request.QueryString["ApplicationNO"]
                            select cust).SingleOrDefault();
        }
        customer_log.cCustomerType = NewCustomerddlCustomerType.Text;
        customer_log.cBranchName = NewCustomerddlBranchName.Text;
        customer_log.nBranchNo = Convert.ToDecimal(Global.gBranchNo);
                     .
                     .
                     .
                     .
    }
    catch{}
}

So when I create Data_Customer_Log customer_log=new Data_Customer_Log();
and then depending on the value of flag I use it , is it an appropriate approach, what are the possible downsides to my approach.


texts: Inserting nodes into a trie data structure

texts:
I have a recursive algorithm that inserts nodes into a trie data structure but it seems to be running not well and takes over 10 mins to complete on a data set of about 1 million. All nodes contain a syllables to a phrase all of the syllables are then inserted into the trie to allow for searching in a binary fashion to attain \$n\log(n)\$ runtime.

As for my performance goal for the insertion, I'm looking for \$O(m\log(n))\$ where \$m\$ is number of phrases and \$n\$ is number of syllables in each phrase.

I am also aware of the stunning lack of memory management.

Recursion:

void Trie::recursiveInsert(Node* starting,stack<string>* words){
    if(starting->getNumberOfChildren() == 0 || starting->getChildren()[words->top()] == 0){
        Node* temp = new Node(words->top());
        starting->appendChild(temp);
        this->numberOfNodes++;
        words->pop();
        if(!words->empty()){
            recursiveInsert(temp, words);
            return;
        }else{
            temp->setEndOfWord(true);
            return;
        }

    }
    starting = starting->getChildren()[words->top()];
    words->pop();
    if(!words->empty()){
        recursiveInsert(starting, words);
    }

}

Supplementary Node class:

Node::Node(){
    this->value = "";
    this->numberOfChildren = 0;
    this->endOfWord = false;
    this->vowel = false;
}

Node::Node(string data){
    this->value = data;
    this->numberOfChildren = 0;
    this->endOfWord = false;
    this->vowel = false;
    if(isdigit(data[data.size() - 1 ])){
        this->vowel = true;
    }
}

string Node::getValue() const{
    return this->value;
}

map<string, Node*> Node::getChildren(){
    return this->children;
}

string Node::childrenToString(){
    std::map<string, Node*> v = this->children;
    string done = "the Children of \'" + this->getValue() + "\' are ";
    for ( auto it = v.begin(); it != v.end(); it++ ){
        done = done +  it->first + " ,";
    }

    return done;
}

void Node::appendChild(Node* node){
    this->children[node->getValue()] = node;
    this->numberOfChildren++;
}

int Node::getNumberOfChildren(){
    return this->numberOfChildren;
}

bool Node::isVowel(){
    return this->vowel;
}

bool Node::isEndOfWord(){
    return this->endOfWord;
}

void Node::setEndOfWord(bool value){
    this->endOfWord = value;
}


texts:
I am pretty new to Python and I would like some tips and criticism on my formatting style/code and what can be better organized. I am a bit shaky on how classes work, but I think that it can be used here to make it more simple.

from tkinter import *
from tkinter import ttk
import random

#frame setup
main = Tk()
frame = ttk.Frame(main)
button_frame = ttk.Frame(frame)
text_frame = ttk.Frame(frame)
text = Text((text_frame), borderwidth=10, height=8, width=20,    relief="sunken",)

def complex_password(): #complex password function
    password2 = []
    password2.append(random.choice((capital)))
    count = 0
    x = ""
    while count != 12:
        roll = random.randint(1,4)
        if roll == 1 or roll == 2:
            password2.append(random.choice((letters)))
            count +=1
        if roll == 3 or roll == 4:
            number = random.randint(0,9)
            number = str(number)
            password2.append(number)
            count +=1
        if count == 12:
            password2 = x.join(password2)
            text.insert(INSERT, password2)
            text.insert(INSERT, "\n")

def simple_password(): #simple password function
    y = ""
    password1 = []
    password1.append(random.choice((words)))
    password1.append(random.choice((words)))
    number = random.randint(1,99)
    num = str(number)
    password1.append(num)
    password1 = y.join(password1)
    text.insert(INSERT, password1)
    text.insert(INSERT, "\n")

def clear_text(): #clear txt box function
    text.delete(1.0, END)

#buttons
simple = ttk.Button(button_frame, text="Simple", command=simple_password)
complex = ttk.Button(button_frame, text="Complex", command=complex_password)
clear = ttk.Button(button_frame, text="Clear", command=clear_text)

#buttons grids
simple.grid(column=2, row=1)
complex.grid(column=1, row=1)
clear.grid(column=3, row=1)
text.grid()

#frame grids
frame.grid(column=1, row=2)
text_frame.grid(column=1, row=2)
button_frame.grid(column=1, row=1)

#misc settings
for child in frame.winfo_children(): child.grid_configure(padx=5, pady=10)
main.title("Password Gen")
main.resizable(width=FALSE, height=FALSE)
main.geometry("238x230")

words = ['Dog', 'Cat', 'Mouse', 'Fire', 'Ice', 'Basket', 'Tree', 'Tiger',
     'Lion', 'Flash','Super', 'Light', 'Zoom','Speed', 'Pants', 'Shirt',
     'Hat', 'Suit', 'Berry', 'Yogurt', 'Epic', 'Keyboard', 'Toe', 'Car',
     'Truck', 'Bike', 'Motor', 'Hammer', 'Pizza', 'Heart', 'Arm','Joint',
     'Saw', 'New', 'Carrots', 'Baby', 'Kiss', 'Backspace',  'Enter', 'Alt',
     'Print', "Down", 'Up', 'Question', 'Rain', 'Forest','Red', 'Orange',
     'Yellow', 'Green', 'Blue', 'Purple', 'Brown', 'Black', 'Indigo', 'Grey',
     'Shadow', 'Eye', 'Brick', 'Twig', 'Gangster', 'Thug', 'Chains', 'Gold',
     'Silver', 'Bronze', 'Platinum', 'Titanium', 'Exploding', 'Ladybug', 'Grass',
     'Monkey', 'Rhino', 'Comma', 'Hair', 'Shark', 'Fish']
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
       'n','o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
capital = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
       'N','O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

main.mainloop() #end of GUI


texts:
Usually, C++ standard library algorithms have two versions, e.g.:

template< class RandomIt >
void sort( RandomIt first, RandomIt last );

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );

Where one version is default in some sense and the second one is customized.

When I write my own algorithms, I use the following approach:

Let us suppose that I want to write a flexible algorithm that computes the average value. The standard C++ approach would be to write 2 algorithms:

template< class RandomIt >
double average( RandomIt first, RandomIt last );

template< class RandomIt, class TGetValue >
double average( RandomIt first, RandomIt last, TGetValue getValue );

where getValue is something that obtains the value to be averaged from the object pointed to by the iterator.

But what if we have an iterator that loses some information when dereferenced? For example, let us consider std::map<TKey, TValue>::iterator. This iterator results in a reference to a std::pair<TKey, TValue>, but some iterators such as QMap::iterator return a reference to TValue. That is, after we dereference QMap::iterator, we lose the ability to examine the TKey. Here some flexibility is lost:

QMap<int, double> map;
...
double averageOfKeys = average(map.begin(), map.end(), ???);

It is impossible to compute the average of keys using this interface, since the getValue object expects the thing pointed to by the iterator, which has the type of the second template parameter. There is no way we can get the key, which is of type int, from the value, which is of type double.

But the iterator itself can be used to get both the key and the value, using the iterator::key() and iterator::value() member functions. All we need to do is to change the interpretation of the getValue functor to expect an iterator instead of a thing pointed to by the iterator:

QMap<int, double> map;
...
using iterator = QMap<int, double>::const_iterator;
double averageOfKeys = average(map.begin(), map.end(),
                               [](iterator it){return it.key();});

So I made this template class:

template <class T>
class Dereference
{
public:
    typedef decltype(*std::declval<T>())                      TReference;
    typedef typename std::remove_reference<TReference>::type  TValue;
    typedef typename std::remove_cv<TValue>::type             TNonConstValue;

    TReference operator()(const T& t) const {return *t;}
};

To serve as a default argument in my algorithms. So for example for the average example, my algorithms would be:

template< typename RandomIt, typename TGetValue = Dereference<RandomIt> >
double average( RandomIt first,
                RandomIt last,
                TGetValue getValue = Dereference<RandomIt>() );

This increases the flexibility of the algorithm and reduces the need to have two overloads thanks to the default parameter.

Since I am new to programming in general and especially to C++11, I would like to ask:

If this is intuitive and usable.
If this can backfire in the future in some unexpected way.
If this approach can be improved somehow.


texts: Push Notifications - save token id into a database using Asynchronous Request

texts:
based on this answer I modified my code. Is this the correct approach now?

   func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    var userId = "001" //I just use it as USER number 1

    let token = deviceToken.hexString()

        var postBody = NSString(format: "user=%@&token=%@", userId, token)
        var endBody = NSURL(string: "http://www.myServer.com/api/v1.0/register.php")
        var request = NSMutableURLRequest(URL: endBody!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)

        request.HTTPMethod = "POST";
        request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

        var response: NSURLResponse?
        var error: NSError?

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
            (response, data, error) -> Void in

            if data != nil {
                println("data: \(response)")

            } else {

                println("failed: \(error.localizedDescription)")
            }
        }
  }

   extension NSData {
func hexString() -> String {
    // "Array" of all bytes:
    let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
    // Array of hex strings, one for each byte:
    let hexBytes = map(bytes) { String(format: "%02hhx", $0) }
    // Concatenate all hex strings:
    return "".join(hexBytes)
    }
   }


texts: Selecting orders submitted by a user, segregated by status

texts:
I have recently started using Laravel as my chosen framework. It is my first time using a framework. As I have made progress through my project, my controller methods have started to increase in size.

My concern is, I feel like I am doing it wrong. It seems way off of the OO approach.

An example of one of my controller methods:

public function viewUser($name)
    {
        $orders = Orders::where('submitter', $name)
            ->where('closed', false)
            ->where('ceased', false)
            ->where('cancelled', false)
            ->orderBy('updated_at', 'desc')
            ->get();

        $completeOrders = Orders::where('submitter', $name)
            ->where('closed', true)
            ->where('ceased', false)
            ->where('cancelled', false)
            ->orderBy('updated_at', 'desc')
            ->get();

        $cancelledOrders = Orders::where('submitter', $name)
            ->where('closed', false)
            ->where('ceased', false)
            ->where('cancelled', true)
            ->orderBy('updated_at', 'desc')
            ->get();

        $ceasedOrders = Orders::where('submitter', $name)
            ->where('closed', false)
            ->where('ceased', true)
            ->where('cancelled', false)
            ->orderBy('updated_at', 'desc')
            ->get();

        return view('admin.order-overview')->with('orders', $orders)
            ->with('completeOrders', $completeOrders)
            ->with('cancelledOrders', $cancelledOrders)
            ->with('ceasedOrders', $ceasedOrders);
    }

As you can see I run 4 seperate queries to get my desired results then I pass them to my view.

Is there a neater, more professional way to approach the above example?


texts: Initial Mass Function for young star clusters and disk field stars

texts:
I hope you can help with improving my code. I am defining a function which draws out elements of a certain mass, one by one, from a distribution constrained by the function imf(), until I have used up all the mass given to the function. The code takes a very long time between 1 minute to 45 minutes depending on the input mass. I am wondering if there is any way to make this code more effective?
In the code there are certain parameters that give trivial answers such as log10(mnorm) this was done to ensure I could in the future alter the parameters. The focus of my problem is the while loop and how it draws from the distribution given by imf(), I have identified that this part is the root course of the long performance time for the code. Any help would be greatly appreciated.

class Mod_MyFunctions:

    def __init__(self):
        pass

    def imf(self, x, imf_type):

        # Chabrier (2003) IMF for young clusters plus disk stars: lognorm and power-law tail
        mnorm = 1.0
        A1 = 0.158
        mc = 0.079
        sigma = 0.69
        A2 = 4.43e-2
        x0 = -1.3

        if imf_type == 0:
            ml = numpy.asarray((x <= log10(mnorm)).nonzero())[0]
            mh = numpy.asarray((x > log10(mnorm)).nonzero())[0]
            y = numpy.zeros(len(x))
            for i in ml: y[i] = A1 * exp(-(x[i] - log10(mc))**2/2./sigma**2)
            for i in mh: y[i] = A2 * (10.**x[i])**(x0-1)
            return y

    def mass_dist(self,
        mmin=0.01,
        mmax=100,
        Mcm=10000,
        imf_type=0,
        SFE=0.03):

        result = []
        while sum(10**(np.array(result))) < SFE*Mcm:
            x=numpy.random.uniform(log10(mmin), log10(mmax),size=1)
            y=numpy.random.uniform(0, 1, size=1)
            result.extend(x[numpy.where(y < myf.imf(x, imf_type))])

        md=numpy.array(result)
        return 10**md, len(md)


texts: Converting multiple query to use parameters to avoid SQL injection

texts:
I have some dropdownlist in my aspx page and I am using the choices from them in my SQL query:

query = "";
DataTable taskData = new DataTable();
connString = @""; //connection string
strClause = "";

if (!blOnLoad)
{
    if (ddlTaskName.SelectedIndex > 0) //dropdownlist
    {
        strClause += " AND CT.ATTR2739 LIKE '%" + ddlTaskName.SelectedItem.Text + "%'";
        //strClause += string.format();
    }
    else
    {
        strClause += " AND (CT.ATTR2739 LIKE '%' OR CT.ATTR2739 IS NULL)";
    }
    if (ddlService.SelectedIndex > 0) //dropdownlist
    {
        strClause += " AND SE.ATTR2821 LIKE '%" + ddlService.SelectedItem.Text + "%'";
    }
    else
    {
        strClause += " AND (SE.ATTR2821 LIKE '%' OR SE.ATTR2821 IS NULL)";
    }
    if (ddlStatus.SelectedIndex > 0) //dropdownlist
    {
        strClause += " AND CT.ATTR2812 LIKE '%" + ddlStatus.SelectedItem.Text + "%'";
    }
    else
    {
        strClause += " AND (CT.ATTR2812 LIKE '%' OR CT.ATTR2812 IS NULL)";
    }
    if (ddlDueDate.SelectedIndex > 0) //dropdownlist
    {
        strClause += " AND CONVERT(VARCHAR(14), CT.ATTR2752, 110) LIKE '%" + ddlDueDate.SelectedItem.Text + "%'";
    }
    else
    {
        strClause += " AND (CONVERT(VARCHAR(14), CT.ATTR2752, 110) LIKE '%' OR CONVERT(VARCHAR(14), CT.ATTR2752, 110) IS NULL)";
    }
    if (ddlOwner.SelectedIndex > 0) //dropdownlist
    {
        strClause += " AND UA.REALNAME LIKE '%" + ddlOwner.SelectedItem.Text + "%'";
    }
    else
    {
        strClause += " AND (UA.REALNAME LIKE '%' OR UA.REALNAME IS NULL)";
    }
    if (ddlClient.SelectedIndex > 0) //dropdownlist
    {
        strClause += " AND C.ATTR2815 LIKE '%" + ddlClient.SelectedItem.Text + "%'";
    }
    else
    {
        strClause += " AND (C.ATTR2815 LIKE '%' OR C.ATTR2815 IS NULL)";
    }
    if (ddlSite.SelectedIndex > 0) //dropdownlist
    {
        strClause += " AND SI.ATTR2819 LIKE '%" + ddlSite.SelectedItem.Text + "%'";
    }
    else
    {
        strClause += " AND (SI.ATTR2819 LIKE '%' OR SI.ATTR2819 IS NULL)";
    }
    if (ddlPractice.SelectedIndex > 0) //dropdownlist
    {
        strClause += " AND PR.ATTR2817 LIKE '%" + ddlPractice.SelectedItem.Text + "%'";
    }
    else
    {
        strClause += " AND (PR.ATTR2817 LIKE '%' OR PR.ATTR2817 IS NULL)";
    }
    if (ddlProvider.SelectedIndex > 0) //dropdownlist
    {
        strClause += " AND P.ATTR2919 LIKE '%" + ddlProvider.SelectedItem.Text + "%'";
    }
    else
    {
        strClause += " AND (P.ATTR2919 LIKE '%' OR P.ATTR2919 IS NULL)";
    }

    if (ddlTaskName.SelectedIndex == 0 && ddlService.SelectedIndex == 0 && ddlStatus.SelectedIndex == 0 && ddlDueDate.SelectedIndex == 0 && ddlOwner.SelectedIndex == 0 && ddlClient.SelectedIndex == 0 && ddlSite.SelectedIndex == 0 && ddlPractice.SelectedIndex == 0 && ddlProvider.SelectedIndex == 0)
    {
        query = strMainQuery + " WHERE CT.ACTIVESTATUS = 0";
    }
    else
    {
        query = strMainQuery + " WHERE CT.ACTIVESTATUS = 0" + strClause;
    }
}
else
{
    query = strMainQuery + " WHERE CT.ACTIVESTATUS = 0";
}

using (SqlConnection conn = new SqlConnection(connString))
{
    try
    {
        SqlCommand cmd = new SqlCommand(query, conn);

        SqlDataAdapter da = new SqlDataAdapter(query, conn);

        myDataSet = new DataSet();
        da.Fill(myDataSet);

        myDataView = new DataView();
        myDataView = myDataSet.Tables[0].DefaultView;

        yourTasksGV.DataSource = myDataView;
        yourTasksGV.DataBind();
    }
}

I am using the dropdownlist text right inside my SQL query which I am sure is prone to SQL injection which I am trying to prevent. I was looking around and found out I can use string.format() along with .Parameters.AddWithValue(); to ensure there is no SQL injection.

I am not sure how to actually take my code above and change it entirety to use Parameters.

How can I achieve the use of parameters instead of taking the dropdownlist text?


texts: Constructing Functions Patterned After Common Lisp Built-in Functions

texts:
This is an experiment to see what's involved in adding new functional
capability to the Common Lisp baseline. In this case, it's adding a
sequence function to select elements from a sequence satisfying a
predicate. I don't regard such baseline functions as simple utilities,
because they seem more foundational, better optimized, and better at
handling all corner cases.
The function select-if below is patterned after the standard -if
sequence functions--namely, remove-if, delete-if, substitute-if, find-if,
position-if, count-if (and their -if-not counterparts). If there's a way
to combine these functions to easily select items from an arbitrary
sequence without inventing a new function, I don't see it (although
loop does cover some cases). But in any event select-if seems like
a good test case.
(defun select-if (predicate sequence &key from-end (start 0) end
                   count (key #'identity))
  "Return elements from a sequence satisfying a predicate."
  (let* ((tally 0)
         (max-tally (or count most-positive-fixnum))
         (subsequence (if from-end
                        (nreverse (subseq sequence start end))
                        (subseq sequence start end)))
         (marker (gensym))
         (items (delete marker
                  (map 'list
                    (lambda (elem)
                      (cond ((and (< tally max-tally)
                                  (funcall predicate (funcall key elem)))
                               (incf tally)
                               elem)
                            (t marker)))
                    subsequence))))
    (declare (fixnum tally max-tally))
    (etypecase sequence
      (list items)
      (bit-vector (coerce items 'bit-vector))
      (string (format nil "~{~A~}" items))
      (vector (coerce items 'vector)))))

I'm particularly interested in whether there are better ways to do sequence selection, better optimization, and corner cases. Thanks for your time.


texts:
I'm writing my own MVC framework for learning purposes. Usually in my projects I like to use AJAX to send requests and retrive data. Now my doubt is if this can be a best approach to make a one page dashboard.

I've created an .htaccess who will display only folders that have an index file inside, the dashboard will be loaded only after user login, the login form is on the index file who is inside a folder named user. On the root of the project there is another index file who will be publicy available.

Assuming I've this code in the user dashboard file:

HTML

settings

show database entry

new insert

What is the best approach to load the requested view for the user selected action?
I want to avoid duplication of the jquery code who now is something like this

$('#open-settings').on('click',function(e){
    e.preventDefault();
    preloader.modal('show');
      $.ajax({
        type: 'GET',
        url: 'view/settings.php',
        cache: false,
        beforeSend: function(){
          preloader.modal('show');
      },
      success: function(response){
         $('#display-view').html(response)
      }
  });


texts:
context: this is somewhat related to project euler problem 5, which is:

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

I apply prime number decomposition to the range of numbers from 1 to 20, and the product of all that should be the smallest number.

(absorb '(2 2 2) '(2 3 4)) -> '(2 2 2 3 4) ;; does not have to be sorted

(defn absorb [seq1 seq2]
  (loop [s1 (sort seq1)
         s2 (sort seq2)
         acc '()]
    (let [s1-curr (first s1)
          s2-curr (first s2)]
      (cond (and (empty? s1) (empty? s2)) acc
            (empty? s1) (into s2 acc)
            (empty? s2) (into s1 acc)
            (= s1-curr s2-curr) (recur (rest s1) (rest s2) (cons s1-curr acc))
            :else (recur (rest s1) s2 (cons s1-curr acc))))))

Is there a way to write this in more idiomatic Clojure, or a more optimized/clea er version?


texts: Python list operation - merge adjacent cubes into minimum number of shapes

texts:
I am hoping to find a way to make the process a lot faster. The lists are made of rows of 6 numbers, i.e. [[float] * 6, ...]. The intent is to pass a list of cube co-ordinates (only two 3D co-ordinates, which are opposite corners) and get a shorter list of co-ordinates of 3D quadrilaterals.

# Merging by creating a list with the first cube and another with the rest.
# If the cube in the first list can be merged with a cube in the second list,
# the cube in the second list is removed and the cube in the first list is
# replaced with the merged shape.
# If there is no suitable merge to be done, the lowest positioned cube in
# the second list is moved to the first list and then we check if
# anything in the second list can be merged with it and so on.

# loops until qbs has been emptied into css
# the condition for merging is matching faces
def xmerge(qbs, css):
    tot = len(qbs)
    j = 0
    while len(qbs) > 0:
        i = 0
        k = 0
        printProgressBar(tot - len(qbs)+1, tot, prefix = ' Merging along x:',
        length = 50)
        while i < len(qbs):
            # first check if faces are touching
            if (abs(css[j][0] - css[j][3]) == abs(css[j][0] - qbs[i][0])
            and css[j][1] == qbs[i][1]
            and css[j][2] == qbs[i][2]
            # if true up to here then corners are touching
            # below we check if the faces match (same size)
            and abs(css[j][1] - css[j][4]) == abs(qbs[i][1] - qbs[i][4])
            and abs(css[j][2] - css[j][5]) == abs(qbs[i][2] - qbs[i][5])):
                css[j] = [css[j][0],css[j][1],css[j][2],
                qbs[i][3],qbs[i][4],qbs[i][5]]
                qbs = np.delete(qbs, i, axis=0)
                k = 1
            i += 1

        if k == 0:
            css = np.vstack([css, qbs[np.argmin(qbs[:,0])]])
            qbs = np.delete(qbs, np.argmin(qbs[:,0]), axis=0)
            j += 1

    print("")
    return css


texts: Setting all possible combinations of values

texts:
I have a circumstance where I need to create every single possible version of an object upon a particular magnitude. After this, a process occurs which determines the best combination of values at this magnitude and then sets these for the next iteration of the magnitude reduction loop.

const int magReductions = 2//As an example; would be user decided
int currentItem;
double bestVal1 = 5,
       bestVal2 = 5,
       bestVal3 = 5,
       bestVal4 = 5,
       bestVal5 = 5;

for (double magnitude = 1; magnitude > pow(10, -magReductions); magnitude /= 10) {
    for (int a = 0; a < 10; a++) {
        for (int b = 0; b < 10; b++) {
            for (int c = 0; c < 10; c++) {
                for (int d = 0; d < 10; d++) {
                    for (int e = 0; e < 10; e++) {
                        currentItem = (10000 * a) + (1000 * b) + (100 * c) + (10 * d) + e;
                        objectList[currentItem].val1 = ((a - 5) * magnitude) + bestVal1;
                        objectList[currentItem].val2 = ((b - 5) * magnitude) + bestVal2;
                        objectList[currentItem].val3 = ((c - 5) * magnitude) + bestVal3;
                        objectList[currentItem].val4 = ((d - 5) * magnitude) + bestVal4;
                        objectList[currentItem].val5 = ((e - 5) * magnitude) + bestVal5;
                    }
                }
            }
        }
    }
//function calculating best values
}

It is very hard to give a concise example of this in action due its nature of being very heavy on computing power.

Quite a while after writing this I look at it with quite a lot of suspicion that it is rather badly done, although no alternative method seems to present itself to me. I suppose I ask the very typical question of this site, 'Is there a better way?'.


texts:
After learning prime factorization today, below is the C code written,

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

#define FIRST_PRIME 2
typedef enum {false, true}bool;

bool isEvenlyDivide(int compositeNumber, int number){
  return (compositeNumber % number)? false:true;
}

int findOtherFactor(int compositeNumber, int number){
  return compositeNumber / number;
}

bool isPrime(int wholeNumber){
  int factorLimit = wholeNumber / 2;
  for(int isItFactor = 2; isItFactor <= factorLimit; isItFactor++){
    if(isEvenlyDivide(wholeNumber, isItFactor)){
      return false;
    }
  }
  return true;
}

bool isComposite(int wholeNumber){
  return !isPrime(wholeNumber);
}

int findNextPrime(int primeNumber){
  int number = primeNumber+1;
  if(isPrime(number)){
    return number;
  }
  return findNextPrime(number);
}

void findPrimeFactors(int compositeNumber, int primeNumber){

  if(isEvenlyDivide(compositeNumber, primeNumber)){

    printf("%d ", primeNumber);
    int otherFactor = findOtherFactor(compositeNumber, primeNumber);
    if(isComposite(otherFactor)){
      findPrimeFactors(otherFactor, FIRST_PRIME);
    }else{
      printf("%d ", otherFactor);
    }
  }else{

    int nextPrime = findNextPrime(primeNumber);
    findPrimeFactors(compositeNumber, nextPrime);
  }

  return;
}

int main(int argc, char*argv[]){

  int compositeNumber = atoi(argv[1]);

  if(argc == 1){
    printf("usage: \n");
    printf("% ./findPrimeFactors <someCompositeNumber>\n");
    exit(1);
  }

  findPrimeFactors(compositeNumber, FIRST_PRIME);
}

for which, below is the compilation and execution(in cygwin),

Personal-PC ~/code_practice/Computing/recursion
$ gcc dummy.c -o findPrimeFactors

Personal-PC ~/code_practice/Computing/recursion
$ ./findPrimeFactors 29
29 1
Personal-PC ~/code_practice/Computing/recursion
$ ./findPrimeFactors 116
2 2 29
Personal-PC ~/code_practice/Computing/recursion
$ ./findPrimeFactors 16
2 2 2 2
Personal-PC ~/code_practice/Computing/recursion
$ ./findPrimeFactors 14
2 7

Do you think the code is complete from conceptual and implementation
aspect?
If yes, Can we further make this code, elegant & high perform?
If yes, Can I make it a stateless functional program using C?

Note: It took 15 minutes for me to write this program


texts: Find files by pattern and copy to target location

texts:
This is my solution to the Chapter 9 exercise in Automate the Boring Stuff:

  Selective Copy

  Write a program that walks through a folder tree and searches for files with a certain file extension (such as .pdf or .jpg). Copy these files from whatever location they are in to a new folder.

#!/usr/local/bin/python3
#selectiveCopy.py - Walks through a folder tree with the extension .PDF and copies them to a new folder.

import re
import os
import shutil

filePdf = re.compile(r"""^(.*?)          #text before extension
          [.][p][d][f]                   #extension .pdf
          """, re.VERBOSE)

def selectiveCopy(fileExtension):
    for pdfFiles in os.listdir("/Users//Desktop/newPDFs"):
        locatedFiles = filePdf.search(pdfFiles)
        if locatedFiles != None:
            print(locatedFiles)
            files_to_copy = os.path.join("/Users/my_user_name/Desktop/newPDFs", pdfFiles)   `
            shutil.copy(files_to_copy, "/Users/my_user_name/Desktop/oldPDFs")
            print("The following file has been copied " + files_to_copy)
selectiveCopy(filePdf)

I appreciate for probably all of you on here that it's not a very difficult exercise, but I've been working through this book slowly and have just decided it's probably a good idea to start putting them on a Github page.  I wanted to know if I could improve the code to make it more efficient or if there are some things I've included that aren't necessarily considered "standard practice".


texts:
I am trying to convert hex to rgb, and rgb to hex. My current code doesn't seem optimal, and there is an issue with 0's in the hexadecimal. What do you think about the overall quality of this code? Can you think of a more efficient way of converting?

  $scope.$watch('hex', function() {
    var rgb = parseInt($scope.hex, 16);
    $scope.r = (rgb >> 16) & 0xFF;
    $scope.g = (rgb >> 8) & 0xFF;
    $scope.b = rgb & 0xFF;
    $scope.rgb = 'rgb(' + $scope.r + ',' + $scope.g + ',' + $scope.b + ');';
  });

  $scope.$watch('r+g+b', function() {
    $scope.rgb = 'rgb(' + $scope.r + ',' + $scope.g + ',' + $scope.b + ');';
    $scope.hex = parseInt($scope.r << 16 | $scope.g << 8 | $scope.b).toString(16);
  });

Here is a sample plunker:


texts: Custom concurrent stack implementation in Java

texts:
I don't want to use synchronized for sizeof method, any suggestion to implement the method thread safe?

package com.r.collection.adt;

import java.util.concurrent.atomic.AtomicReference;

public class ConcurrentStack<E> implements Stack<E>{

    @SuppressWarnings("hiding")
    private class Node<E>{

        public E item;
        public Node<E> next;

        public Node(E item){
            this.item=item;
        }

    }

    @SuppressWarnings("rawtypes")
    private AtomicReference<Node> head;

    @SuppressWarnings("rawtypes")
    ConcurrentStack(){
        head = new AtomicReference<Node>();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void push(E item) {
        Node<E> newHead = new Node<E>(item);
        Node<E> headNode = null;
        do
        {
            headNode = head.get();
            newHead.next = headNode;
        }while(!head.compareAndSet(headNode, newHead));

    }

    @SuppressWarnings("unchecked")
    @Override
    public E pop() {
        Node<E> headNode = head.get();
        do
        {
            headNode = head.get();
            if(headNode == null)
                return null;
        }while(!head.compareAndSet(headNode, headNode.next));

        return headNode.item;
    }

    @SuppressWarnings("unchecked")
    @Override
    public E peek() {
        Node<E> headNode = head.get();
        if(headNode == null){
            return null;
        }

        return headNode.item;
    }

    @Override
    public boolean isEmpty() {

        return head.get() == null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public synchronized int  sizeOf() {
        int size=0;
        for(Node<E> node=head.get();node != null; node=node.next){
            size++;
        }
        return size;
    }

}


texts:
From 2.11

  Exercise 2.11.  In passing, Ben also
  cryptically comments: ``By testing the
  signs of the endpoints of the
  intervals, it is possible to break
  mul-interval into nine cases, only one
  of which requires more than two
  multiplications.'' Rewrite this
  procedure using Ben's suggestion.

I wrote the following:

(define (negative? . n) (or (= 0 (length n))
                            (and (> 0 (car n)) (apply negative? (cdr n)))))

(define (positive? . n) (or (= 0 (length n))
                            (and (>= (car n) 0) (apply positive? (cdr n)))))

(define (straddles-zero? x) (and (>= 0 (lower-bound x))
                                 (>= (upper-bound x) 0)))

(define (fast-mul-interval x y)
  (let* ((u-x (upper-bound x))
        (u-y (upper-bound y))
        (l-x (lower-bound x))
        (l-y (lower-bound y)))
    (cond
      ; same sign - max is neg, or min is pos
      ((positive? l-y l-x) (make-interval (* l-x l-y) (* u-x u-y)))
      ((negative? u-y u-x) (make-interval (* u-x u-y) (* l-x l-y)))
      ; x and y have opposite signs
      ((and (positive? l-x)
            (negative? u-y)) (make-interval (* u-x l-y) (* l-x u-y)))
      ((and (positive? l-y)
            (negative? u-x)) (make-interval (* l-x u-y) (* u-x l-y)))

      ; x straddles zero
      ((straddles-zero? x)
       (if (straddles-zero? y)
           (make-interval (min (* l-x u-y) (* l-y u-x))
                          (max (* l-x l-y) (* u-x u-y)))
           (if (negative? u-y)
               (make-interval (* u-x l-y) (* l-x l-y))
               (make-interval (* l-x u-y) (* u-x u-y)))))
      ((straddles-zero? y)
       (if (negative? u-x)
           (make-interval (* u-y l-x) (* l-y l-x))
           (make-interval (* l-y u-x) (* u-y u-x)))))))

What do you think?

The new version is here:

(define (fast-mul-interval x y)
  (let ((l-x (lower-bound x))
        (u-x (upper-bound x))
        (l-y (lower-bound y))
        (u-y (upper-bound y)))
    (cond ((> l-x 0)
           ;x > 0
           (cond ((> l-y 0)
                  ;y > 0
                  (make-interval (* l-x l-y) (* u-x u-y))
                  )
                 ((< u-y 0)
                  ;y < 0
                  (make-interval (* u-x l-y) (* l-x u-y))
                  )
                 (else
                  ;y contains 0
                  (make-interval (* u-x l-y) (* u-y u-x))
                  ))
           )
          ((> l-y 0)
           ;y > 0
           (if (< u-x 0)
               ; x < 0
               (make-interval (* u-y l-x) (* l-y u-x))
               ; x contains 0
               (make-interval (* l-x u-y) (* u-x l-y))
               )
           )
          ((< u-x 0)
           ;x < 0
           (if (< u-y 0)
               ; y < 0
               (make-interval (* u-x u-y) (* l-x l-y))
               ; y contains 0
               (make-interval (* u-y u-x) (* l-y u-x))
               )
           )
          ((< u-y 0)
           ;y < 0 and x contains 0
           (make-interval (* u-y u-x) (* l-x u-y))
           )
          (else
           ;x and y both contain 0
           (let ((p1 (* l-x l-y))
                 (p2 (* l-x u-y))
                 (p3 (* u-x u-y))
                 (p4 (* u-x l-y)))
             (make-interval (min p1 p2 p3 p4) (max p1 p2 p3 p4)))
           ))))


texts:
I was wondering about on how to organise the code on my site, to make it clearer as possible and clearly readable.

I'm organising it with namespace, separating every single section of the page.

For example:

var Header = {
//code relative to the header
}

var CentralBody = {
//code relative to the CentralBody
}

$(function(){
//code to execute on doc ready

});

First of all, I would know if it is a good way to organise code. In second instance, I was thinking about "what must be placed where". I explain: If, for example, I have to assign some tooltip or to bind event with code like

$('someclass').tooltip()
$('someclass').on( 'event' , ... );

where do I have to place this kind of "functions"? Do I have to place them in the concerning namespace?  Do I have to place them on document.ready?  Or writing functions in namespace and then call them on document.ready?