texts: Create user in users table and insert data into second table with one form in Laravel Relationships

texts:
I'm trying  to create a user while adding data to a second table via one form:

users table:

Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

info table:

Schema::create('infos', function (Blueprint $table) {
        $table->id();
        $table->string('fname');
        $table->string('lname');
        $table->string('dateofbirth');
        $table->string('phonenumber')
        $table->timestamps();
    });

info_user table:

Schema::create('info_user', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id');
        $table->unsignedBigInteger('info_id');
        $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('info_id')->references('id')->on('infos')->onUpdate('cascade')->onDelete('cascade');
        $table->timestamps();
    });

User.php Model

public function infos() {
    return $this->belongsToMany(Info::class)->withTimestamps();;
}

Info.php Model

public function users() {
    return $this->belongsToMany(User::class)->withTimestamps();
}

And my attempt at InfoController

public function store(Info $info, User $user, Request $request)
{

        User::create([
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $data = new Info;
        $data->fname = $request->fname;
        $data->lname = $request->lname;
        $data->dateofbirth = $request->dateofbirth;
        $data->phonenumber = $request->phonenumber;

        $data->save();

    return redirect('/');
}

I'm trying to figure out how to register a user while adding info to the second table so they have a common info_user table.

I think I succeeded, but only if it is right and especially safe.

public function store(Info $info, User $user, Request $request)
{
        $user = User::create([
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $data = new Loan;

        $data->fname = $request->fname;
        $data->lname = $request->lname;
        $data->dateofbirth = $request->dateofbirth;
        $data->phonenumber = $request->phonenumber;

        $data->save();

        $user->infos()->attach($data);

    return redirect('/');
}


texts:
Following code produces number sequentially. There will be only one such producer, However there can be many threads to pause/resume the list of sequential numbers.

package pauseresume;

public class Sequential implements Runnable {
  volatile boolean pause;

  @Override
  public void run() {
    long i = 0;
    while (true) {
      while (pause) {
        synchronized (this) {
          try {
            wait();
          } catch (InterruptedException e) {
          }
        }
      }
      System.out.println(i);
      try {
        Thread.sleep(10);
      } catch (InterruptedException e) {
      }
      i++;
    }
  }

  public synchronized void pause() {
    pause = true;
  }

  public synchronized void resume() {
    pause = false;
    notifyAll();
  }
}

Does the code seems thread-safe?


texts: Refresh the List box with new rooms from the server every 3 seconds

texts:
So i have a server which I send a Request to and it sends me back a list of rooms,Now i made a window for joining rooms and I'm trying to refresh it every 3 seconds but when i use the Timer thread to refresh the list it doesn't work if I use the normal refresh method with the Timer it works just fine.
Here's some code:
private void AutoRefresh()
{
   System.Timers.Timer timer = new System.Timers.Timer(TimeSpan.FromMilliseconds(3000).TotalMilliseconds);
   timer.AutoReset = true;
   timer.Elapsed += new System.Timers.ElapsedEventHandler(this.Refresh);
   timer.Start();
  }

private void Refresh(object sender, System.Timers.ElapsedEventArgs elapsedEventArg)
{
    GetRoomsResponse response;
    response = SendAndRecv();
    Button temp;
    foreach (RoomData room in response.rooms)
    {
        temp = new Button { Content = room };
        temp.Click += (sender, e) =>
    {
        JoinRoomClick(sender, e);
    };
        temp.Content = room.Name;
        buttons.Add(temp);
    }
ListBoxRooms.ItemsSource = buttons;
}

If I call refresh from the main it works perfectly if I call AutoRefresh it doesn't I think it gets stuck on the for each loop no error's just doesn't do it's job


texts: How to optimize these nested loops for better performance?

texts:
I need to optimize this code so it can execute faster, even if that means using more memory:

for (int t = 0; t < Clientes[0].ChildNodes.Count; t++)
{
    for (int i = 0; i < Clientes[0].ChildNodes.Item(t).ChildNodes.Count; i++)
    {
        if (Clientes[0].ChildNodes.Item(t).ChildNodes.Item(i).Name.Contains("Service"))
        {
            int a = 0;
            int.TryParse(Clientes[0].ChildNodes.Item(t).ChildNodes.Item(i).Name.ToUpper().Replace("SERVICE", ""), out a);
            if (a.Equals(Type))
            {
                Queues[t].Send(QueueMessage);
            }
        }
    }
}

I have decided to avoid accessing Clientes[0] and its ChildNodes.Item(t) over and over in each loop by keeping them in new variables like this:

XmlNodeList clientZeroChildNodes ;
int clientZeroChildCount ;

XmlNodeList clientZeroItemTchildNodes ;
int clientZeroItemTchildCount;
string clientZeroItemTchildIname;

clientZeroChildNodes = Clientes[0].ChildNodes;
clientZeroChildCount = clientZeroChildNodes.Count;

for (int t = 0 ; t < clientZeroChildCount ; t++)
{
    clientZeroItemTchildNodes = clientZeroChildNodes.Item(t).ChildNodes;
    clientZeroItemTchildCount = clientZeroItemTchildNodes.Count;

    for (int i = 0; i < clientZeroItemTchildCount; i++)
    {
        clientZeroItemTchildIname = clientZeroItemTchildNodes.Item(i).Name;

        if (clientZeroItemTchildIname.Contains("Service"))
        {
            int a = 0;

            int.TryParse(clientZeroItemTchildIname.ToUpper().Replace("SERVICE", ""), out a);

            if (a.Equals(Type))
            {
                try
                {
                    Queues[t].Send(QueueMessage);
                }
                catch (MessageQueueException mqe)
                {
                    //log error about mqe
                }
            }
        }
    }

}

As you can see, the second for loop only takes certain items of the ChildNodes based on its name. I have tried to use LINQ so that the second for only iterates the list of ChildNodes that match both of the if conditions that are inside the loop but have not been able to do it.

Can you show me how would you improve the speed of the original code focusing on an efficient way to improve the loops and nested ifs? I am not trying to determine which line of code is taking longer and the performance of the Queues is not relevant for me.


texts: Google CodeJam 2016 - Python Counting Sheep

texts:
I decided to try some google codejam problems to get some more experience coding. The problem is at http://code.google.com/codejam/contest/6254486/dashboard, my solution is below. It gets the correct solution but would appreciate any tips on coding.

Problem

  Bleatrix Trotter the sheep has devised a strategy that helps her fall asleep faster. First, she picks a number N. Then she starts naming N, 2 × N, 3 × N, and so on. Whenever she names a number, she thinks about all of the digits in that number. She keeps track of which digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) she has seen at least once so far as part of any number she has named. Once she has seen each of the ten digits at least once, she will fall asleep.

  Bleatrix must start with N and must always name (i + 1) × N directly after i × N. For example, suppose that Bleatrix picks N = 1692. She would count as follows:

  N = 1692. Now she has seen the digits 1, 2, 6, and 9. 2N = 3384. Now she has seen the digits 1, 2, 3, 4, 6, 8, and 9. 3N = 5076. Now she has seen all ten digits, and falls asleep. What is the last number that she will name before falling asleep? If she will count forever, print INSOMNIA instead.

  Input

  The first line of the input gives the number of test cases, T. T test cases follow. Each consists of one line with a single integer N, the number Bleatrix has chosen.

  Output

  For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the last number that Bleatrix will name before falling asleep, according to the rules described in the statement.

Code

import os

def getnumber(number,numberoftries):
  N = number
  digitlist = []
  print "new case number = " + str(number)
  for j in range(1,numberoftries):
    N = str(N)
    N.rstrip()
    digits = []
    for l in range(0,len(N)):
      if N[l] not in digits:
        digits.append(N[l])
       # print digits
    for l in range(0,len(digits)):
      k = digits[l]
      #  Add digits to digitlist
      if k not in digitlist:
        digitlist.append(k)
        print digitlist
  # check if we have all digits
    count = 0
    for k in range (0,10):
      if str(k) in digitlist:
        count = count + 1
    if count == 10:
      print "count = 10"
      return str(N)
    else:
      N = number * (j+1)
      print "number = " + str(N)
  return "INSOMNIA"

numberoftries = 1000
path = '/home/username/GoogleCodeJam/'
inputfile = 'A-large-practice.in'
inputfilename = path + inputfile
outputfilename = path + 'largeoutput'
f = open(inputfilename, "r")
numberofcases = f.readline()
o = open(outputfilename,"w")
for i in range (1,int(numberofcases)+1):
  N = f.readline()
  N = int(N)
  result = getnumber(N,numberoftries)
  outputline = 'Case #' + str(i) + ': ' + str(result) + '\n'
  o.write(outputline)
o.close()


texts: Project Euler #1: Sum of Multiples of 3 and 5 below 1000

texts:
def prob_1():
    sum_mult=[]  #Create an empty list which will take sum of multiples of 3 and 5
    check_sum=0
    for i in range(1,1000): #Take numbers till 1000
    #if(i)
        if( (i%3)==0 or (i%5)==0 ): #divisor condition
            sum_mult.append(i)

    return sum(sum_mult)    #return sum of list

I am just starting out my journey as a programmer, here is my code and I would love to see any critical feedback and other alternative solutions maybe using some clever hack of using lambda function's etc.


texts: How can I improve the following stored procedure?

texts:
I have created the following stored procedure which duplicates a record in a table and also all its related records in other tables however since I am a newbie to SQL I would appreciate it if someone could review my code and show me how it could be improved and whether there are any hazards.

   USE [Neptune2Dev]
    GO
    /****** Object:  StoredProcedure [dbo].[DuplicateItemInBatch]    Script Date: 03/04/2013 17:55:47 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER PROCEDURE [dbo].[DuplicateItemInBatch] @batchID AS INT , @numInBatch AS INT

    AS

    declare @itemIdToBeDuplicated as int
    declare @duplicatedItemID as int
    declare @URI as varchar(max)
    declare @itemOrganisationID as int
    declare @duplicateItemOrganisationID as int

    BEGIN TRY
        BEGIN TRANSACTION;

           --increment all proceeding numbInbatch fileds to accomodiate the new item being duplicated
           UPDATE items  SET numinbatch = numinbatch + 1
        WHERE numinbatch > @numInBatch AND BatchID = @batchID

           select @itemIdToBeDuplicated = ID from items i where i.BatchID = @batchID and i.NumInBatch = @numInBatch
           select @URI = URI from ItemMedia where ID = @itemIdToBeDuplicated

           --duplicate the item and insert it into the table
           insert into items
           select
           i.SupplierID, i.Title, i.PubDate, i.Body, i.StatusID,
           i.IsRelevant, i.ClipDuration, i.ResearchDuration,
           i.Comments, i.ItemTypeID, i.PageNumber, i.BatchID,
           i.NumInBatch + 1, i.OverrideDate, i.MediaChannelID,
           i.Size, i.PreviouslyCompleted
           from items i where i.ID = @itemIdToBeDuplicated
           select @duplicatedItemID =  SCOPE_IDENTITY();

           select @itemOrganisationID = ID from ItemOrganisations where ItemID = @itemIdToBeDuplicated
           insert into ItemOrganisations
           select @duplicatedItemID, OrganisationID, comment, rating from ItemOrganisations where ID = @itemOrganisationID
           select @duplicateItemOrganisationID = SCOPE_IDENTITY();

           insert into ItemOrganisationMessages
           select @duplicateItemOrganisationID, MessageID from ItemOrganisationMessages where ItemOrganisationID = @itemOrganisationID

           insert into ItemOrganisationIssues
           select @duplicateItemOrganisationID, IssueID from ItemOrganisationIssues where ItemOrganisationID = @itemOrganisationID

           insert into ItemByLines
           select @duplicatedItemID, ByLineID from ItemByLines where ItemID = @itemIdToBeDuplicated

           insert into ItemDocumentLink
           select ItemDocumentID, @duplicatedItemID from ItemDocumentLink where ItemID = @itemIdToBeDuplicated

           insert into ProfileResults
           select ProfileId, @duplicatedItemID from ProfileResults where ItemID = @itemIdToBeDuplicated

           insert into ItemNotes
           select  @duplicatedItemID,Quote,Theme,Rating,Comment,IsBad from ItemNotes where ItemID = @itemIdToBeDuplicated

           IF @URI <> null
           BEGIN
                  insert into ItemMedia values (@duplicatedItemID, @URI)
           END
           ELSE
        PRINT  N'No Article to be duplicated '

        COMMIT TRANSACTION;
        END TRY
        BEGIN CATCH
    BEGIN
        PRINT
            ERROR_NUMBER() +' ' + ERROR_MESSAGE()
        ROLLBACK TRANSACTION;
    END;
END CATCH;


texts: Selecting mail messages that meet one of four search criteria

texts:
This is the current very repetitive and long SQL I have. Unfortunately I'm not that good at SQL to group this and get rid of the repetition.

select * from Mail
where admin_status = 1
and admin_id = 4
and core_event_id =0
and user_id !=0
and mail_reply_status = 0
and sent_to = 0
and admin_inbox_date > DATE_SUB(CURDATE(), INTERVAL 48 HOUR)

or ( admin_status = 1
and admin_id = 4
AND sent_to = 0
and mail_reply_status = 0
and user_id != 0
and core_event_inactive = 1)
and admin_inbox_date > DATE_SUB(CURDATE(), INTERVAL 48 HOUR)

or (`subject` like 'RE:%'
AND admin_status = 1
AND `admin_id` = 4
and core_event_id =0
and user_id != 0
and mail_reply_status = 0
and sent_to = 4 )
and admin_inbox_date > DATE_SUB(CURDATE(), INTERVAL 48 HOUR)

or (`subject` like 'RE:%'
and admin_status = 1
and admin_id = 4
AND sent_to = 0
and mail_reply_status = 0
and user_id != 0
and core_event_inactive = 1)
and admin_inbox_date > DATE_SUB(CURDATE(), INTERVAL 48 HOUR)


texts: One of my first Bash scripts - checking for best practice and error handling

texts:
I have a Bash script that resides on Remote Server A and transfers files from Remote Server 1 to Remote Server 2. Remote Server 2 is a Dropbox folder so in this script, I call another script (that's not mine) to interface with the Dropbox API.

This is one of my 1st forays into the Bash-scripting world (I'm mostly a designer and front-end guy), so I'd love to hear some input on how close to "best practices" I've come. Also, I'm not 100% positive I've handled errors correctly (using a combination of trap and checking various commands' return signals). And of course, if there are any blaring performance or security issues, let me know. Thanks in advance.

#!/usr/bin/env bash

clean_up () {
    ARG=$?

    if mount | grep $localPath > /dev/null; then
        fusermount -u $localPath
    fi

    if [ -d $localPath ]; then
        rm -rf $timestamp
    fi

    if [ ${#errors[@]}  -gt 0 ] ; then
        figlet -f small Error
        (   IFS=$'\n'; echo "${errors[*]}" )
        echo "***"
        echo "This is not typical - please copy the error message above and  notify your developer immmediately."
        echo "***"
    else
        figlet -f small Success
        echo "Upload Complete - Files now accessible via Dropbox"
    fi

    echo
    echo

    exit $ARG
}
trap clean_up EXIT

timestamp=$(date +%Y.%m.%d-%H.%M.%S)
localPath=$PWD/$timestamp

token="MY_TOKEN"
sourcePath=chef/revel
destPath=/chef_uploads
pattern=*.txt
user=me
server=example.com
DIR=/chef_uploads

errors=()

mkdir $timestamp

sshfs $user@$server:$sourcePath ${localPath}
if [ $? -eq 0 ]; then
    echo
    echo
    echo "Transferring $timestamp to $destPath"
    ./dropbox_uploader.sh -p -h upload "$timestamp/" "$destPath/"
    if [ $? -gt 0 ]; then
        errors+=(" !! ERROR: cannot copy files to $timestamp.")
    fi
else
    errors+=("     ERROR: cannot mount remote filesystem - $timestamp")
fi


texts: Printing a score sheet for baseball batters

texts:
I've been learning Python 2.7 for about a week now and have written a quick program to ask for names of batters and printing a score sheet. I have then added the names to a list which I will use more in other future functions.

I have a few questions:

I feel like there is too much repetition in my code, such as the prompting for each batter and all the printing. I am trying to figure out how I could use a loop to do these for me. Since I know I need 11 batters a for loop would be best but I need to make a new variable each time, how can I do this?
I have been reading around about the use of global. I can't seem to get a definite answer but is this the correct use if I want to use a variable from one function in multiple others?

def Input_Players():

    global First, Second, Third, Fourth, Fith, Sixth, Seventh, Eigth, Ninth, Tenth, Eleventh

    First = [raw_input("Name of 1st Batsman > ")]
    Second = [raw_input("Name of 2nd Batsman > ")]
    Third = [raw_input("Name of 3rd Batsman > ")]
    Fourth = [raw_input("Name of 4th Batsman > ")]
    Fith = [raw_input("Name of 5th Batsman > ")]
    Sixth = [raw_input("Name of 6th Batsman > ")]
    Seventh = [raw_input("Name of 7th Batsman > ")]
    Eigth = [raw_input("Name of 8th Batsman > ")]
    Ninth = [raw_input("Name of 9th Batsman > ")]
    Tenth = [raw_input("Name of 10th Batsman > ")]
    Eleventh = [raw_input("Name of 11th Batsman > ")]

def Print_Score_Sheet():
    total_chars = 56

    Batsman = First + Second + Third + Fourth + Fith + Sixth + Seventh + Eigth + Ninth + Tenth + Eleventh

    print "1." + Batsman[0] + "." * (total_chars - len(Batsman[0]) + 2)
    print "2." + Batsman[1] + "." * (total_chars - len(Batsman[1]) + 2)
    print "3." + Batsman[2] + "." * (total_chars - len(Batsman[2]) + 2)
    print "4." + Batsman[3] + "." * (total_chars - len(Batsman[3]) + 2)
    print "5." + Batsman[4] + "." * (total_chars - len(Batsman[4]) + 2)
    print "6." + Batsman[5] + "." * (total_chars - len(Batsman[5]) + 2)
    print "7." + Batsman[6] + "." * (total_chars - len(Batsman[6]) + 2)
    print "8." + Batsman[7] + "." * (total_chars - len(Batsman[7]) + 2)
    print "9." + Batsman[8] + "." * (total_chars - len(Batsman[8]) + 2)
    print "10." + Batsman[9] + "." * (total_chars - len(Batsman[9]) + 1)
    print "11." + Batsman[10] + "." * (total_chars - len(Batsman[10]) + 1)

Input_Players()
Print_Score_Sheet()


texts: Is this a good example of Reactive Extensions? How can I make this better?

texts:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;

namespace ReactiveExtensions
    {
    class Program
        {
        static void Main(string[] args)
        {
            var start = Observable.Start(() =>
            {
                Console.WriteLine("Getting some work done");
                for (var i = 0; i < 10; i++)
                    {
                    Thread.Sleep(10000);
                    //go call stackoverflow
                    var d = CallStackOverFlow();
                    //send the result for checking to a delegate
                    foreach (var q in d.questions)
                        {
                            var list = (q.tags as JArray).Values().Select(v => v.ToString()).ToList();
                            var result = FindByTag(list);
                            if(result)
                                Console.WriteLine("Quesion title :{0}",q.title);
                        }
                 }
                return "I am done observing";
            });
            Console.WriteLine("Subscribing"); // Make visible when we subscribe
            start.Subscribe(Console.WriteLine);
            Console.ReadKey();
        }

        private static readonly Func<List<String>,bool> FindByTag =(x => x.Contains("c#"));

        private static dynamic CallStackOverFlow()
        {
            var client = new RestClient("http://api.stackoverflow.com/1.1");
            var request = new RestRequest("/questions/no-answers", Method.POST);
            var response = client.Execute(request);
            var content = response.Content; // raw content as string
            dynamic deserialised = JsonConvert.DeserializeObject(content);
            return deserialised;
        }
     }
  }

Please add the tag for ReactiveExtensions , my reputation does not allow me to do that.


texts:
The following query is taking over 800ms to run, and returning 300 rows. When deployed to SQL Azure, it takes much longer on an affordable price tier.

SELECT
    Tests.Id,
    Tests.Title,
    Tests.AuthorId,
    Tests.[Status],
    Users.FirstName + ' ' + Users.LastName AS AuthorName,
    (SELECT
        COUNT(1)
     FROM Results LEFT JOIN Users ON Results.UserId = Users.Id
     WHERE
        Results.TestId = Tests.Id AND
        Results.MarkedBy IS NULL AND
        Results.QuestionNumber >= 1 AND
        EXISTS (
          (SELECT ClassName FROM UserClasses WHERE UserClasses.UserId = Users.Id)
          INTERSECT
          (SELECT ClassName FROM TestClasses WHERE TestClasses.TestId = Tests.Id)
          INTERSECT
          (SELECT ClassName FROM UserClasses WHERE UserId = @teacherId)
        )
    ) AS UnmarkedCount,
    (CASE WHEN EXISTS (SELECT 1 FROM Results WHERE Results.TestId = Tests.Id)
      THEN CAST(1 AS BIT)
      ELSE CAST(0 AS BIT) END
    ) AS AnyResults,
    (SELECT Stuff((SELECT ',' + ClassName FROM
      (
        (SELECT ClassName FROM TestClasses WHERE TestClasses.TestId = Tests.Id)
        INTERSECT
        (SELECT ClassName FROM UserClasses WHERE UserId = @teacherId)
      ) x FOR XML PATH ('')),1,1,'')
    ) AS Classes
FROM
    Tests INNER JOIN Users ON Tests.AuthorId = Users.Id
WHERE
    Users.SchoolId = @schoolId AND Tests.Status <= 4

An overview of the schema:

Users include students and teachers.
UserClasses matches many users to many class names.
TestClasses matches many tests to many class names.
Each test in Tests can have multiple Results - one per question per student.

The query returns a list of tests, using subqueries to find:

UnmarkedCount: How many unmarked results exist for this test, where the intersection of the following is not empty:

The classes of the student of this result
The test's classes
The teacher's classes

AnyResults: Are there any results for this test?
Classes: As a comma-separated list, which of the teacher's classes are assigned to this test?

Note that if we remove the condition where three queries are intersected, the execution time is reduced to 150ms. However, this logic is required.

How could this be improved?

Further Details:

Query Execution Plan

This is an extract from the query execution plan, where the heavy lifting seems to occur. I can't see anywhere suggesting indexes.

Business logic

The procedure returns a list of all tests at a given school. For each test, it calculates:

UnmarkedCount: How many results are not yet marked for students in classes which are both allocated to this test and taught by the current user?
Classes: Which of the classes allocated to this test does the current user teach?


texts:
I have built a simple finite state machine that models an even simpler fictitious bank account system.

Any given account can be in one of three states at any time: Open, Closed, or Held.

I have a few different methods that transition from one state to another:

reopen: closed -> open
close : open / held -> closed
place_hold  : open -> held
remove_hold : held -> open

I have used an ES6 class and prototypes to implements this. three different objects, each with its own methods, are set to be the __proto__ of any given BankAccount object.

The problem with this is that changing the __proto__ of an object removes its ability to call its class's methods, which is a problem.

Here is a stripped down version of my code:

const open ={stateName:"Open",
  close: function(){
    this.changeState(closed);
  },
  reopen: function(){
    return;
  },
  place_hold: function(){
    this.changeState(held);
  },
  remove_hold: function(){
    return;
  }
}

const held ={stateName:"Held",
  close: function(){
    this.changeState(closed);
  },
  reopen: function(){
    return;
  },
  place_hold: function(){
    return;
  },
  remove_hold: function(){
    this.changeState(open);
  }
}

const closed ={stateName:"Closed",
  close: function(){
    return;
  },
  reopen: function(){
    this.changeState(open);
  },
  place_hold: function(){
    return;
  },
  remove_hold: function(){
    return;
  }
}

class BankAccount {
  constructor() {
    this.balance = 0;
    this.__proto__ = open;
    this.changeState = state=>this.__proto__ = state;
  }
  otherStuff(){
    // this cannot be called...
  }
}

What would be a more proper way to do this, keeping our accounts able to access the class's methods, as well as the syntax used to access the methods implemented through the state machine?


texts: Designing a binary tree structure from scratch in C

texts:
I'm a beginner and self learning programming students. While learning binary tree data types, for the sake of understanding graph theory and other interesting programming problems, I've writen the below implementation. Would you please suggest if there's anything wrong or either this can be improved.

It may seem reinventing the wheel, as there's a nice STL in C++, but I do implement data structure and algos from scratch for the sake of a better understanding and visualization for me

Here's my code, and thanks in advance

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

typedef struct tree {
      int value;

      struct tree *left_child;
      struct tree *right_child;
} bin_tree;

void create_tree(int value, bin_tree **root);
void print_tree(bin_tree *root);
void free_mem(bin_tree *root);

int main() {
    bin_tree *root;

    root = (bin_tree *) malloc (sizeof(bin_tree));
    root = NULL;

    int val;
    while (scanf("%d", &val) != EOF) {
           create_tree(val, &root);
    }

    printf("root : %d\n", root->value);
    print_tree(root);
    free_mem(root);
    //printf("root: %d\n", root->value);
    return 0;
   }

void create_tree(int val, bin_tree **root) {
     if (*root == NULL) {
        bin_tree *cache = (bin_tree *) malloc(sizeof(bin_tree));
        cache->value = val;
        cache->left_child = NULL;
        cache->right_child = NULL;
        *root = cache;
     }
    /*this tree is built avoiding duplicates*/
   else if(val < (*root)->value){ create_tree(val, &(*root)->left_child);}
   else if(val > (*root)->value){ create_tree(val, &(*root)->right_child);}
  }

  void print_tree(bin_tree *root) {
       if (root != NULL) {
           print_tree(root->left_child);
           print_tree(root->right_child);
           printf("%d ", root->value);
         }
       }

   void free_mem(bin_tree *root) {
        if (root) {
           free_mem(root->left_child);
           free_mem(root->right_child);
           free(root);
   }
 }


texts: Graceful shutdown of applications/servers

texts:
I am trying to find out if there is any difference between two implementations that currently do the same thing - gracefully shutdown applications/servers, for example, when Ctrl+C is hit. Both work fine and are based on the documentation.

What a friend of mine says, is that Example 2 handles shutdown at the application level which shuts down all contexts throughout the application. However, Example 1 does it at the HTTP server level which doesn't necessarily shut down all contexts throughout the application. Since I am a beginner I cannot argue back and need your input on this, please.

Example 1

The signals are handled in the http.go file so the whole graceful shutdown has been handled in a single file.

cmd/app/main.go

package main

import (
    "context"
    "internal/http"
    "os"
    "os/signal"
    "syscall"
)

func main() {
    // Bootstrap config, logger, etc

    http.Start()
}

internal/http/server.go

package http

import (
    "context"
    "github.com/prometheus/common/log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func Start() {
    log.Infof("starting HTTP server")

    srv := &http.Server{Addr: ":8080", Handler: nil}

    idle := make(chan struct{})

    go shutdown(srv, idle)

    if err := srv.ListenAndServe(); err != http.ErrServerClosed {
        log.Fatalf("failed to start/close HTTP server [%v]", err)
    }

    <-idle

    log.Info("gracefully shutdown HTTP server")
}

func shutdown(srv *http.Server, idle chan<- struct{}) {
    sig := make(chan os.Signal, 1)

    signal.Notify(sig, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)

    <-sig

    ctx, cancel := context.WithTimeout(context.Background(), time.Duration(10)*time.Second)
    defer cancel()

    if err := srv.Shutdown(ctx); err != nil {
        log.Fatalf("shutdown HTTP server by interrupting idle connections [%v]", err)
    }

    close(idle)
}

Example 2

The signals are handled in the application's main.go file so the whole graceful shutdown has been split within two files. The only addition is this example uses the WithCancel context.

cmd/app/main.go

package main

import (
    "context"
    "internal/http"
    "os"
    "os/signal"
    "syscall"
)

func main() {
    // Bootstrap config, logger, etc

    backgroundCtx := context.Background()
    withCancelCtx, cancel := context.WithCancel(backgroundCtx)
    go shutdown(cancel)

    http.Start(withCancelCtx)
}

func shutdown(cancel context.CancelFunc) {
    sig := make(chan os.Signal, 1)

    signal.Notify(sig, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)

    <-sig

    cancel()
}

internal/http/server.go

package http

import (
    "context"
    "github.com/prometheus/common/log"
    "net/http"
    "time"
)

func Start(ctx context.Context) {
    log.Infof("starting HTTP server")

    srv := &http.Server{Addr: ":8080", Handler: nil}

    idle := make(chan struct{})

    go shutdown(ctx, srv, idle)

    if err := srv.ListenAndServe(); err != http.ErrServerClosed {
        log.Fatalf("failed to start/close HTTP server [%v]", err)
    }

    <-idle

    log.Info("gracefully shutdown HTTP server")
}

func shutdown(ctx context.Context, srv *http.Server, idle chan struct{}) {
    <-ctx.Done()

    ctx, cancel := context.WithTimeout(context.Background(), time.Duration(10)*time.Second)
    defer cancel()

    if err := srv.Shutdown(ctx); err != nil {
        log.Fatalf("shutdown HTTP server by interrupting idle connections [%v]", err)
    }

    close(idle)
}


texts:
This is the Wiggle Subsequence problem from leetcode.com:

  A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.

  For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.

  Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.

The solution is inspired by an \$O(n\log n)\$ answer to How to determine the longest increasing subsequence using dynamic programming?

class Solution(object):
    def wiggleMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums or len(nums) == 1:
            return len(nums)
        current_num, prev_num = nums[0], nums[0]
        count, trend = 0, None
        for current_num in nums:
            if not trend:
                if current_num > prev_num:
                    trend = "down_to_up"
                    count += 2
                elif current_num < prev_num:
                    trend = "up_to_down"
                    count += 2
            elif trend == "down_to_up":
                if current_num < prev_num:
                    count += 1
                    trend = "up_to_down"
            elif trend == "up_to_down":
                if current_num > prev_num:
                    prev_num = current_num
                    count += 1
                    trend = "down_to_up"
            prev_num = current_num
        if trend == None:
            count = 1
        return count


texts: Selecting a table with multiple ID on MySQL using PHP PDO

texts:
I have made a MySQL script to query a table with a set of id using an IN clause and after some reading I found out that there are security issues with it like prone to SQL injections and the likes.

Are there other ways to write this code with a more secure way? Although I'm using PDO, is that really enough?

 public function GetAllCustomerFilter($search, $cat_id)
 {
   $stmt = $this->db->prepare("SELECT * from users_cards WHERE cat_id IN ($cat_id) AND username LIKE :search ORDER BY id DESC LIMIT 60";
   $stmt->bindParam(":search", $search);
     if($stmt->execute()) {
       $products =  $stmt->fetchAll(PDO::FETCH_ASSOC);
     }
 }

Data is received from an Ajax:

    loadProductsListPerCat = function(form,data_serve) {

    var data_fed = new Array();
    $.each(data_serve, function(i,obj)
    {
        data_fed[i] = obj.cat_id;
    });
    var raw = data_fed.join();
    var encoded = encodeURIComponent(raw);
    var formData =  "data_serve="+encoded+"&"+ $(form).serialize();
    var requestURL = 'searchUsers';
    console.log(formData);
    $.ajax({
        url: requestURL,
        data: formData,
        crossDomain: true,
        dataType: 'json',
        cached: false,
        async: true,
        success: function(data) {
            console.log(data);

        },
        complete: function() {
            if(isAppend) {
                $('.btn-toggle-load-more-users').attr('disabled', false);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {

        }
    });
};

The variable data_serve is taken by another jQuery function on which it counts input elements that has data-on set to true:

var PCatVal = (function(){
    var cats = new Array();

    $("#main_cat").find(".option_").each(function(index) {
        $(this).removeClass("option_");
        $(this).addClass("ctrls option_"+index);

        $(".option_"+index).on("click", function(e){
            var opt = $(this).data('parentname');
            var opt_id = $(this).val();
            var data_serve = [];
            //array check if exists
            var idx = $.inArray(opt_id, cats);
                if (idx == -1) {
                   cats.push(opt_id);
                } else {
                    cats.splice(idx, 1);
                }
           //loop the array so to encode to a json format
            $.each(cats, function(i,obj){
              data_serve.push({"cat_id": obj});
            });
            //Switch for the category buttons
            var swtch_var = $(this).attr('data-on');

                if(swtch_var == 0)
                {
                  swtch_var = 1;
                }
                else
                {
                  swtch_var = 0;
                }
                $(this).attr('data-on',swtch_var);

loadUsers($('#frmSearchUsers'),'',data_serve);

           e.preventDefault();
        });
    });
});

This is how the $_GET parameters are received:

    public function searchUser()
    {
     $cat_id = (isset($_GET['data_serve']) && !empty($_GET['data_serve'])) ? $_GET['data_serve'] : null;
$search_filter = (isset($_GET['search_filter']) && !empty($_GET['search_filter'])) ? $_GET['search_filter'] : null;

     $products = $this->model->GetAllCustomerFilter($search_filter, $cat_id);
    return $products;
    }


texts: C++ code that convolves a data file for smoothing random data curves of microcanonical ensemble graphs

texts:
I am new to this, I have a convolution program that takes in a data file, convolves it and outputs another file. I am attaching the code here.

#include<bits/stdc++.h>
using namespace std

void convolute()
{
    ifstream fin;
    ofstream fout;

    int count = 0;
    double a=0,b=0;

    string input_file_string = "maxclus_500000node_3M_5000ens_666.dat";

    string output_file_string = "1convolute_"+input_file_string;

    fin.open(input_file_string.c_str());

    while(fin) //to know the size of array to initialize
    {
        fin>>a>>b;
        count++;

    }

    fin.close();

    double* c = NULL;
    c = new double[count+1];
    double* d = NULL;
    d = new double[count+1];

    for(int i=0;i<count+1;i++)
    {
        c[i] = 0;
        d[i] = 0;
    }

    fin.open(input_file_string.c_str());

    int n = 1;

    while(fin) //takes in data
    {
        fin>>a>>b;
        c[n] = a;
        d[n] = b;
        n++;
    }

    fin.close();

    double* binom = NULL;
    binom = new double[count];

    double* summ = NULL;
    summ = new double[count+1];

    for(int i=0;i<count+1;i++) summ[i] = 0;

    for(int i=0;i<count;i++) binom[i] = 0;

    //here the main convolution of data takes place
    for(int j=1;j<count;++j)
    {
        double prob = j*1.0/(count-1);
        binom[j] = 1;

        for(int i=j+1;i<count;++i)
        binom[i] = binom[i-1]*((count-1)-i+1)*1.0/i*prob/(1-prob);

        for(int i=j-1;i>=0;--i)
        binom[i] = binom[i+1]*(i+1)*1.0/((count-1)-i)*(1-prob)/prob;

        double sum = 0;

        for(int i=0;i<count;++i) sum += binom[i];
        for(int i=0;i<count;++i) binom[i] /= sum;

        sum = 0;

        for(int i=1;i<count;++i) sum += d[i]*binom[i];

        summ[j] = sum;

        if(j%1000==0)// just to make the process faster and check progress
        cout<<count-1<<'\t'<<j<<endl;

    }

    cout<<"writing to file "<<endl;

    fout.open(output_file_string.c_str());

    for(int i=1;i<count;i++) fout<<c[i]<<'\t'<<summ[i]<<endl;

    fout.close();

    delete [] c;
    c = NULL;
    delete [] d;
    d = NULL;

    delete [] binom;
    binom = NULL;

    delete [] summ;
    summ = NULL;

}

int main()
{
     convolute();

     return 0;
}

The main convolution takes place inside the 'j' loop, i have marked it inside the code, the data file it handles, the smallest one is with 1499994 points (all 'double' points, 2columns), it takes over 15++ hours to finish the whole program, badly in need of help to optimize it, so that it still does the same thing, but wayyyyyy faster!
p.s. i am also using gcc optimization flags, -Ofast -march=native -funroll-loops etc but still no improvement.


texts: bash script at scale for kubernetes kubectl operations

texts:
I have my below prototyped script and it runs fine but I need to scale it out at large. So, wanted to get feedback if my script can be improved in terms of performance and if there are any non standard stuff am doing in it.

What is does: Script is to delete all the pods under defined namespaces and then also from kube-system namespace only certain pods. It also gives user 10sec to chose to cancel. Operation.

I am going to merge this to production but I want to assure am atleast in good shape to do coz there will be 1000s of pods in production. Am new to coding, if bash is best choice, please suggest how to proceed with it.

#!/bin/bash

TT_NAMESPACES=(ambassador
               argo-workflow-controller
               webhook
              )

#Pulling teamstest pods under teamstest service name namespace
printf "Deleting pods for teamstest Namespaces: %s\n" "${TT_NAMESPACES[@]}"
for nmspc in ${TT_NAMESPACES[@]}
do
  printf "Terminate Jenkins Job in: %d seconds to cancel this operation\n" "10"
  sleep 10
  printf "Deleting PODS for Namespace: %s\n" "$nmspc"
  kubectl -n $nmspc delete --all pods --force --grace-period 0
  printf '\n'
done

#Pulling teamstest pods under Kube-system namespace
TT_SERVICES_KS_NMSPC=(local-volume-provisioner
                      registry-creds
                      tiller
                      )
printf "Deleting pods for teamstest services in kube-system Namespace: %s\n" "${TT_SERVICES_KS_NMSPC[@]}"
for ml_service_pod in ${TT_SERVICES_KS_NMSPC[@]}
do
  printf "Deleting teamstest PODS for %s in Kube-System Namespace\n" "$ml_service_pod"
  printf "Terminate Jenkins Job in: %d seconds to cancel this operation\n" "10"
  sleep 10
  kubectl -n kube-system get pods | grep $ml_service_pod | xargs -l1 -- sh -c 'kubectl -n kube-system delete pod $1 --force --grace-period 0' --
  printf '\n'
done


texts:
I am currently reading Michael Kerrisk's book, The Linux Programming Interface. This is one of the exercises from the end of chapter 4 (I'm working in Rust, not C).

A Rust implementation of the tee program on UNIX systems. According to it's man page

  The tee utility copies standard input to standard output, making a copy in zero or more files.  The output is unbuffered.

So running echo "foo" | tee will print "foo" to the terminal.
running echo "foo" | tee myfile will print "foo" to the terminal and also create the file myfile with the contents "foo".

It's a small example but I'd love feedback on whether this is idiomatic Rust code and whether the efficiency could be improved.

use std::env;
use std::io::{self, Read};
use std::io::prelude::Write;
use std::error::Error;
use std::fs::File;

fn main() {
    let fname = match env::args().nth(1) {
        Some(name) => name,
        None => String::from("/dev/null"),
    };

    let mut outfile = match File::create(&fname) {
        Ok(file) => file,
        Err(why) => panic!("{}", why.description()),
    };

    loop {
        let mut line = String::new();
        match io::stdin().read_to_string(&mut line) {
            Ok(_) => {}
            Err(_) => std::process::exit(0),
        }

        if line.is_empty() {
            std::process::exit(0);
        }

        println!("{}", &line);

        let _ = outfile.write(line.as_bytes());
    }
}


texts:
I'm using numpy to write the "back substitution" method for solving linear system where "A" is a nonsingular upper triangular matrix.

import numpy as np

def upperTriSol(A, b):
    n = np.size(b)
    x = np.zeros_like(b)

    x[-1] = 1. / A[-1, -1] * b[-1]
    for i in xrange(n-2, -1, -1):
        x[i] = 1. / A[i, i] * (b[i] - np.sum(A[i, i+1:] * x[i+1:]))

    return x

I know that "for loops" are slow, so I wonder if there is any way to avoid them in this case? If not, is there a "correct" way to write efficient "for loops" in numpy?


texts:
Here's the situation. I'm writing a simple game and I had two main actors: GameController and GridView.

GridView is a UIView subclass displaying a grid with which the user interacts. It defines its custom delegate protocol (GridViewDelegate) for handling callbacks such as gridView:didSelectTile and others.
GameController is the game controller (duh!) which instantiate a GridView and set itself as a delegate, therefore implementing the GridViewDelegate protocol.

So far so good, then I decided to add HUD components on top of the grid (a score, a timer and other stuff). The most reasonable choice seemed to wrap such HUD components along with the grid into a new UIView subclass called GameBoard.

And here comes the design issue: I need the controller to talk to the GridView and I think there's two reasonable options here.

Expose a gridView property and do something like

[self.gameBoard.gridView doStuff];

Forward the invocation made to GameBoard directly to GridView overriding the forwardInvocation: method of GameBoard

The first options looks like the most convenient, but I cannot get myself into liking it, due to the Law of Demeter.

So I decided to go for the second approach and do something like

// The GameBoard serves a proxy between the GameContoller and the GridView
- (void)forwardInvocation:(NSInvocation *)anInvocation {
    if ([self.gridView respondsToSelector:anInvocation.selector]) {
        [anInvocation invokeWithTarget:self.gridView];
    } else {
        [super forwardInvocation:anInvocation];
    }
}

// This method is necessary for the above forwardInvocation to work
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    NSMethodSignature * signature = [super methodSignatureForSelector:aSelector];
    if (!signature) {
        signature = [self.gridView methodSignatureForSelector:aSelector];
    }
    return signature;
}

It works as expected, but I'd like to have a second opinion on my design choice.

I generally tend to avoid overusing of the dynamic features of Objective-C, but it looked like an elegant way to achieve my result fulfilling the Law of Demeter.


texts:
I've written a function to get the smallest date from an date[ ] and check for null.
If null == infinity

    /**
     * @param DateTimeInterface|null ...$dates
     * @return DateTime|null
     */
    public static function minDateTime(?DateTimeInterface ...$dates)
    {
        $dateList = [];
        $dates = array_filter($dates);
        if (empty($dates)) {
            // all values where null
            return null;
        }

        foreach ($dates as $date) {
            $dateList[] = $date->getTimestamp();
        }

        return (new DateTime())->setTimeStamp(min($dateList));
    }

Its working but could this be written smaller or with more comments, so that external coworkers can read this?


texts: Implementation of OOP for retrieving list of objects from database

texts:
If I have a Person class that outlines the properties of a person and one of People that just contains a List<Person> like so:

public class Person
{
    public Person(){}
    public int personID {get;set;}
    public string name {get;set;}
    public string address {get;set;}
}

public class People
{
    public People(){}

    public List<Person> peoples {get;set;}

    public List<Person> getPeople()
    {
        List<Person> p = new List<Person>();
        //create database connection
        //open datareader

        Person onePerson = new Person();
        //write data to eahc property type and add data to list

        p.Add(onePerson);
        return p;
    }
}

To call the database method that gets the people from the database I could do this:

static void main(string[] args)
{
    People p = new People();
    p.getPeople();
}

Is this how I would do this in terms of OOP?

I'm just beginning to use these techniques in my coding as usually I would remove the getPeople() method from the People class and do this in main():

static void main(string[] args)
{
    List<Person> people = getPeople();
}

private static List<Person> getPeople()
{
    List<Person> p = new List<Person>();
    //create database connection
    //open datareader
    //load data into list

    Person onePerson = new Person();

    p.Add(onePerson);
    return p;
}


texts:
I would much appreciate your advice on this design I am going to implement. I am relatively new to object programming and I am not so sure about the delegate pattern.

I need to provide the implementation of a class that implements several interfaces of different nature. As the class would be huge I am thinking on using the delegate pattern to implement the code for each interface in a separate class. Simplifying the code a bit it goes like this:

The interfaces I have:

public interface DoorControlIF {
    public void openDoor(int id);
    //some more door operations
}

public interface DoorStatusListenerIF {
    public void onDoorOpened(int id);
}

public interface DoorAlarmListenerIF {
    public void onDoorAlarm(int id, String alarmType);
}

public interface DoorConnectionIF {
    public void connectToDoor(int id);
    public void disconnectDoor(int id);
}

public interface DoorNotifierIF {
    public void addDoorStatusListener(DoorStatusListenerIF listener);
    public void addDoorAlarmListener(DoorAlarmListenerIF listener);
}

Then the Manager class would be like:

public class DoorManager implements DoorControlIF,  DoorConnectionIF,  DoorNotifierIF{

SocketController socketController;
DoorController doorController;
DoorNotifier doorNotifier;

public void init() {
    socketController = new SocketController();
    doorController = new DoorController();
    doorController.setSocketController(socketController);
    doorNotifier = new DoorNotifier();
    doorNotifier.setSocketController(socketController);
}

public void connectToDoor(int id) { socketController.open(id); }
public void disconnectDoor(int id) { socketController.disconnect(id); }
public void openDoor(int id) { doorController.openDoor(id); }
public void addDoorStatusListener(DoorStatusListenerIF listener) { doorNotifier.addDoorStatusListener(listener); }
public void addAlarmStatusListener(DoorAlarmListenerIF listener) { doorNotifier.addDoorAlarmListener(listener); }

Then we would have all the delegate classes implement each one of  them a specific interface:

public SocketController implements DoorConnectionIF{}
public DoorController implements DoorControlIerF{}
public DoorNotifier implements DoorNotifierIF{}

Particularly I am not so sure if it is right or not having each delegate class implementing again the same interface as the the Manager class. Then there's this forwarding of listeners that are added to the Manager but inside my class I add to my specific notifier. How about passing the SocketController to each of the delegates?


texts:
I made the following code. It's a simple animation of 'raindrops' falling and splattering once they reach the ground. The images I use can be found here: https://imgur.com/a/VYV07ef

import pygame, sys
from pygame import locals
import random
import itertools

def listenToQuit():
    for event in pygame.event.get():
        if event.type == locals.QUIT:
            pygame.quit()
            sys.exit()

def makeNewDrop(display, drops):
    # there isa 15% chance we'll make a new drop, each frame
    x = display.get_width() * random.random() # a random xpostion
    return RainDrop(x, display, drops)

class RainDrop(pygame.sprite.Sprite):
    img = pygame.image.load('assests/rain_drop.png')

    def __init__(self, x, display, group):
        # call the super constructor, and pass in the
        # group you've created and it is automatically added to the group every
        # time you create an instance of this class
        pygame.sprite.Sprite.__init__(self, group)
        self.y = 0
        self.x = x
        self.fall_step = 5
        self.display = display
        self.die = False
        self. animation = iter([
            pygame.image.load('assests/splatter_1.png'),
            pygame.image.load('assests/splatter_2.png'),
            pygame.image.load('assests/splatter_3.png'),
            pygame.image.load('assests/splatter_4.png')
        ])

    def update(self):
        self.checkIfShouldDie()
        self.fall()
        if self.die:
            try:
                self.img = next(self.animation)
            except StopIteration:
                self.kill()

        self.display.blit(self.img, (self.x,self.y))

    def fall(self):
        self.y = self.y + self.fall_step

    def checkIfShouldDie(self):
        if self.img.get_rect().bottom + self.y >= self.display.get_height():
            self.die = True
            self.y = self.display.get_height() - self.img.get_rect().bottom - 5

if __name__ == '__main__':
    pygame.init()
    drops = pygame.sprite.Group()
    cooldown = 0

    fps = 30
    clock = pygame.time.Clock()

    main_display = pygame.display.set_mode((400,400),0,32)
    pygame.display.set_caption("rain!")

    while True:
        main_display.fill((255,255,255))

        if random.random() >= 0.85 and cooldown == 0:
            # a 15% change we'll make a new drop, each frame
            # assuming we didn't make a drop in the last few frames
            drop = makeNewDrop(main_display, drops) # automatically added to the drops group
            cooldown = cooldown + 5

        drops.update()

        # reduce cooldown
        cooldown = 0 if cooldown <= 0 else cooldown - 1
        listenToQuit()
        pygame.display.update()
        clock.tick(30)

How can this code be improved? Specifically the part where I iterator over animations and catch the StopIteration error seems very hacky to me.


texts: Synchronous and asynchronous methods in a client library

texts:
I am working on a library in which I need to make synchronous and asynchronous methods in my client library.

My library does this:

The customer will use our library and they will call it by passing user_id. We will then construct a URL by using that userId and make an HTTP client call to that URL. We will then get a JSON string back after hitting the URL. And after we get the response back as a JSON string, then we will send that JSON String back to our customer as it is.

Now I need to have synchronous and asynchronous methods. Some customer will call the executeSynchronous method to get the same feature and some customer will call our executeAsynchronous method and with the executeAsynchronous method, they will call future.get in there code itself.

Interface:

public interface Client {

    // for synchronous
    public String executeSynchronous(final String userId);

    // for asynchronous
    public Future<String> executeAsynchronous(final String userId);
}

And then I have SmartClient which implements the Client interface:

public class SmartClient implements Client {

    private RestTemplate restTemplate = new RestTemplate();
    private ExecutorService service = Executors.newFixedThreadPool(5);

    // for synchronous call
    @Override
    public String executeSynchronous(String userId) {

        String response = null;

        try {
            Future<String> handle = executeAsynchronous(userId);
            response = handle.get(500, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

        return response;
    }

    //for asynchronous call
    @Override
    public Future<String> executeAsynchronous(String userId) {
        Future<String> future = null;

        try {
            Task task = new Task(userId, restTemplate);
            future = executor.submit(task);
        } catch (Exception ex) {
            e.printStackTrace();
        }

        return future;
    }
}

This simple class will perform the actual task:

class Task implements Callable<String> {

    private final String userId;
    private RestTemplate restTemplate;

    public Task(String userId, RestTemplate restTemplate) {
        this.userId = userId;
        this.restTemplate = restTemplate;
    }

    public String call() throws Exception {

        String url = createURL(userId);

        // make a HTTP call to the URL
        String jsonResponse = restTemplate.exchange(url, HttpMethod.GET, null, String.class);

        return jsonResponse;
    }

    // create a URL
    private String createURL(String userId) {
        String generateURL = somecode;

        return generateURL;
    }
}

Is this the correct and efficient way of solving this problem? Can we generalize my interface?
How about the exception handling?

I need to have both synchronous and asynchronous methods so that the customer can call any method they like to call. Some customers might call the asynchronous method and then they will do future.get in their own library. Some can call the synchronous method, which internally can call the asynchronous method and do a future.get on it to return the response.


texts:
I have a working macro that finds a specific word and deletes the whole text. It finds the word "JOBSPECIALTYCODE" in the sheet, selects and deletes it, then moves to the next sheet. I just want to ask if there is any alternative way to make my macro work fast. I only use a record macro.

Sub aHaveProgess()
'
'
'
'

'Deleting Trash Text to make it clear

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "JOBSPECIALTYCODE"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = False
    .CorrectHangulEndings = False
    .HanjaPhoneticHangul = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchWildcards = False
    .MatchFuzzy = False
End With

Do While Selection.Find.Execute
    Selection.SelectCell
    Selection.Delete Unit:=wdCharacter, Count:=1
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
Loop
End Sub


texts:
Wrote a function to calculate the square root.
Magic from: https://tour.golang.org/flowcontrol/8
The result is almost always the same as math.sqrt. Difference percentage
is always around 10%. All difference (if any) is almost always in magnitude e-10.
How can the function be more accurate? Does is even need to be more accurate?
import math
from random import randint

def sqrt(n):
    x = 1  # initial guess
    h1, h2 = 0.0, 0.0 # history
    while True:
        # if answer or if number reappears
        if x*x == n or x == h1 or x == h2:
            return x
        h2 = h1
        h1 = x
        x = x - ((x*x - n) / (2*x)) # magic

if __name__ == "__main__":

    error_count = 0
    repeat = 300
    for _ in range(repeat):
        number = randint(0, 10000000000000)
        result = sqrt(number)
        math_result = math.sqrt(number)
        error = abs(result - math_result)
        if error:
            error_count += 1
        print(number, result, math_result, error)

    print()
    print(f"Errors: {error_count}")
    print(f"Percentage: {error_count/repeat:%}")


texts: Creating a Tkinter window that generates seven numbers from 1 - 49 and sorts them

texts:
I would like to critical advice on my code:

#-----import modules-----#
from tkinter import *
from turtle import *
from random import sample , seed

#-----Setup-----#
win = Tk() # ...generates a window...
win.title("Lotto Number Generator")
#win.geometry("500x500")
win.resizable(False,False)

#-----Widget Declaration-----# ...With Labels and Buttons
Labl1 = Label(win , relief = 'groove' , width = 2)
Labl2 = Label(win , relief = 'groove' , width = 2)
Labl3 = Label(win , relief = 'groove' , width = 2)
Labl4 = Label(win , relief = 'groove' , width = 2)
Labl5 = Label(win , relief = 'groove' , width = 2)
Labl6 = Label(win , relief = 'groove' , width = 2)
LablX = Label(win , relief = 'groove' , width = 2) #This is a lucky number.
ResetBtn = Button(win , text = "Reset")
PickBtn = Button(win , text = "Pick My Lucky Numbers")

#-----Position Widgets-----#
Labl1.grid(row = 1 , column = 1 , padx = 10)
Labl2.grid(row = 1 , column = 2 , padx = 10)
Labl3.grid(row = 1 , column = 3 , padx = 10)
Labl4.grid(row = 1 , column = 4 , padx = 10)
Labl5.grid(row = 1 , column = 5 , padx = 10)
Labl6.grid(row = 1 , column = 6 , padx = 10)
LablX.grid(row = 1 , column = 7 , padx = 20)

ResetBtn.grid(row = 2 , column = 6 , columnspan = 2)
PickBtn.grid(row = 2 , column = 1 , columnspan = 5)

#-----Functions-----#
def reset(): ...That resets the labels...
    Labl1.configure(text='...')
    Labl2.configure(text='...')
    Labl3.configure(text='...')
    Labl4.configure(text='...')
    Labl5.configure(text='...')
    Labl6.configure(text='...')
    LablX.configure(text='...')
    PickBtn.configure(state = NORMAL)
    ResetBtn.configure(state = DISABLED)

def pick(): #...and can pick random numbers WITH a bonus number
    picks = sample(range(1,49) , 7)
    LablX.configure(text=picks[6])
    del picks[6]
    picks.sort()
    Labl1.configure(text=picks[0])
    Labl2.configure(text=picks[1])
    Labl3.configure(text=picks[2])
    Labl4.configure(text=picks[3])
    Labl5.configure(text=picks[4])
    Labl6.configure(text=picks[5])
    PickBtn.configure(state = DISABLED)
    ResetBtn.configure(state = NORMAL)

#-----Assign Functions-----#
ResetBtn.configure(command = reset)
PickBtn.configure(command = pick)

#-----Initialise-----#
reset()

win.mainloop()


texts: Builder pattern that forces all members to be initialized at compile-time

texts:
This java answer made me wonder whether it would be possible to implement the builder pattern in C++ in a way that checks at compile-time whether all necessary members of the constructed object are actually set before the object is constructed. This is what I came up with:

struct Foo {
    int x_;
    int y_;
    int z_;
};

template <bool x_set = 0, bool y_set = 0, bool z_set = 0>
struct FooBuilder {
    int x_, y_, z_;

    Foo build() {
        static_assert(x_set && y_set && z_set, "all members must be initialized before building a Foo!");
        return { x_, y_, z_};
    }

    FooBuilder<1,y_set,z_set> x(int val) {
        FooBuilder<1,y_set,z_set> result;
        result.x_ = val;
        result.y_ = y_;
        result.z_ = z_;
        return result;
    }

    FooBuilder<x_set,1,z_set> y(int val) {
        FooBuilder<x_set,1,z_set> result;
        result.x_ = val;
        result.y_ = y_;
        result.z_ = z_;
        return result;
    }

    FooBuilder<x_set,y_set,1> z(int val) {
        FooBuilder<x_set,y_set,1> result;
        // optional check to allow z to be set only once
        static_assert(!z_set, "z may not be initialized twice!");
        result.x_ = val;
        result.y_ = y_;
        result.z_ = z_;
        return result;
    }
};

int main() {
    FooBuilder<> b;
    auto f1 = b.x(1).y(2).z(3).build();
    auto f1a = b.z(3).y(2).x(1).build();
    auto f2 = b.x(1).y(2).build(); // fails with static assertion
    auto f3 = b.x(1).y(2).z(3).z(4).build(); // fails with static assertion
    auto partially_initialized_builder = b.x(1);
    auto f4 = partially_initialized_builder.build(); // fails...
    auto f5 = partially_initialized_builder.y(4).z(6).build(); // runs

    return 0;
}

With this approach, I like the fact that programming errors that result from forgotten arguments to the builder can be caught at compile-time. However, I'm not sure if it is too verbose, since the whole content of the builder has to be copied/moved in each setter method (even if the copies might be optimized away).

So my main questions are:

Would such a pattern actually be useful in practice?
Is there an elegant way of sharing the member variables of the Builder objects, despite the results of each setter call being of a different type? (For cheap-to-move types, I am thinking along the lines of a "data block"-like struct, that gets moved from this into the result.)
Any other downsides to this approach?

P.S.: Please disregard the lack of access control (x_ etc. should be private), this question is more about the high-level picture ;-)


texts: Find the nearest (small) number x where x can be represented by sum of cubes

texts:
I recently came across a problem where a number \$x\$ is given and I have to find \$y\$:

\$y < x > 1\$
\$y\$ can be expressed as \$a^3 + b^3\$ (more than one combination)

Example:

If 4105 is \$x\$ then 4104 is the answer, where 4104 can be expressed as \$16^3 + 2^3\$ and also \$15^3 + 9^3\$.

I am able to write a program in Objective-C, but I am sure that my method is not optimized and is not best.

I am posting this to find out

the best algorithms to solve this problem
Flaws in my way of solving

#import <Foundation/Foundation.h>

BOOL isPerfectCube(int cubeValue)
{
    float CalculatedCubeRoot = powf(cubeValue, 1.0/3.0);
    CalculatedCubeRoot = floorf(CalculatedCubeRoot * 100) / 100;
    return ((CalculatedCubeRoot - (int) CalculatedCubeRoot) == 0);
}

int cubeRoot(int value)
{
    return powf((float)value, 1.0/3.0);
}

int nearbyNumber(int numberUnderInvestigation)
{
    if(numberUnderInvestigation < 2)
    {
        return -1;
    }
    else
    {
        int firstCube = 1;
        int combination = 0;

        for(int i=2;firstCube<numberUnderInvestigation;i++)
        {
            firstCube = i*i*i;
            int nextCubeNumber = numberUnderInvestigation - firstCube;
            if(isPerfectCube(nextCubeNumber))
            {
                combination++;
            }
        }

        if(combination > 3)
        {
            return numberUnderInvestigation;
        }
        else
        {
            return nearbyNumber(numberUnderInvestigation - 1);
        }
    }
}

int main(int argc, const char * argv[])
{
    @autoreleasepool
    {
        int inputNumber = 4150;

        NSLog(@"%d",nearbyNumber(inputNumber));
    }

}


texts:
I need a method which will parse text to RichTextBlock-compatible XAML markup with clickable links.

Example:

Input:

"Hello, check new service for students! Check edusty.ru and http://edusty.ru/test?text1=abc&args=123 sites. Check edusty.ru/privacy.html to read privacy policy."

Output:

<Paragraph xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" TextAlignment="Left" FontSize="20"  FontWeight="Normal" FontStyle="Normal" FontStretch="Normal" >
     <Run Text="Hello, check new service for students! Check "/>
     <Hyperlink NavigateUri="http://edusty.ru">edusty.ru</Hyperlink>
     <Run Text=" and "/>
     <Hyperlink NavigateUri="http://edusty.ru/test?text1=abc&amp;args=123">http://edusty.ru/test?text1=abc&amp;args=123</Hyperlink>
     <Run Text=" sites. Check "/>
     <Hyperlink NavigateUri="http://edusty.ru/privacy.html">edusty.ru/privacy.html</Hyperlink>
     <Run Text=" to read privacy policy."></Run>
</Paragraph>

I wrote this method:

public static string ParseLinksToXaml(this string source)
        {
            var transformedText = Regex.Replace(source,
                @"((https?:\/\/)?(ftps?:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/\S*)?)",
                @"""/> <Hyperlink NavigateUri=""$1"">$1</Hyperlink> <Run Text=""", RegexOptions.IgnoreCase);
            transformedText = WebUtility.HtmlEncode(transformedText);
            var matches = Regex.Matches(transformedText, @"&quot;\/&gt;\s&lt;Hyperlink NavigateUri=&quot;.*?&quot;&gt;|&lt;\/Hyperlink&gt;\s&lt;Run Text=&quot;");
            foreach (var match in matches)
                transformedText = transformedText.Replace(match.ToString(), WebUtility.HtmlDecode(match.ToString()));

            matches = Regex.Matches(transformedText, @"NavigateUri=\""(.*?)"">");
            foreach (Match match in matches)
            {
                var link = match.Groups[1].ToString();
                link = link.Replace("&", "&amp;");
                link = link.Contains("://") ? link : "http://" + link;
                transformedText = transformedText.ReplaceFirst("\"" + match.Groups[1] + "\"", "\"" + link + "\"");
            }
            var xaml = @"<Paragraph xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" TextAlignment=""Left"" FontSize=""20""  FontWeight=""Normal"" FontStyle=""Normal"" FontStretch=""Normal"" >
                                    <Run Text=""" + transformedText + @"""></Run></Paragraph>";
            return xaml;
        }

It works, but the code really looks bad. Can anyone help rewrite/optimize this?


texts: Change Background Color of ASP:GridView Based On Text

texts:
I am using the OnRowDataBound() event to change the Row.BackColor based on the text.  Now my issue is, this is extremely slow.  I have roughly 100 rows in the ASP:Gridview and only need to evaluate the first row or index[0].  What optimization techniques do you guru's have on how to speed this process up?

protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TableCell cell = e.Row.Cells[1];
        string question = cell.Text;

        if (question == "View below to get data:" | question == "Check the state information below:" | question == "Check the state information below:")
        {
            e.Row.BackColor = System.Drawing.Color.Gray;
        }
    }
}


texts: Dual rewrite rules (WWW prefix and HTTPS)

texts:
I want to configure my website to force a www. prefix on the name, and the HTTPS protocol.

<system.webServer>
  <rewrite xdt:Transform="Insert">
    <rules>
      <clear/>
      <rule name="Add WWW prefix" enabled="true">
        <match url="(.*)" ignoreCase="true" />
        <conditions>
          <add input="{HTTP_HOST}" negate="true" pattern="^www\.(.*)$" /> <!--pattern="^www\.([.a-zA-Z0-9]+)$"/>-->
        </conditions>
        <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" appendQueryString="true" redirectType="Permanent"/>
      </rule>
      <rule name="Redirect to HTTPS" enabled="true" stopProcessing="true">
        <match url="(.*)" ignoreCase="true" />
        <conditions>
          <add input="{HTTPS}" pattern="^OFF$" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
      </rule>-->
    </rules>
  </rewrite>
</system.webServer>

Considerations:

The first rule appears to be working fine.
The second rule is so far untested on the live site. (Still configuring SSL.)
Are there any performance considerations when applying two rules together like this? That is, must they both be applied on each request.


texts:
I have some data under an HTML format and would like to import it in R. However, it seems that type inference is much less sophisticated than what exists with functions such as read.table. I am using the following workaround, which consists in reading the data table once, write it as a csv and re-import it.

# import raw data as HTML
require(XML)
raw_data <- readHTMLTable(doc = ".\\data\\mydata",
                          header = T,
                          as.data.frame = T)
# clean format and import

write.table(x = raw_data, file = ".\\temp.csv", quote = TRUE)
clean_data <- read.table(".\\temp.csv")

removeDots <- function(x)
{
  x <- gsub(pattern = "NULL", replacement = "", x = x, fixed = T)
  gsub(pattern = ".", replacement = "", x = x, fixed = T)
}

colnames(clean_data) <- lapply(X = colnames(clean_data), FUN = removeDots)

Per example, the following data is imported as a table of factors:

    Jill
    Smith
    50

    Eve
    Jackson
    94

Is there any better option ?


texts:
The following is a personal attempt at implementing the Composite design pattern in Scala. Observation is abstract...

class CompositeObservation(obss: Observation*) extends Observation {
  val elements: MutableList[Observation] = new MutableList[Observation]()

  elements ++ obss

  def hasElement(o: Observation): Boolean = elements.contains(o);
}

hasElement fails to return if an element is contained in the composite. Questions:

Am I misinterpreting the ++ operator? The Observation*?
What is the most ideomatic way to implement this pattern in Scala?


texts: Merging an overlapping collection of intervals

texts:
I'm getting myself acquainted with Rust and decided to implement the classical overlapping intervals problem.

Here is a statement of the problem:

  Given a collection of intervals, write a function that merges all
  overlapping intervals and prints them out.

  For example, given [1, 3], [2, 6], [8, 10], and [7, 11], the function
  should print [1, 6], [7, 11]. Or given [5, 12], and [8, 10] the
  function should print [5, 12].

  You can assume that the first element of each interval is always less
  or equal than the second element of the interval.

This is my implementation:

use std::cmp;
use std::fmt::Write;

//--------------- Range ---------------//

#[derive(Copy, Clone)]
struct Range{
    start: i32,
    end: i32,
}

fn new_range(start: i32, end: i32)->Range{
    Range{
        start: start,
        end: end,
    }
}

impl Range{
    fn overlaps(&self,other: &Range) -> bool{
        (other.start >= self.start && other.start <= self.end)
        || (other.end >= self.start && other.end <= self.end)
    }

    fn merge(&mut self, other: &Range){
        self.start = cmp::min(self.start, other.start);
        self.end = cmp::max(self.end, other.end);
    }

    fn to_string(&self)->String{
        format!("[{},{}]",self.start,self.end)
    }
}

//--------------- RangeStack ----------------//

struct RangeStack{
    ranges: Vec<Range>,
}

fn range_stack_with_ranges(ranges : &Vec<Range>)->RangeStack{
    let mut raw_ranges = ranges.to_vec();
    raw_ranges.sort_by(|a,b| a.start.cmp(&b.start));

    let mut range_stack = RangeStack{
        ranges: Vec::new(),
    };

    for range in raw_ranges.iter(){
        range_stack.add(range);
    }

    range_stack
}

impl RangeStack{

    //private
    fn add(&mut self,range :&Range){
        if self.ranges.len() == 0 {
            self.ranges.push(range.clone());
        }else if self.ranges.last_mut().unwrap().overlaps(range){
                self.ranges.last_mut().unwrap().merge(range);
        }else{
                self.ranges.push(range.clone());
        }
    }

    fn to_string(&self) -> String {

        let mut res = String::new();
        for range in self.ranges.iter() {
            write!(&mut res, "{}", range.to_string()).unwrap();
        }

        res
    }
}

//--------------- Main ---------------//

fn main() {
    let v = vec![
        new_range(3,6),
        new_range(1,5),
        new_range(7,11),
        new_range(9,12),
        new_range(4,8),
    ];

    let rs = range_stack_with_ranges(&v);
    print!("Result: {}\n",rs.to_string());
}

I would appreciate it if someone could review the Rust code and let me know if there is anything that is not idiomatic. In particular, I'm not sure if my usage of mut would be considered ideal.


texts: Revealing module pattern modified for more class-like behavior

texts:
I've recently been learning about the revealing module pattern, and it seems like a really good way to structure code in many cases. However, I find myself wanting to use it like a class, so I'm trying to modify it to behave in the following ways:

Instances get created from the module (doesn't just immediately return its own object)
The module can take arguments and use them like a constructor (I don't see this in many revealing module examples)
The module can be extended like a class; extending modules inherit its public properties/methods and can share arguments/parameters

I seem to have achieved this by using just a function expression instead of an IIFE, creating an instance of the parent within the extending module, and passing the extending module's arguments into the parent instance. Here is the full working pattern I've come up with:

var Module = function({text = 'no text given'} = {}) {
    var private = {};
    private.text = text;
    private.logText = function() {
        console.log(private.text);
    };

    var public = {};
    public.logText = private.logText;

    return public;
};

var Extended = function({extraText = 'no extra text given'} = {}) {
    var parent = Module(arguments[0]);
    // Note: I chose to use an object as a parameter in this snippet,
    // but you could also just use regular parameters and pass in
    // arguments instead of arguments[0]

    var private = {};
    private.extraText = extraText;
    private.alertText = function() {
        alert(private.extraText);
    }

    var public = {};
    public.logText = parent.logText;
    public.alertText = private.alertText;

    return public;
};

// TEST INSTANCES

var testModule = Module({ text: "I'm in the console." });
testModule.logText(); // "I'm in the console."

var testExt = Extended({ extraText: "I'm in an alert." });
testExt.logText(); // "no text given"
testExt.alertText(); // alerts "I'm in an alert."

var anotherExt = Extended({
  text: "I'm in the console.",
  extraText: "I'm in an alert."
});
anotherExt.logText(); // "I'm in the console."
anotherExt.alertText(); // alerts "I'm in an alert."

Now it basically behaves as a class like I was wanting - but I'm wondering what limitations/shortcomings there might be that I'm not seeing. Is the revealing module pattern ever used this way?


texts: N-Queens without recursion (but with one goto)

texts:
Compared to the recursive version e.g. on Rosetta, this is 5-10% faster and uses 50% less instructions (for N=12).
Only problem is the goto. Can it be avoided without using a function?
The two outer for-loops don't do much in terms of loop control. But this is how I could make it work.
Is there a more convincing non-recursive version? I searched quite a bit and most are recursive and/or longer.
/* N-Queens, non-recursive, with goto */
#include <stdio.h>
//const int N = 8;  //92 solutions
const int N = 12;   //14200 in 0.100 s

/* Print excluding last row, plus last col */
void pr_solution(int *bq, int col) {
    for (int i = 0; i < N - 1; i++)
        printf("%d:", bq[i]);
    printf("%d\n", col);
}
void init_board(int bq[], int v) {
    for (int i = 0; i < N; i++)
        bq[i] = v;
}
int main() {
    int bq[N];
    init_board(bq, -1);
    int row, col, rd, old;
    int cnt = 0;
    for (row = 0; row >= 0;) {

        for (col = bq[row];;) {
            NEXT_col:
            if (++col == N)
                bq[row--] = -1;
            else {
                for (rd = 1; rd <= row; rd++)
                    if ((old = bq[row-rd]) == col || old == col+rd || old == col-rd)
                        goto NEXT_col;
                if (row == N - 1) {
                    cnt++;
                    row--;
                    //pr_solution(bq, col);
                }
                else
                    bq[row++] = col;
            }
            break;
        }
    }
    printf("%d SOLUTIONS (%dx%d)\n", cnt, N, N);
    return 0;
}


texts: Algorithm to transform one word to another through valid words

texts:
I have been practicing backtracking and I wanted to know how I can improve my code. For eg, I don't want to use global. Also, I am not sure if my code will work for all the cases.

# Given two words of equal length that are in a dictionary, write a method to transform one word into another word by changing only
# one letter at a time.  The new word you get in each step must be in the
# dictionary.

# def transform(english_words, start, end):

# transform(english_words, 'damp', 'like')
# ['damp', 'lamp', 'limp', 'lime', 'like']
# ['damp', 'camp', 'came', 'lame', 'lime', 'like']

def is_diff_one(str1, str2):
    if len(str1) != len(str2):
        return False

    count = 0
    for i in range(0, len(str1)):
        if str1[i] != str2[i]:
            count = count + 1

    if count == 1:
        return True

    return False

potential_ans = []

def transform(english_words, start, end, count):
    global potential_ans
    if count == 0:
        count = count + 1
        potential_ans = [start]

    if start == end:
        print potential_ans
        return potential_ans

    for w in english_words:
        if is_diff_one(w, start) and w not in potential_ans:
            potential_ans.append(w)
            transform(english_words, w, end, count)
            potential_ans[:-1]

    return None

english_words = set(['damp', 'camp', 'came', 'lame', 'lime', 'like'])
transform(english_words, 'damp', 'lame', 0)


texts: Draw the table like 6³ = 3³ + 4³ + 5³ to 100³ = 35³ + 70³ + 85³

texts:
I want to draw the table like this:

6³ = 3³ + 4³ + 5³
9³ = 1³ + 6³ + 8³
12³ = 6³ + 8³ + 10³
18³ = 2³ + 12³ + 16³
18³ = 9³ + 12³ + 15³
19³ = 3³ + 10³ + 18³
20³ = 7³ + 14³ + 17³
.....
100³ = 35³ + 70³ + 85³

I've tried this:

$start = microtime(true);
funcC(100);
echo microtime(true) - $start;

function funcC($n){

    $tnum = 3;
    $s = '³';

    $testmax = $n-$tnum;
    $p3a = array();

    $numlist = array_fill(0, 10, array());

    for ($i = 0; $i <= $n; $i++) {
        $j = pow($i,3);
        $p3a[] = $j;
        $numlist[$j%10][$j] = $i;
    }

    for ($i = $tnum; $i <= $n; $i++) {
        $ipow = $p3a[$i];
        for ($j = 1; $j <= $i; $j++) {

            for ($k = $j+1; $k <= $testmax+2; $k++) {

                if($p3a[$j]+$p3a[$k] > $ipow){break;}

                $diff = $ipow - ($p3a[$j]+$p3a[$k]);
                $diff_t =  $diff%10;

                if(isset($numlist[$diff_t][$diff]) && $numlist[$diff_t][$diff]>$k ){

                    echo " $i$s  =  $j$s + $k$s + ".$numlist[$diff_t][$diff].$s.'<br>'.PHP_EOL;
                    break;
                }
            }
        }
    }
}

It is ok, but I want to know a faster way of doing this.

This code uses 0.59064292907715 as test code here.


texts: Implement versioning of a RESTful API with PHP/Slim and Apache

texts:
I want to create a RESTful API with Apache/PHP and the Slim Framework (3.x). The API should support URI-based versioning like <host>/rest/api/v1/<resource> and <host>/rest/api/latest/<resource>.

Overall I found a solution which works, but I not really happy with my solution and I'm want to known what can I make better. I'm a rookie/newbie about Slim. I'm looking for new ideas and how I can improve my knowledge about Slim.

Every new version should be a new project, which a own independent code base. The version dispatching should be done by the Apache server and no in the PHP/Slim code. I found some example which implements different versions of the API in on project by using the group-method. But I'm not very happy with this solution. I feel better to have independent projects for independent versions.

General improvements or comments?
Do you have a better/simpler solution?
Do you see problems in my solution?
Improvements for .htaccess / rewrite rules
Links to real implementations of a RESTful API with Slim
....

I'm looking forward for your answers and I'll be curious to see what's new.

The implementation of all version of the API are in the Apache htdoc folder with following structure

rest
 +--api
     +-v1
        +-.htaccess
        +-index.php
     +-v2
        +-.htaccess
        +-index.php
     +-.htaccess
     +-index.html

The implementation of the API are in the file index.php. Map calls like /rest/api/v1/books to my implementation I create in every version folder a .htaccess file which includes rules for the rewrite Apache module:

RewriteEngine On
RewriteRule ^ index.php [QSA,L]

In index.php I create some routes

$app->get('/books', function ...
$app->get('/books/{id}', function ...

Everything works fine if I use a explicit version in the URI (<host>/rest/api/v2/books). For convenience if I create an alias latest (/rest/api/latest/books), which redirect the alias-call to the latest version of the API version.

Therefore I create the file rest/api/.htaccess which rewrites the URI to an implementation:

RewriteEngine On
RewriteRule ^latest.*$ ./v2/index.php [QSA,L]

The rewrite rule works fine and the v2 implementation are called. But the routes don't match anymore. I found out that the original path is now part of the path.

/rest/api/v2/books -> /books
/rest/api/latest/books -> /rest/api/latest/books

If I modified the rules like this, it works - but I don't like to implement every rule twice.

$app->get('/rest/api/latest/books', function ...
$app->get('/rest/api/latest/books/{id}', function ...

Therefore I wrote a middleware function which trims /rest/api/latest from the path before the routes are matched.

$app->add(function (Request $request, Response $response, callable $next) {
    $uri = $request->getUri();
    $path = $uri->getPath();
    if (substr($path,0,16) == "/rest/api/latest") {
        $uri = $uri->withPath(substr($path,16));
        return $next($request->withUri($uri), $response);
    }
    return $next($request, $response);
});

Now I can use the same rules for both cases, explicit version call and implicit version call.


texts: IQueryable left outer join linq extension

texts:
I wanted to create an extension method to enable left outer joins in linq/lambda IQueryables, and I have come up with the following, but I am still not sure it's completely correct.

public static IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
    this IQueryable<TOuter> outer,
    IQueryable<TInner> inner,
    Expression<Func<TOuter, TKey>> outerKeySelector,
    Expression<Func<TInner, TKey>> innerKeySelector,
    Func<TOuter, TInner, TResult> resultSelector)
{
    return outer.GroupJoin(
        inner,
        outerKeySelector,
        innerKeySelector,
        (o, i) => new { outer = o, innerCollection = i })
    .SelectMany(
        a => a.innerCollection.DefaultIfEmpty(),
        (a, i)=>resultSelector(a.outer,i));
}

I am especially concerned with the resultSelector being a Func, not an Expression, but I cant call an Expression in the lambda on the last line. I assume it gets cast automatically, but it's only an assumption.

Is this correct? How can I improve this? Can it be optimized more?


texts:
I'm writing a sub-routine in AppleScript to get text from a file and insert that text in a list of lists forming a dictionary.

Text File:

a:b
c:d
e:f

Expected list:

{{"a", "b"}, {"c", "d"}, {"e", "f"}}

Here's my code:

on getDictionary(filePath)
    set dictionary to {}
    set dictionaryFile to paragraphs of (read POSIX file filePath)
    repeat with entry in dictionaryFile
        set AppleScript's text item delimiters to {":"}
        set delimitedEntry to every text item of entry
        copy delimitedEntry to the end of dictionary
    end repeat
    return dictionary
end getDictionary

I'm wondering if this is a good approach for my goal. It does produce the desired result.


texts:
Recently I've started learning ReactJS and I do not look forward to making one Page website so I learned about react-router and this is my way of doing to it.

App.js

import React, { Component } from "react";
import "babel-polyfill";
import Navbar from "./Components/MenuNavbar";
import Footer from "./Components/Bottom";
import Home from "./Components/Home";
import About from "./Components/About";
import Contact from "./Components/Contact";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Products from "./Components/Products";
import { CircleArrow as ScrollUpButton } from "react-scroll-up-button";
// import Topbar from "./Components/Topbar";

class App extends Component {
  render() {
    return (

        <Router>
          <React.Fragment>
            <Navbar />
            <Switch>
              <Route exact path="/" component={Home} />
              <Route exact path="/products" component={Products} />
              <Route exact path="/about" component={About} />
              <Route exact path="/contact" component={Contact} />
            </Switch>
            <ScrollUpButton />

          </React.Fragment>
        </Router>

    );
  }
}

export default App;

In my other Components, I wrap parent in a div as learned in some tutorials, like this:

render() {
    return (

        <ProductsHero />
        <ProductsCashew />
        <ProductsAlmonds />

    );
  }

Is this the best practice? If not how can I improve? Shall I wrap every child in React.Fragment instead of div? If so why?


texts: Parse an XML and retrieve zero or one attribute per level starting from a leaf

texts:
I need to extract from a large XML file some information:

0 or 1 attribute per tag
Trigger on a leaf element

So I wrote this Python code:

def ascend(element):
    parent = element.getparent()
    return [parent] + ascend(parent) if parent is not None else []

def parsexml(filename, tag, attrs):
    from lxml import etree
    for el in etree.ElementTree(file=filename).iter(tag):
        nodes = ascend(el)[::-1] + [el]
        yield [n.attrib[a] for n, a in zip(nodes,attrs) if a]

This snippet can be used as follow (with simplified data):

In [1]: xml = StringIO.StringIO("""
<data>
    <level1 a="1">
        <level2 b="1">
            <level3 c="1"/>
            <level3 c="2"/>
        </level2>
        <level2 b="2">
            <level3 c="3"/>
            <level3 c="4"/>
        </level2>
    </level1>
    <level1 a="2">
        <level2 b="3">
            <level3 c="5"/>
            <level3 c="6"/>
        </level2>
        <level2 b="4">
            <level3 c="7"/>
            <level3 c="8"/>
        </level2>
    </level1>
</data>""")

In [2]: list(parsexml(xml, 'level3', [None, 'a', None, 'c']))
Out[2]:
[['1', '1'],
 ['1', '2'],
 ['1', '3'],
 ['1', '4'],
 ['2', '5'],
 ['2', '6'],
 ['2', '7'],
 ['2', '8']]

My goal is to import the extracted data in Pandas:

ds = pd.DataFrame(data, columns=['level1', 'level3'])

Is my implementation correct or can I do better? I think the code is short and elegant, but I feel it spends most of its time looking for parents which can be ineffective (I didn't measured it and for my application it is still fast enough).


texts: Optional argument for which None is a valid value

texts:
I have the following function:

def item_by_index(iterable, index, default=Ellipsis):
    """Return the item of <iterable> with the given index.

    Can be used even if <iterable> is not indexable.

    If <default> is given, it is returned if the iterator is exhausted before
    the given index is reached."""

    iterable_slice = itertools.islice(iterable, index, None)
    if default is Ellipsis:
        return next(iterable_slice)
    return next(iterable_slice, default)

It should (and does) throw an exception if the default is not given and the iterator is exhausted too soon.  This is very similar to what the built-in function next does.

Usually, one would probably use None as default value to make an argument optional. In this case, however, None is a valid value for default and should be treated differently from no argument.  This is why I used Ellipsis as a default value.  It sort of feels like an abuse of the Ellipsis object, though.

Is there a better way of doing this or is Ellipsis a good tool for the job?


texts: Sort files in a given folders and provide as a list

texts:
I have two folders query and subject. The following function sorts alphabetically and provides the query and subject as a separate list. The file names are mixed of numbers and I found the sort function works perfectly well. Any comments to improve?

import os
import re

subject_path = "/Users/catuf/Desktop/subject_fastafiles/"
query_path = "/Users/catuf/Desktop/query_fastafiles"

def sorted_nicely(l):

    """ Sort the given iterable in the way that humans expect. https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ """
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
    return sorted(l, key = alphanum_key)

def subject_list_fastafiles():

    subject_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(subject_path) if os.path.isfile(os.path.join(subject_path, fastafile))])

    return subject_fastafiles

def query_list_fastafiles():

    query_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(query_path) if os.path.isfile(os.path.join(query_path, fastafile))])

    return query_fastafiles

def filter_files_ending_with_one(sorted_files):

    """ The function filters the files end with 1 """

    files_end_with_one = [name for name in subject_fastafiles if name[-1].isdigit() and not name[-2].isdigit() == 1]

    return files_end_with_one

subject_fastafiles = subject_list_fastafiles()

query_fastafiles = query_list_fastafiles()

subject_files_ending_with_one = filter_files_ending_with_one(subject_fastafiles)


texts:
I'm just getting into Clojure, and I wanted to make sure I am writing code the "Clojure way". The challenge I took on is Zeckendorf numbers (fairly trivial).
(defn fibs-until
  ([n]
    (vec (if (< n 3)
      (range 1 (inc n))
      (concat [1 2] (fibs-until n 1 2)))))
  ([n a b]
    (let [fib (+ a b)]
      (if (> fib n)
        []
        (cons fib (fibs-until n b fib))))))

(defn zeckendorf
  ([n]
    (if (= 0 n) "0" (zeckendorf n (reverse (fibs-until n)))))
  ([n fibs]
    (if (= fibs [])
      ""
      (let [head (first fibs) tail (rest fibs)]
        (if (or (> head n) (= 0 n))
          (str "0" (zeckendorf n tail))
          (str "1" (zeckendorf (- n head) tail)))))))

A few review questions I have:

Is there a more "Clojure way" to do this?
I noticed that I am repeating the same (overloading-esque) pattern of defining functions that have two arities, and calling out to the second in the first. Is there a better way to do this?
I wanted to use [[head & tail] fibs] rather than [head (first fibs) tail (rest fibs)] but I get a stack overflow.  Why is this?


texts:
I'm new to this competitive programming world. This morning I came across this question, which required the time to be less than 1 sec. But my code runs for 1.000069 sec, thereby rejecting my solution.

Question:

  There are N chocolate boxes, and you will be given with a chocolate index for which we have to guess the correct box number. For example, The first box contain chocolates from 1 to N1 and the next box contain N1+1 through N2 and so on.

My Solution:

#include<iostream>
using namespace std;

//returns the sum of chocolates from 0 to i

int getSum(int i,int *array){
    int sum = 0;
    for(int j=0; j< i; j++){
        sum += array[j];
    }
    return sum;
}
int main(){
    int n,q;
    //Get the number of chocolate boxes.
    cin >> n;
    int chocolatesInEachBox[n];
    //Get the number of chocolates in each box.
    for(int i =0; i < n; i++){
        cin >> chocolatesInEachBox[i];
    }
    //Get the number of queries.
    cin>>q;
    int chocolateIndexes[q];
    //Get each query.
    for(int i =0; i < q; i++){
        cin >> chocolateIndexes[i];
    }
    int j=0,i=0;

    while(j < q && i<n){

        if((chocolateIndexes[j]-getSum(i+1,chocolatesInEachBox))>0)
        i++;

        else{
            cout<<i+1<<endl;
            j++;
            i=0;
        }
    }
}


texts:
I created this small function just to practice C code.  It's a simple random string generator.

#include <string.h>
#include <time.h>

char *randstring(int length) {
    static int mySeed = 25011984;
    char *string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
    size_t stringLen = strlen(string);
    char *randomString = NULL;

    srand(time(NULL) * length + ++mySeed);

    if (length < 1) {
        length = 1;
    }

    randomString = malloc(sizeof(char) * (length +1));

    if (randomString) {
        short key = 0;

        for (int n = 0;n < length;n++) {
            key = rand() % stringLen;
            randomString[n] = string[key];
        }

        randomString[length] = '\0';

        return randomString;
    }
    else {
        printf("No memory");
        exit(1);
    }
}

The code seems to work ok.
Any ideas, improvements or bugs?

I added the mySeed var so that if I call it twice with the same length it doesn't give me the same exact string.

EDIT:

I have changed the code to this:

char *randstring(size_t length) {

    static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
    char *randomString = NULL;

    if (length) {
        randomString = malloc(sizeof(char) * (length +1));

        if (randomString) {
            for (int n = 0;n < length;n++) {
                int key = rand() % (int)(sizeof(charset) -1);
                randomString[n] = charset[key];
            }

            randomString[length] = '\0';
        }
    }

    return randomString;
}

I know that in the sizeof(charset) you don't have to use the (). You only need them when using sizeof with types, but it's just out of habit.


texts: Rust idiomatic way of polymorphic struct

texts:
I've implemented a simple polymorphic structure, which looks a bit ugly and I'm afraid I am missing an idiomatic way of doing it.

To describe briefly what I'm trying to achieve here: I would like to have a structure with a collection of handlers, which all must implement specific trait.

use std::fmt;
use std::fmt::Formatter;
use std::fmt::Error;

trait Handler {
    fn get_type(&self) -> String;
}

struct FileHandler {
}

struct DbHandler {
}

impl Handler for FileHandler {
    fn get_type(&self) -> String {
        "file".to_string()
    }
}

impl Handler for DbHandler {
    fn get_type(&self) -> String {
        "db".to_string()
    }
}

struct Config {
    handlers: Vec<Box<Handler>>
}

impl fmt::Debug for Config {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        for h in self.handlers.iter() {
            println!("{}", h.get_type());
        }
        write!(f, "config")
    }
}

pub fn run() {
    let mut handlers: Vec<Box<Handler>> = Vec::new();

    let fh = FileHandler {};
    let dh = DbHandler {};

    handlers.push(Box::new(fh));
    handlers.push(Box::new(dh));

    let c = Config { handlers };
    println!("{:?}", c);
}

Is there a way of more cleaner or more idiomatic solution here?