texts: Template for PHP service (/etc/init.d) script

texts:
I wanted a template for a service script that is versatile and easily configurable.

Along with producing similar outputs to the SSH and Samba daemons, I request the code to be as clean, simple and self explanatory as possible.  Hence I removed all the comments.

Sample usage:

$ service mydaemon restart
mydaemon stop/waiting
mydaemon start/running, process 30549

Sample of similar command with the SSH daemon:

$ service ssh restart
ssh stop/waiting
ssh start/running, process 30577

Here is my service.php script:

#!/usr/bin/php
<?php

    define('NAME',      basename($argv[0]));
    define('RUNAS',     'root');
    define('DIR',       __DIR__);
    define('CMD',       __DIR__.'/thread.php');
    define('SUDO',      'sudo -u '.RUNAS.' ');
    define('LOG_FILE',  '/dev/null');
    define('PID_FILE',  '/var/run/'.NAME.'.pid');

    function writeln($string)
    {
        echo $string.PHP_EOL;
    }

    class service
    {
        public static function unset_pid()
        {
            if (is_file(PID_FILE)) unlink(PID_FILE);
        }

        public static function get_pid()
        {
            if (!is_file(PID_FILE)) return null;

            $pid=file_get_contents(PID_FILE);

            $process_status=null;
            if (!empty($pid) && ctype_digit($pid)) $process_status=shell_exec('ps '.$pid);

            if (empty($process_status) || strpos($process_status, CMD, 0)===false)
            {
                service::unset_pid();
                return null;
            }

            return $pid;
        }

        public static function is_running()
        {
            return (!empty(service::get_pid()));
        }

        public static function start()
        {
            if (service::is_running())
            {
                writeln('start: Job is already running: '.NAME);
                return true;
            }

            $new_pid=shell_exec('cd '.DIR.';'.SUDO.CMD.' >> '.LOG_FILE.' 2>&1 & printf $!;');
            file_put_contents(PID_FILE, $new_pid);
            service::status();

            return service::is_running();
        }

        public static function stop()
        {
            if (!service::is_running())
            {
                writeln('stop: Unknown instance:');
                return true;
            }

            shell_exec('kill '.service::get_pid());

            for ($seconds=0; $seconds<60; $seconds++)
            {
                if (!service::is_running()) break;
                sleep(1);
            }

            if (service::is_running())
            {
                writeln('Not stopped; may still be shutting down or shutdown may have failed.');
                return false;
            }

            service::status();

            return !service::is_running();
        }

        public static function restart()
        {
            if (!service::stop())
            {
                writeln('Aborting restart.');
                return false;
            }

            return service::start();
        }

        public static function status()
        {
            $running=service::is_running();
            if ($running) writeln(NAME.' start/running, process '.service::get_pid()); else writeln(NAME.' stop/waiting');
            return $running;
        }

    };

    if (count($argv)!=2)
    {
        if (count($argv)>2) writeln('Too many arguments given.');
        $argv=array($argv[0], '');
    }

    switch (strtolower($argv[1]))
    {
        case 'start':

            service::start();
            break;

        case 'stop':

            service::stop();
            break;

        case 'restart':

            service::restart();
            break;

        case 'status':

            service::status();
            break;

        default:

            if (!empty($argv[1])) writeln('Unknown option: '.$argv[1]);
            writeln('Usage: '.$argv[0].' {start|stop|restart|status}');
            break;
    }

?>

Any suggestions for improvements will be appreciated.


texts: Route factory which creates instances based on database context and model

texts:
I am trying to bridge the gap between the database context and routes that are stored in the database.

The factory is designed so that when used in other assemblies, you are forced to use the database context which is known to contain the DbSet which can provide the required data to populate the route.

In the assembly in which the factory resides, you can specify the database context to use so that if more route types are created the route factory can provide different types of route to other classes within the assembly.

However, the idea initially behind the factory was that the assemblies which reference the assembly with the factory could also specify a database context or model as long as it inherits the base database context or model. I'm aware that making the methods internal prevents this, but the methods have been made internal as they may be removed if I refactor the way everything works.

The following is the class:

namespace Sapphire.Cms.Web.Routing
{
    using Sapphire.Cms.Data.Entity;
    using Sapphire.Cms.Models;
    using System;
    using System.Web.Routing;

    public class RouteFactory : IRouteProvider
    {
        public virtual RouteBase GetRoute(IRouteHandler routeHandler)
        {
            DbContextTypeWrapper<SapphireDbContext<SiteTree>, SiteTree> dbContextTypeWrapper = new DbContextTypeWrapper<SapphireDbContext<SiteTree>, SiteTree>();
            return GetRoute(dbContextTypeWrapper, routeHandler);
        }

        internal virtual RouteBase GetRoute(DbContextTypeProvider databaseContextTypeProvider, IRouteHandler routeHandler)
        {
            return GetRoute(databaseContextTypeProvider, typeof(SiteTree), routeHandler);
        }

        internal virtual RouteBase GetRoute(DbContextTypeProvider databaseContextTypeProvider, Type model, IRouteHandler routeHandler)
        {
            Type catchallRoute = typeof(CatchallRoute<,>).MakeGenericType(new Type[] {
                databaseContextTypeProvider.DbContextType,
                model
            });

            Type routeTypeWrapper = typeof(RouteTypeWrapper<>).MakeGenericType(new Type[] {
                catchallRoute
            });

            RouteTypeProvider routeTypeProvider = (RouteTypeProvider)Activator.CreateInstance(routeTypeWrapper);

            return GetRoute(routeTypeProvider, routeHandler);
        }

        private static RouteBase GetRoute(RouteTypeProvider routeTypeProvider, IRouteHandler routeHandler)
        {
            Object[] constructorParameters = new Object[]
            {
                routeHandler
            };

            return (RouteBase)Activator.CreateInstance(routeTypeProvider.RouteType, constructorParameters);
        }

        #region IRouteProvider Members
        RouteBase IRouteProvider.GetRoute(IRouteHandler routeHandler)
        {
            return GetRoute(routeHandler);
        }
        #endregion
    }
}

As you can see the class makes heavy use of reflection, which is bad for performance, however the intended use of this factory is that it should only ever have to get one route, a catchall route.

My questions are:

Based on what was said, should I keep the internal methods internal or make them public?
Should the factory be refactored to improve performance despite the intention being to only ever use it once per request?


texts: Generate 16-digit unique code (like product serial)

texts:
I am not sure what to call this type of code (16-digit alphanumeric code).

Conditions are like this:

Digits (or characters) are limited 16
Numeric, alphabet mixed
No duplication allowed (not yet implemented)

One class with the main method:

public class QuadraDigitCipherGenerator {
    // Step 1. Generate 16 digit wich is not duplicated
    // Step 2. divide by 4 digit

    private static List<Integer> pickRandomIndex (String original, int count) {
        List<Integer> randIndices = new ArrayList<Integer>();
        Set<Integer> noDuplicateIndices = new HashSet<Integer>();
        System.out.println(noDuplicateIndices.size() + "    " + count);
        while (noDuplicateIndices.size() < count){
            System.out.println(noDuplicateIndices.size() + "    " + count);
            int randNumber = (int)(Math.random() * original.length());
            noDuplicateIndices.add(randNumber);
        }
        randIndices.addAll(noDuplicateIndices);
        return randIndices;
    }

    // FROM 97 - 122
    private static char convertDigit2Char(char digit) {
        return (char)(17 + digit);
    }

    private static String generateCode(int digit, int charCnt) {
        long nano = System.nanoTime();
        StringBuilder util = new StringBuilder(String.valueOf(nano));
        util = util.reverse();
        List<Integer> convertIndices = pickRandomIndex(util.toString(), charCnt);
        System.out.println("Below indices will be casting to Alphabet " + convertIndices);

        for(Integer i : convertIndices){
            char target = util.charAt(i);
            util.setCharAt(i, convertDigit2Char(target));
        }
        return util.toString();
    }

    private static String beautifyDigits(String original, int term){
        System.out.println("original " + original);
        return original.substring(0, term) + "-" + original.substring(term, 2*term)
                + "-" + original.substring(2*term, 3*term) + "-" + original.substring(3*term, 4*term);
    }

    public static void main(String argv[]) throws Exception {
        int digit = 16;
        System.out.println(digit + " digits random code > " + beautifyDigits(generateCode(16, 4), 4));
    }
}

The output looks like D33J-H872-3545-71A1, a product serial key.

Anyway, I think this code is not satisfied with the third condition (no duplication). Do you have any advice with regards to that aspect of the requirements?


texts:
I created a simple Authorization module with Rails. I found that there are other authorization systems, such as CanCanCan, but they grant permissions at Model level and, for this particular website I am developing, it is more convenient to authorize at Controller level.

The idea is simple: the permissions are stored in a YAML file in the config directory and a function checks if the combination of admin_role, controller and action exist in the config file. There is also a wildcard :all.

# app/controllers/admins/base_controller.rb
class Admins::BaseController < ApplicationController

  include Admins::AuthorizationHelper

  before_action :authorize_admin

  ...

end

# app/helpers/admin/authorization_helper.rb
module Admins::AuthorizationHelper

  private

  def authorize_admin
    unless is_authorized? params[:controller], params[:action]
      refuse_access_to_admin_site
    end
  end

  def is_authorized?(controller, action)
    permissions = Rails.application.config_for :admin_auth
    authority = current_admin.authority

    if permissions[authority].nil?
      false
    elsif permissions[authority] == ['all']
      true
    elsif permissions[authority][controller].nil?
      false
    elsif permissions[authority][controller] == ['all']
      true
    elsif permissions[authority][controller].include? action
      true
    else
      false
    end
  end

  def refuse_access_to_admin_site
    flash[:error] = 'Permission denied'

    if request.referer.present?
      redirect_to :back
    else
      redirect_to admins_products_path
    end
  end

end

# config/admin_auth.yml
defaults: &defaults
    super_admins:
        - all
    admins:
        admins/shops:
            - index
            - show_used_history
        admins/products:
            - index
        admins/prescriptions:
            - all
        admins/products:
            - index
    operators:
        admins/products:
            - index
        admins/prescriptions:
            - all
        admins/shipments:
            - index
            - show
test:
    <<: *defaults
development:
    <<: *defaults
staging:
    <<: *defaults
production:
    <<: *defaults


texts:
I needed to create a simple method that converts numbers in Base 26 (string) using, as expected, letters from a to z.

But that's not all, this Base 26 needs to be One Based. Which means that there is no representation for zero absolute value and there is a representation for 26 absolute value. Let me show a example:

In Base 26 Zero Based the number 18252 will be represented like:

$$
(18252)_{10} = (BBAA)_{26}
$$

where B == 1 and A == 0. But as an One Based I need to get:

$$
(18252)_{10} = (ZYZ)_{26}
$$

where Y == 25 and Z == 26.

So I came up with this snippet:

var array = new List<int>();

var div = myNumber;
var getOne = 0;

while (div > 26)
{
    var value = div % 26;

    value -= getOne;

    if (value <= 0)
    {
        value += 26;
        getOne = 1;
    }
    else
    {
        getOne = 0;
    }

    array.Add(value);

    div = div / 26;
}

div -= getOne;

if (div > 0) array.Add(div);

var letters = array.Select(s => (char)('A' + s - 1)).Reverse().ToArray();

return new string(letters);

Now I wonder if there is a better way write this.


texts: Find the smallest number whose sum of digits add to a number

texts:
Request for review, optimization, best practice recommendations etc.

/**
 * Find the smallest positive number whose individual digits adds to the input number.
 * eg: consider the input 14,
 * The smallest number whose digit add to the given number is 59 ie 5 + 9 = 14.
 *
 * Complexity: O(n), where n is the input number
 *
 */
public class SmallestNumber {

    private SmallestNumber() {}

    private static int getIntNum(int x, int y) {
        String number = new StringBuilder().append(x).append(y).toString();
        return Integer.parseInt(number);
    }

    /**
     * Given an integer, returns the smallest positive number whose digits adds up to that number.
     *
     * @param x the number used to find another number whose digits add up to itself
     * @returns the smallest positive number whose digits adds up to input number.
     */
    public static int getVal(int x) {
        x = Math.abs(x);
        int min = Integer.MAX_VALUE;

        for (int i = 1; i <= x / 2; i++) {
            int diff = x - i;

            int p1 = getIntNum(i, diff);
            int p2 = getIntNum(diff, i);

            /**
             * http://stackoverflow.com/questions/9576557/most-efficient-way-to-
             * find-smallest-of-3-numbers-java
             */
            if (p1 < min) min = p1;
            if (p2 < min) min = p2;
        }
        return min;
    }

    /**
     * http://stackoverflow.com/questions/2674707/how-to-concatenate-int-values-
     * in-java
     *
     * @param args
     */
    public static void main(String[] args) {
       int x1 = getVal(14);
       System.out.println("Expected 59, Actual: " + x1);

       int x2 = getVal(16);
       System.out.println("Expected 79, Actual: " + x2);
    }
}


texts: Cell division Solving algorithm problems

texts:
When G cell divides, it is divided into two G + 1 cells.

In order for the G cell to divide, energy as much as G is required.

What is the minimum energy required to make the total number of cells x?

Input Example (G for each of 2 cells, total number of cells)

1 3 4

Output Example (minimum energy)

3

Input Description
Assuming that there is one cell of the first generation and one cell of the first generation in the beginning, the energy required to make a total of four cells is as follows.
1G 3G -> Generation 1 (Energy 1 required)
2G 2G 3G -> Generation 2 (energy 2 required)
2G 3G 3G 3G (total 4 completed final energy 3)

I've answered the question in C #.

Is there a better way or a way to speed it up?

ex) If Sum is 10 million

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program
  {
     static void Main(string[] args)
     {
        StringBuilder m_strbuilder = new StringBuilder();

         List<int> Cells = new List<int>();
         int MinIndex = 0;
         int Sum = 0;
         int FirstCell = 0;
         int SecondCell = 0;

         bool etc = true;
         ulong Result = 0;

         string Inputdata = null;
         string[] Textdata = null;

         while (etc)
        {
           try
           {
             Cells.Clear();

             Inputdata = Console.ReadLine();

             Textdata = Inputdata.Split(' ');

             if (Textdata[0] != null && Textdata[1] != null && Textdata[2] != null)
             {
                int.TryParse(Textdata[0], out FirstCell);
                int.TryParse(Textdata[1], out SecondCell);
                int.TryParse(Textdata[2], out Sum);
              }

            else
                continue;

            if ( 0 < FirstCell && FirstCell <= 10000000)
            {
                if (0 < SecondCell && SecondCell <= 10000000)
                {
                    if (2 <= Sum && Sum <= 100000000)
                        etc = false;
                    else
                        continue;
                }
                else
                    continue;
             }
            else
                continue;
           }

        catch (ArgumentException e)
        {
            Console.WriteLine("Unable to add {0}", e.ToString());
        }
        catch (NullReferenceException e)
        {
            Console.WriteLine("Unable to add {0}", e.ToString());
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine("Unable to add {0}", e.ToString());
        }
       }

        Cells.Add(FirstCell);
        Cells.Add(SecondCell);

        if (Cells[0] > Cells[1])
        {
            int TempNum = Cells[1];
            Cells[1] = Cells[0];
            Cells[0] = TempNum;
        }

         for (int i = 2; i < Sum; i++)
        {
            Result += (ulong)Cells[MinIndex];

            Cells[MinIndex] += 1;

            Cells.Insert(MinIndex + 1, Cells[MinIndex]);

            if (MinIndex + 1 != Cells.Count - 1)
            {
                if (Cells[MinIndex + 2] < Cells[MinIndex])
                    MinIndex = MinIndex + 2;
                else
                    MinIndex = 0;
            }
            else
                MinIndex = 0;
        }

        m_strbuilder.Append(Result);
        Console.WriteLine(m_strbuilder);

      }
    }
 }


texts:
I had an overloaded method, but Grails doesn't allow overloaded methods in controller actions.  The overloaded method looked like this:

def punch(User user, User source) {
    user.userVersion++
    punch(user, source, null, null)
  }

 def punch(User user, User source, String latitude, String longitude) {

     UserPunch userPunch = new UserPunch()
     userPunch.punchClockStatus = user.punchClockStatus
     userPunch.user = user
     userPunch.job = user.job
     userPunch.task = user.task
     userPunch.date = new Date()
     userPunch.source = source
     userPunch.save(flush: true)
     if (latitude != null) {
        userPunch.latitude = latitude
        userPunch.longitude = longitude
     }
     if (userPunch.hasErrors())
        userPunch.errors.each {
            log.error it
     }
}

In order to get around the restrictions on overloaded methods, I used a try/catch, like this:

def punch(User user, User source, String latitude, String longitude) {

    UserPunch userPunch = new UserPunch()
    userPunch.punchClockStatus = user.punchClockStatus
    userPunch.user = user
    userPunch.job = user.job
    userPunch.task = user.task
    userPunch.date = new Date()
    userPunch.source = source
    userPunch.save(flush: true)
    try {
        userPunch.latitude = latitude
        userPunch.longitude = longitude
    } catch (MissingPropertyException e) {
        user.userVersion++
    }
    if (userPunch.hasErrors())
        userPunch.errors.each {
            log.error it
        }
}

Does this look like it will work right? Does anyone have a better solution?


texts: C program to generate Seed programs from statically defined Befunge code

texts:
My program takes static input, and then number crunches for a few hours. I am currently using Macros, but is there a better, more "user friendly" way to do this without losing on performance.

I have written a program in C to generate Seed programs from a Befunge program. It is a very long, brute force calculation. So that it can be heavily optimised, the input variables are hardcoded using Macros. However, I was wondering if there was a better way to do this that would lead to the same or better optimisation.

Here's the Mersenne Twister I used: math.sci.hiroshima-u.ac.jp/~m-mat/...

/*
Copyright wizzwizz4 (c) 2015
*/

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include "mt19937ar.h"

/*Settings*/
#define PROGRAM_STRING "\"ck,@!dlroW ,olleH"
#define PROGRAM_LENGTH 18
#define   INITIAL_SEED 0
/*End settings*/

/*Meta settings*/
#define PROGRAM_LENGTH_TYPE char
/*End meta settings*/

unsigned long seed = INITIAL_SEED;
char prog[PROGRAM_LENGTH] = PROGRAM_STRING;

/*Ctrl-C Handlers*/
void ignore(int sig) {
    signal(SIGINT, ignore);
}
void panic(int sig) {
    printf("Quick! Copy the output. Something's trying to close me!");
    signal(SIGINT, ignore);
}
void stopped(int sig) {
    printf("We got to %u\nPress any key to quit...", seed);
    signal(SIGINT, panic);
    getchar();
    exit(1);
}
void finished(int sig) {
    printf("Copied the output? Great.\nPress any key to quit...");
    signal(SIGINT, panic);
    getchar();
    exit(0);
}
/*End Ctrl-C Handlers*/

int main(void) {
    signal(SIGINT, stopped);

    PROGRAM_LENGTH_TYPE x; /*The program loop character*/
    _Bool y; /*Seed === Program?*/

    /*Take 32 from the program characters*/
    for (x = 0; x < PROGRAM_LENGTH; x++)
        prog[PROGRAM_LENGTH] = prog[PROGRAM_LENGTH] - 32;

    /*Do the checking*/
    while (1) {
        init_genrand(seed);
        y = 1;
        for (x = 0; x < PROGRAM_LENGTH; x++) {
            /*Compares generated character to expected one*/
            if (prog[PROGRAM_LENGTH] != (char)(genrand_res53() * 96) ) {
                y = 0;
                break; /*Break if wrong; no sense in checking the rest!*/
            }
        }
        if (y) break; /*If the for loop didn't break, seed was right!*/
        seed++;
    }

    /*Output, and make sure nobody gets hurt*/
    printf("COMPLETE Seed program:\n%u %u\nMake sure you copy this down\nPress ^C to quit...", PROGRAM_LENGTH, seed);
}


texts: Loading a Protein Data Bank file into a numpy matrix

texts:
Here is my code:

def read_Coordinates_Atoms2(fileName, only_CA = True):
    '''
    in : PDB file
    out : matrix with coordinates of atoms
    '''
    with open(fileName, 'r') as infile:
        for line in infile :
            if only_CA == True :
                if line.startswith('ATOM') and line[13:15] == 'CA':
                    try:    # matrix fill-up
                        CoordAtoms = np.vstack([CoordAtoms, [float(line[30:38]), float(line[38:46]), float(line[46:54])]]) # np.append
                    except NameError:  # matrix declaration
                        CoordAtoms = np.array([[line[30:38],line[38:46], line[46:54]]], float)
            else :
                if line.startswith('ATOM'):
                    try:    # matrix fill-up
                        CoordAtoms = np.vstack([CoordAtoms, [float(line[30:38]), float(line[38:46]), float(line[46:54])]]) # np.append
                    except NameError:  # matrix declaration
                        CoordAtoms = np.array([[line[30:38],line[38:46], line[46:54]]], float)
        return CoordAtoms

Is there a more efficient way to do this ? I mean, a way where I don't have to write twice the same lines? I think the code should look more like this :

def foo(file, condition2 = True):
    if condition1 and condition2 :
        # do lots of instructions
    elif condition1 :
        # do the same lots of instructions (but different output)


texts:
This is a continued discussion from (Different path for grid move) to optimize for space complexity, and since it is new code and I make a new post.

  Given a m * n grids, and one is allowed to move up or right, find the different number of paths between two grid points.

My major idea is, if move r steps right, u steps up, we can find (1) solutions for r-1 steps right and u steps up, then combine with one final right step (2) solutions for r steps right and u-1 steps up, then combine with one final up step.

I use a dynamic programming method to track count in r-1 steps (using pre_row) and r steps (using cur_row). Here is my code and any advice on code bugs, performance improvements in terms of time complexity, or code style issues are appreciated.

Source code in Python 2.7,

def grid_move(rights, ups):
    pre_row = []
    pre_row.append(0)
    # initialize for zero right and up only
    for i in range(1, ups+1):
        pre_row.append(1)
    cur_row = []
    for r in range(1, rights+1):
        for u in range(0, ups+1):
            if u > 0:
                cur_row.append(pre_row[u] + cur_row[-1])
            else:
                cur_row.append(1)
        pre_row = cur_row

    return cur_row[-1]

if __name__ == "__main__":
    print grid_move(2,3)


texts: Find the probability of picking a prime number in a range

texts:
The task is:

From a sub-sequence of integers between 2 inputted numbers A and B, we need to find the probability of picking a prime number. I have written something to accomplish the task-

import java.util.*;
class Sample{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int cases = sc.nextInt();
        for(int i = 0; i<cases; i++){
            int l = sc.nextInt();
            int r = sc.nextInt();

            double ans = 0.0;
            for(int j = l; j<=r;j++){
                if(isPrime(j)){
                    ans++;
                }
            }
            System.out.println(String.format("output: %.6f",ans/(r-l+1)));

        }

    }
    public static boolean isPrime(int n){
        boolean ans = true;
        if(n == 1){
            ans = false;
        }
        if(n>5&& n%5==0){
            ans = false;
        }
        if(n>2&&n%2 == 0){
            ans = false;
        }
        else{
        for(int i = 3; i<(Math.sqrt(n)+1);i=i+2){
            if(n%i == 0){
                ans = false;
                break;
            }
        }}
        return ans;
    }
}

We also input an integer (cases) to represent the number of test cases.
This gives a correct answer on my machine, but gets a time limit exceeded verdict when I upload it. I thought that maybe using c++ would solve the issue.

So I made a similar program in c++, but still it does not match the time limit of 1 second. The C++ code is:

#include <iostream>
#include <math.h>
using namespace std;
bool isPrime(int n){
    bool ans= true;
    if(n == 1){
        ans = false;
    }
    if(n > 2 && n%2 == 0){
        ans = false;
    }
    for (int i = 3; i < (pow(n,0.5)+1); ++i)
    {
        if(n%i == 0){
            ans = false;
            break;
        }
    }
    return ans;
}
int main(){
    int cases;
    cin>> cases;
    for(int i = 0;i<cases;i++){
        int a, b , ans = 0;
        cin>> a,b;
        for (int j = a; j <= b; ++j)
        {
            if(isPrime(j)){
                ans ++;
            }
        }
        double d = ans/(r-l+1);
        cout<<d;
    }

}

Constraints:

1 ≤ Cases ≤ 100000

1 ≤ A≤ B ≤ 1000000

How can I optimize it further?

What I researched -

I should check if a i divides n only up till Math.sqrt(n)+1. Also I should do i = i+2 as I have checked for even numbers before only. I should also break the loop once ans becomes false so as to stop any further unnecessary iterations.

for(int i = 3; i<(Math.sqrt(n)+1);i=i+2){
        if(n%i == 0){
            ans = false;
            break;
        }
    }

Here is the link to the question: codechef.


texts:
This is my simple unique_ptr implementation. Anything that could be improved upon or should be added?

#include <algorithm>

template<typename T>
class unique_ptr
{
private:
    T * ptr_resource = nullptr;
public:
    // Safely constructs resource. Operator new is called by the user. Once constructed the unique_ptr will own the resource.
    // std::move is used because it is used to indicate that an object may be moved from other resource.
    explicit unique_ptr(T* raw_resource) noexcept : ptr_resource(std::move(raw_resource)) {}
    unique_ptr(std::nullptr_t) : ptr_resource(nullptr) {}

    // destroys the resource when object goes out of scope
    ~unique_ptr() noexcept
    {
        delete ptr_resource;
    }
    // Disables the copy/ctor and copy assignment operator. We cannot have two copies exist or it'll bypass the RAII concept.
    unique_ptr(const unique_ptr<T>&) noexcept = delete;
    unique_ptr& operator = (const unique_ptr&) noexcept = delete;
public:
    // releases the ownership of the resource. The user is now responsible for memory clean-up.
    T* release() noexcept
    {
        T* resource_ptr = this->ptr_resource;
        this->ptr_resource = nullptr;

        return resource_ptr;
    }
    // returns a pointer to the resource
    T* get() const noexcept
    {
        return ptr_resource;
    }
    // swaps the resources
    void swap(unique_ptr<T>& resource_ptr) noexcept
    {
        std::swap(ptr_resource, resource_ptr.ptr_resource);
    }
    // replaces the resource. the old one is destroyed and a new one will take it's place.
    void reset(T* resource_ptr) noexcept(false)
    {
        // ensure a invalid resource is not passed or program will be terminated
        if (resource_ptr == nullptr)
            throw std::invalid_argument("An invalid pointer was passed, resources will not be swapped");

        delete ptr_resource;

        ptr_resource = nullptr;

        std::swap(ptr_resource, resource_ptr);
    }
public:
    // operators
    T* operator->() const noexcept
    {
        return this->ptr_resource;
    }
    T& operator*() const noexcept
    {
        return *this->ptr_resource;
    }
    // May be used to check for nullptr
};


texts:
I was wondering if there is a better way to code this:

using (SqlConnection connection = new SqlConnection(ConnectionString)) {
   using (SqlCommand cmdDelete = new SqlCommand("DELETE FROM table WHERE
         (TestNumber = '" + testNumber + "')", connection)) {
      try
      {
         connection.Open();
         int recordExists = deletePolicyFromTdm.ExecuteNonQuery();
         connection.Close();

         if(recordExists == 1)
            result.Append("Record has been deleted");
         else
           result.Append("Record does not exist");
      ...

Couple of assumptions:

testNumber is unique and no duplicate records and was input tested, at least according to bus rules. So I realize that if more than one record is present the if statement won't work properly
Table has a PK but testNumber isn't it
Only one roundtrip to db
Can't change how DB is set up
SQL command will eventually be replaced with a sproc and parameter

The idea is that if user clicks a button and gets either a message that no record exists or that the records were deleted.


texts:
We use a third party dll which has an object called CServer and was provided by one of our software vendors to act as an API between our applications and their applications.

CServer has the following method:

bool SynchroniseData() which can be called if we want to fetch data from server which is very important for our application. This call signifies to the DLL our intention that we want to fetch the data. It does not fetch the data. Instead it returns true, if the request was successfully send to their application.

When data are actually fetched in the CServer object, CServer fires the event onDataFetched. We listen to that event and process the data. The CServer always has the latest data, since it continuously synchronises the data with our Vendor's servers.

However, there are many times at which the event onDataSynchronisationStopped is called. This signifies that the CServer object will stop data synchronisation with the server. This event is fired when the network is momentarily down, or if the server has some minor delays and so on.

We always want to have that data, and thus we try to fetch them again.

We currently do it like this:

private void OnDataFetchedHandler(object sender, EventArgs eventArgs){

            try{
                bool dataHaveBeenFetched;
                do{
                    dataHaveBeenFetched = TrytoFetchData((CServer) sender);
                    Thread.Sleep(1000);
                } while (!dataHaveBeenFetched);
            }
            catch (Exception ex){
                Log.ErrorFormat(ex.Message, ex);
            }
        }

        private bool TrytoFetchData(CServer sender){
            sender.SynchroniseData();
            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            EventHandler manualResetEventSethandler = (s, e) => manualResetEvent.Set();
            sender.OnDataFetched += manualResetEventSethandler;

            bool dataHaveBeenFetched = manualResetEvent.WaitOne(new TimeSpan(0, 0, 3, 0));
            sender.OnDataFetched -= manualResetEventSethandler;

            return dataHaveBeenFetched;
        }

Is there any cleaner way of doing this?


texts:
I am creating a small library for controlling bars of leds and have some doubts about my design.

I have 2 basic entities in the design so far:

BarService (and implementation)

template<class T>

class BarService{
public:
  virtual void turnOnLeds(T* bar, int end) = 0;

class PinBarService : public BarService<PinBar>{
public:
  virtual void turnOnLeds(PinBar* bar, int end);
  void initPins(PinBar* bar);
};

class OpampService : public BarService<OpampBar>{
public:
  virtual void turnOnLeds(OpampBar* bar, int end);
  void initPins(OpampBar* bar);
};

Bar models:

class Bar{
private:
  int ledCount;
public:
  Bar(int ledCount);
  int getLedCount();
};

class BasicBar : public Bar{
private:
  int* pins;
public:
  BasicBar(int ledCount, int pins[]);
  int getPin(int index);
};

class OpampBar : public Bar{
private:
  int input;
public:
  OpampBar(int ledCount, int input);
};

My reasoning for separating these is that I feel the Bar models should only contain information about themselves, thus allowing me to create more classes later on which use that information rather than having the bar itself perform actions (like writing to hardware).

The reason I'm having doubts is that by using templates every implementation of the service needs to accept a different model.

My question comes down to: Am I going overboard with separating the model from its actions? and are templates a good solution here? and overall, what could be improved about this design?


texts: Better multithreading with network IO and database queries

texts:
I'm writing a script that:

fetch a list of urls from a db (about 10000 urls)
download all the pages and insert them into the db
parse the code
if(some condition) do other inserts into the db

I have a Xeon quad-core with hyper-threading, so a total of 8 thread available and I'm under Linux (64 bit).

I'm using cStringIO as buffer, pycurl to fetch the pages, BeautifulSoup to parse them and MySQLdb to interact with the database.

I tried to simplify the code below (removing all the try/except, parsing operation, ...).

import cStringIO, threading, MySQLdb.cursors, pycurl

NUM_THREADS = 100
lock_list = threading.Lock()
lock_query = threading.Lock()

db = MySQLdb.connect(host = "...", user = "...", passwd = "...", db = "...", cursorclass=MySQLdb.cursors.DictCursor)
cur = db.cursor()
cur.execute("SELECT...")
rows = cur.fetchall()
rows = [x for x in rows]  # convert to a list so it's editable

class MyThread(threading.Thread):
    def run(self):
        """ initialize a StringIO object and a pycurl object """

        while True:
            lock_list.acquire()  # acquire the lock to extract a url
            if not rows:  # list is empty, no more url to process
                lock_list.release()
                break
            row = rows.pop()
            lock_list.release()

            """ download the page with pycurl and do some check """

            """ WARNING: possible bottleneck if all the pycurl
                connections are waiting for the timeout """

            lock_query.acquire()
            cur.execute("INSERT INTO ...")  # insert the full page into the database
            db.commit()
            lock_query.release()

            """do some parse with BeautifulSoup using the StringIO object"""

            if something is not None:
                lock_query.acquire()
                cur.execute("INSERT INTO ...")  # insert the result of parsing into the database
                db.commit()
                lock_query.release()

# create and start all the threads
threads = []
for i in range(NUM_THREADS):
    t = MyThread()
    t.start()
    threads.append(t)

# wait for threads to finish
for t in threads:
    t.join()

I use multithreading so I don't need to wait if some requests are going to fail for timeout. That specific thread will wait but the others are free to continue with the other urls.

Here is a screenshot while doing nothing but the script:

It seems that 5 cores are busy while the other are not. So the questions are:

should I create as many cursors as the number of threads?
do I really need to lock the execution of a query? What happened if a thread execute a cur.execute() but not the db.commit() and another thread come in doing the execution + commit with another query?
I read about the Queue class, but I'm not sure if I understood correctly: can I use it instead of doing lock + extract a url + release?
using multithreading can I suffer from I/O (network) bottleneck? With 100 threads my speed doesn't exceed ~500Kb/s while my connection can go faster. If I move to multiprocess will I see some improvement on this side?
the same question but with MySQL: using my code, there could be a bottleneck on this side? All those lock + insert query + release can be improved in some way?
if the way to go is multithreading, is 100 an high number of threads? I mean, too many threads doing I/O requests (or DB queries) are useless because of the mutual exclusion of these operations? Or more threads means more network speed?

1:


texts: Python string clean up function with optional args

texts:
I've got a function that I mainly use while web scraping. It gives me the ability to throw in a multi line address and clean it or a name field with unwanted characters and clean those, etc.

Below is the code and I would like to know if this is the best approach. If I should switch to recursive or stick with the while loop. Or if I should look at some other completely different approach. Examples of I/O commented in the code.

def clean_up(text, strip_chars=[], replace_extras={}):
    """
    :type text str
    :type strip_chars list
    :type replace_extras dict
    *************************
    strip_chars: optional arg
    Accepts passed list of string objects to iter through.
    Each item, if found at beginning or end of string, will be
    gotten rid of.
    example:
    text input: '       ,  ,      , .,.,.,.,,,......test, \t  this\n.is.a\n.test...,,,         , .'
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^------^^^^----^^-----^^-----^^^^^^^^^^^^^^^^^^
    strip_chars arg: [',', '.']
    output: 'test, this .is.a .test'
    *************************
    replace_extras: optional arg
    Accepts passed dict of items to replace in the standard
    clean_up_items dict or append to it.
    example:
    text_input: ' this is one test\n!\n'
                 ^--------^^^-----^^-^^
    replace_extras arg: {'\n': '', 'one': '1'}
    output: 'this is 1 test!'
    *************************
    DEFAULT REPLACE ITEMS
    ---------------------
    These can be overridden and/or appended to using the replace_extras
    argument.
    replace item      |   with
    <\\n line ending> - <space>
    <\\r line ending> - <space>
    <\\t tab>         - <space>
    <  double-space>  - <space>
    <text-input>      - <stripped>
    *************************
    """

    clean_up_items = {'\n': ' ', '\r': ' ', '\t': ' ', '  ': ' '}
    clean_up_items.update(replace_extras)

    text = text.strip()

    change_made = True
    while change_made:
        text_old = text
        for x in strip_chars:
            while text.startswith(x) or text.endswith(x):
                text = text.strip(x).strip()

        for key, val in clean_up_items.items():
            while key in text:
                text = text.replace(key, val)

        change_made = False if text_old == text else True

    return text.strip()


texts: Filter for reading data over a serial connection

texts:
This is a simple filter that I have been using for a project reading data over a serial connection, and thought it would be good to use it as my first attempt to write docstrings. Does anyone have any suggestions? I have been reading PEP 257. As it is a class, should the keyword arguments come after the __init__ ?

If there is a better way to write any part of it (not only the docstrings), I would appreciate it if people could point me in the right direction.

class Filter(object) :
    """Return x if x is greater than min and less than max - else return None.

    Keyword arguments:
    min -- the minimum (default 0)
    max -- the maximum (default 0)

    Notes:
    Accepts integers and integer strings
    """
    def __init__(self, min=0, max=0) :
        self.min = min
        self.max = max
    def __call__(self, input) :
        try :
            if int(input) <= self.max and int(input) >= self.min :
                return int(input)
        except : pass


texts:
Here is a screenshot of my setup:

Here is the actual code:

#activate python virtualenv
activate_this = 'C:/Users/D/Dropbox/_mypyapp/learnbottle/learnbottle/scripts/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

#import dependencies
import os
from bottle import route, run, template

#this is what will become the page html
index_html = '''My First web app! By {{ author }}'''

@route('/:anything')
def something(anything = ''):
    return template(index_html, author = anything)
@route('/')
def index():
    return template(index_html, author = 'your name here')

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 8080))
    run(host = '0.0.0.0', port = port, debut = True)

Couple things I should note:

This is my first time using virtualenv
This is the first time I am using git
This is my first time writing any sort of web app or using a framework

I'm following along with a tutorial on realpython.com. The tutorial is written for a "Unix-based environment" so I had to do some things to get it working on Windows. Not sure if I should go the route of setting up a VM as it seems unnecessarily complicated.

So, am I making any newbie mistakes and is there anything I should do differently?


texts: RouteContext as constructor parameter or method parameter in ASP.NET vNext

texts:
I have this simple class where I load an object from the database and store it into the RouteContext.DataTokens because I need to access it through out the request.

In this example the RouteContext is injected via the constructor but I'm not sure that's the right thing to do here, maybe the RouteContextshould be a method parameter instead?

public class RouteResolverTrie : IRouteResolverTrie
{
    private readonly IDocumentStore documentStore;
    private RouteContext context;

    public RouteResolverTrie(RouteContext context, IDocumentStore documentStore)
    {
        this.documentStore = documentStore;
        this.context = context;
    }

    public Trie LoadTrie()
    {
        if(context.DataTokens.ContainsKey("some key")) {
            return context.DataTokens["trie"] as Trie;
        }
        else {
            using(var session = documentStore.OpenSession()) {
                var trie = session.Load<Trie>("trie/1");
                context.DataTokens["trie"] = trie;
                return trie;
            }
        }
    }
}

This is how the routing works in vNext and this is my first entry point. As you can see I use LoadTrie() in the method RouteAsync which in turn uses the RouteContext to store temporary data through out the request. So, the question is, should I instantiate the DefaultRouter with a new RouteResolverTrie that takes the current RouteContext as a constructor parameter or should it be a method parameter?

public class DefaultRoute : IRouter
{
    private readonly IRouter _target;
    private IRouteResolverTrie _routeResolverTrie;

    public DefaultRoute(IRouter target, IRouteResolverTrie routeResolverTrie) {
        _target = target;
        _routeResolverTrie = routeResolverTrie;
    }

    public string GetVirtualPath(VirtualPathContext context)
    {
        return null;
    }

    public async Task RouteAsync(RouteContext context)
    {
        var trie = _routeResolverTrie.LoadTrie();
    }
}


texts:
Related to this question, I wrote the (+++) function to join 2 JoinList's:

(+++) :: Monoid m => JoinList m a -> JoinList m a -> JoinList m a
(+++) Empty               y                    = y
(+++) x                   Empty                = x
(+++) left@(Single _ _)   right@(Single _ _)   = Append (tag $ Append mempty left right) left right
(+++) left                right                = Append (tag left `mappend` tag right) left right

Calling (+++) on jl1 and jl2 results in:

jl1 :: JoinList (Product Integer) String
jl1 = Append (Product 100) (Single (Product 25) "foo") (Single (Product 4) "bar")

jl2 :: JoinList (Product Integer) String
jl2 = Append (Product 50) (Single (Product 25) "bippy") (Single (Product 2) "baz")

Testing

*JoinList> (+++) jl1 jl2
Append (Product {getProduct = 5000})
          (Append (Product {getProduct = 100})
               (Single (Product {getProduct = 25}) "foo")
               (Single (Product {getProduct = 4}) "bar"))
          (Append (Product {getProduct = 50})
               (Single (Product {getProduct = 25}) "bippy")
               (Single (Product {getProduct = 2}) "baz"))


texts: Renaming the iframe src attribute to facilitate lazy loading

texts:
I'm not great with javascript. I need some code to rename all iframe src attribute names to data-src, for a lazyload plugin to work. I couldn't find out how to rename the attribute names, but with some trial and error I managed something similar and it is working OK:

$( document ).ready( function() {

     $( 'iframe' ).each(function() {

        //store each iframe scr attribute value in a variable
        var attr_value = $(this).attr("src");

        //Add a data-src attribute with the src attribute value
        $(this).attr('data-src', attr_value);

        // remove the old src attribute
        $(this).removeAttr('src');
    });
});

Does this look OK? or is there a better way to achieve this. Any help appreciated?


texts: Iterating through specific elements of an array with filter()

texts:
I have the following code which iterates through some divs of an array to show() them. I was wondering if there is any way to rewrite the for loop using filter(). Will this have a better performance over my initial code?

var selectEnabledGenerators = function(generators) {
    //List of generator indexes to show
    var list = generators;
    var allGenerators = $(".generatorContainer");
    //Hide all generators
    allGenerators.hide();
    //maybe use filter here?
    for (var i = 0, max = list.length; i < max; i++) {
        $(".generatorContainer[data-generator=" + list[i] + "]").show();
    }
};


texts:
I found a project that aims to implement a CLI calculator app in as many different languages and ways as possible. Having a little experience in PS, I tried my hand at it. The requirements are as follows:

Use a set interface (that is correctly done here)
Must use functions
No builtins, unless it's to interact with the terminal
Must have comments
Mustn't throw an error on input or keyboard interrupt

I don't have an idea about PS best practices, so I'm hoping for some input there. Anyways, here's what I came up with:

# Ask the user to input a number using the given prompt string
function Get-Double {

    param (
        $Prompt
    )

    do {
        $inp = Read-Host -Prompt $Prompt

        # Try to cast, if that fails $num will contain null
        $num = $inp -as [Double]
        $ok = $num -ne $NULL
        if (-not $ok) {
            Write-Host "You must enter a numeric value" -ForegroundColor Red
        }
    # try until the user gets it right
    } until ($ok)

    return $num
}

# Do a exponentiation using the given base and exponent
function Calculate-Exponent {

    param (
        $Base,
        $Exp
    )

    $res = 1

    # If the exponent is < 0, flip the sign of it to allow the same loop to be used
    # Also use the inverse base in that case since x/y = x*(1/y)
    if ($Exp -lt 0) {
        $Base = 1/$Base;
        $Exp *= -1;
    }

    for ($i = 0; $i -lt $Exp; $i++) {
        $res *= $Base
    }

    return $res
}

while (1) {
    clear
    Write-Host "PowerShell CLI calc v1.0" -ForegroundColor Yellow
    Write-Host "Choose a function"
    Write-Host "1 - Add        3 - Multiply   5 - Exponentiation"
    Write-Host "2 - Subtract   4 - Divide"

    do {
        # The Read-Host cmdlet puts a ":" after the supplied prompt when using -Prompt.
        # If we do it like this, we can get the requested custom prompt without that
        Write-Host -nonewline ">>> "
        $mode = Read-Host

        #match a single 1 2 3 4 or 5
        $ok = $mode -match "^[1-5]$"

        if (-not $ok) {
            Write-Host "Please enter a number between 1 and 5" -ForegroundColor Red
        }

    } until ($ok)

    # Newline for formatting
    Write-Host ""

    # Array definitions so that we can use the inputted mode value easily
    $modes = @("Addition", "Subtraction", "Multiplication", "Division", "Exponentation")
    $signs = @("+", "-", "*", "/", "^")

    Write-Host $("{0} - Please choose two numbers a and b to calculate a {1} b" -f $modes[$mode-1], $signs[$mode-1])

    $a = Get-Double -Prompt "a"
    $b = Get-Double -Prompt "b"

    switch ($mode) {
        1 {$res = $a + $b; break}
        2 {$res = $a - $b; break}
        3 {$res = $a * $b; break}
        4 {$res = $a / $b; break}
        5 {$res = Calculate-Exponent -Base $a -Exp $b; break}
    }

    Write-Host $("Result: {0} {1} {2} = {3}" -f $a, $signs[$mode-1], $b, $res)
    Write-Host ""

    Write-Host "Type Q/q to quit or press Enter to restart"
    do {
        Write-Host -NoNewline ">>> "
        $inp = $NULL
        $inp = Read-Host

        # Match a single q or Q
        if ($inp -match "^[qQ]$") {
            exit;
        }

        # Pressing enter results in the input being of length 0
        $ok = $inp.Length -eq 0
        if (-not $ok) {
            Write-Host "Please type either Q/q to quit or press Enter to restart!" -ForegroundColor Red
        }
    } until($ok);
}

UPDATE
Fixed Calculate-Exponent, shold now return correct result for any exponent


texts: Pandas : Apply Merge operations from a column

texts:
I have a data frame, which contains three columns:
import numpy as np
import pandas as pd
np.random.seed(0)
dataframe = pd.DataFrame({'operation': ['data_a', 'data_b', 'avg', 'concat', 'sum', 'take_a', 'concat'],
             'data_a': list(np.random.uniform(-1,1,[7,2])), 'data_b': list(np.random.uniform(-1,1,[7,2]))})

Column 'operation' represent merge column, so if there is 'data_a' value in Column 'operation', it means take that particular row's data_a value, if there is 'avg' operation, then take the average of 'data_a' and 'data_b' of that particular row so on.
What I am expecting in the output, a new column contains the values as per the operation column's merge functions:

What I have tried:
dataframe['new_column'] = 'dummy_values'

for i in range(len(dataframe)):

    if dataframe['operation'].iloc[i]  == 'data_a':
        dataframe['new_column'].iloc[i] = dataframe['data_a'].iloc[i]
    elif dataframe['operation'].iloc[i] == 'data_b':
        dataframe['new_column'].iloc[i] = dataframe['data_b'].iloc[i]
    elif dataframe['operation'].iloc[i] == 'avg':
        dataframe['new_column'].iloc[i] = dataframe[['data_a','data_b']].iloc[i].mean()
    elif dataframe['operation'].iloc[i] == 'sum':
        dataframe['new_column'].iloc[i] = dataframe[['data_a','data_b']].iloc[i].sum()
    elif dataframe['operation'].iloc[i] == 'concat':
        dataframe['new_column'].iloc[i] = np.concatenate([dataframe['data_a'].iloc[i], dataframe['data_b'].iloc[i]], axis=0)

That is obviously not a good way to do this, It's very slow too. I am looking for more pandas version to do this task.


texts: Background task with instant abort capability in c#

texts:
I'm looking for a better way to make a background operation with abort/cancel support. Right now I use this approach:

Task.Factory.StartNew(() => {
    var cts = new System.Threading.CancellationTokenSource();
    var ct = cts.Token;
    try
    {
        var t = System.Threading.Thread.CurrentThread;
        using (ct.Register(t.Abort))
        {
            LongOperation();
        }
    }
    catch {...} // an exception gets thrown about aborting threads
});

Calling ct.Cancel() stops the operation even if it's something that cannot usually be interrupted. The focus is that it can be stopped instantly.

I don't think this is unsafe if I'm not doing any file writing. So far it's been working well enough for me, but this code doesn't look proper to me. Is there a more canonical way to start background operations and abort them instantly? Are there any safety concerns I have been lucky not to encounter so far?

Update 2 years later: I looked it all up again, and it seems like a better way to avoid problems is to "abort" a process instead of aborting a thread on your app's main process. See this answer by Eric Lippert. to "What is a safe way to stop a running thread?" question.


texts:
I am writing a piece of code which models the evolution of a social network. The idea is that each person is assigned to a node and relationships between people (edges on the network) are given a weight of +1 or -1 depending on whether the relationship is friendly or unfriendly.

Using this simple model you can say that a triad of three people is either "balanced" or "unbalanced" depending on whether the product of the edges of the triad is positive or negative.

Finally, what I am trying to do is implement an ising type model.  In other words, random edges are flipped and the new relationship is kept if the new network has more balanced triangles (a lower energy) than the network before the flip, if that is not the case then the new relationship is  only kept with a certain probability.

I have written the following code, however the dataset I have contains ~120k triads, and as a result it will take 4 days to run!

Could anyone offer any tips on how I might optimise the code?

#Importing required librarys

try:
    import matplotlib.pyplot as plt
except:
    raise

import networkx as nx
import csv
import random
import math

def prod(iterable):
    p= 1
    for n in iterable:
        p *= n
    return p

def Sum(iterable):
    p= 0
    for n in iterable:
        p += n[3]
    return p

def CalcTriads(n):
    firstgen=G.neighbors(n)
    Edges=[]
    Triads=[]

    for i in firstgen:
        Edges.append(G.edges(i))

    for i in xrange(len(Edges)):
        for j in range(len(Edges[i])):# For node n go through the list of edges (j) for the neighboring nodes (i)
            if set([Edges[i][j][1]]).issubset(firstgen):# If the second node on the edge is also a neighbor of n (its in firstgen) then keep the edge.
                t=[n,Edges[i][j][0],Edges[i][j][1]]
                t.sort()
                Triads.append(t)# Add found nodes to Triads.

    new_Triads = []# Delete duplicate triads.
    for elem in Triads:
        if elem not in new_Triads:
            new_Triads.append(elem)
    Triads = new_Triads

    for i in xrange(len(Triads)):# Go through list of all Triads finding the weights of their edges using G[node1][node2]. Multiply the three weights and append value to each triad.
            a=G[Triads[i][0]][Triads[i][1]].values()
            b=G[Triads[i][1]][Triads[i][2]].values()
            c=G[Triads[i][2]][Triads[i][0]].values()
            Q=prod(a+b+c)
            Triads[i].append(Q)

    return Triads

###### Import sorted edge data ######
li=[]
with open('Sorted Data.csv', 'rU') as f:
    reader = csv.reader(f)
    for row in reader:
        li.append([float(row[0]),float(row[1]),float(row[2])])
G=nx.Graph()
G.add_weighted_edges_from(li)

for i in xrange(800000):
    e = random.choice(li)   # Choose random edge

    TriNei=[]
    a=CalcTriads(e[0]) # Find triads of first node in the chosen edge
    for i in xrange(0,len(a)):
        if set([e[1]]).issubset(a[i]): # Keep triads which contain the whole edge (i.e. both nodes on the edge)
            TriNei.append(a[i])
    preH=-Sum(TriNei) # Save the "energy" of all the triads of which the edge is a member

    e[2]=-1*e[2]# Flip the weight of the random edge and create a new graph with the flipped edge
    G.clear()
    G.add_weighted_edges_from(li)

    TriNei=[]
    a=CalcTriads(e[0])
    for i in xrange(0,len(a)):
        if set([e[1]]).issubset(a[i]):
            TriNei.append(a[i])
    postH=-Sum(TriNei)# Calculate the post flip "energy".

    if postH<preH:# If the post flip energy is lower then the pre flip energy keep the change
        continue

    elif random.random() < 0.92: # If the post flip energy is higher then only keep the change with some small probability. (0.92 is an approximate placeholder for exp(-DeltaH)/exp(1) at the moment)
        e[2]=-1*e[2]


texts:
I decided to write my own programming language, of sorts.  Essentially, you write code into a text file and the program will run the code inside the text file. The file is provided through a script argument.

# Basic programming language
from operator import eq, ne, lt, gt, le, ge
from random import random
from sys import exit, argv

# Specify file to be run
code = argv([1])

"""
>> - Specify to the user that something will be outputted.
<< - Specify to the user that something will be inputted.
"""

# Dict storing operators
OPERATORS = {
    "==": eq,
    "!=": ne,
    "<=": le,
    ">=": ge,
    "<": lt,
    ">": gt
}

# Dict storing program data
data = {
    "vars": [0] * 100000,
    "rand": random()
}

# Interpret the code
def interpreter(separator):
    for line in open(code, "r").readlines():

        # Split each line
        s_command = line.split(separator)

        # Basic input and output
        if s_command[0] == "$out" and s_command[1] == ">>":
            if s_command[2] in data:
                print data[s_command[2]]
            if s_command[2] not in data:
                print s_command[2]
        if s_command[0] == "$inp" and s_command[1] == "<<":
            inp = raw_input(s_command[2])

        # Assign integer variables
        if s_command[0] == "$assignint" and s_command[1] == "<<":
            data["vars"][int(s_command[2])] = int(s_command[3])

        # Assign string variables
        if s_command[0] == "$assignstr" and s_command[1] == "<<":
            data["vars"][int(s_command[2])] = s_command[3]

        # Return variable values
        if s_command[0] == "$return" and s_command[1] == ">>":
            print data["vars"][int(s_command[2])]

        # Test integer values
        if s_command[0] == "$testint" and s_command[1] == ">>":
            if s_command[3] in OPERATORS:
                print OPERATORS[s_command[3]](
                    int(s_command[2]),
                    int(s_command[4]))

        # Test string values
        if s_command[0] == "$teststr" and s_command[1] == ">>":
            if s_command[3] in OPERATORS:
                print OPERATORS[s_command[3]](
                    s_command[2],
                    s_command[4])

        # Test variable values
        if s_command[0] == "$testvar" and s_command[1] == ">>":
            if s_command[3] in OPERATORS:
                print OPERATORS[s_command[3]](
                    data["vars"][int(s_command[2])],
                    data["vars"][int(s_command[4])])

        # Terminate the program
        if s_command[0] == "$exit" and s_command[1] == ">>":
            exit(int(s_command[2]))

# Run the interpreter
if __name__ == "__main__":
    while True:
        interpreter(":")

Here's an example of a code file:

$out:>>:Hello world.
$inp:<<:[input]>

$assignint:<<:0:10
$assignint:<<:1:11

$return:>>:0
$return:>>:1

$testvar:>>:0:==:1
$testvar:>>:0:!=:1

$exit:>>:0

All I'm really looking for is a way to turn that ugly if/else chain into something prettier without changing the original syntax.


texts: User model with user roles in Codeigniter PHP/MySQL

texts:
I am building an app that currently allows the users to have 3 different roles:

Consumer
Merchant
Admin

I have three tables:

user (Name, email, password etc with a status=0/1)
user_role (The list of roles available)
user_user_role (The table joining users to user roles in a many to many relationship. Also a status column indicating if the role is disabled for the user.)

But only two models:

User_model
User_role_model

In my User_model:

/**
 * @param $user_data
 * @param array $roles
 * @return bool|object
 */
function insert( $user_data, $roles = [] ){
    // Hash password
    if ( isset( $user_data['password'] ) ) {
        $user_data['password'] = password_hash($user_data['password'], PASSWORD_DEFAULT);
    }
    if ( $user_id = $this->db->insert( $this->table_name, $user_data ) ) {

        // Add user roles
        if (count($roles)) {
            foreach ($roles as $role_id) {
                $this->add_role($user_id, $role_id);
            }
        }

        return $user_id;

    } else {
        return FALSE;
    }
}

/**
 * Add role to user
 * @param $user_id
 * @param $role_id
 */
function add_role( $user_id, $role_id ){
    $this->db->insert(self::User_user_role_table_name, [
        'user_id' => $user_id,
        'user_role_id' => $role_id,
        'status' => self::Status_active,
        'created_on' => NULL,
        'modified_on' => NULL
    ]);
}

My questions:

Is my database schema ideal? (Each role has access to a specific area with each area's controller extended from a core controller. i.e. Dashboard extends Admin_controller - which extends from a global controller. I don't foresee a need to have complex permissions in a typical RBAC.)
Should I have 1 model instead of 2?
Should I have the roles parameter in my insert function?


texts:
I have a single image of shape img.shape = (500, 439, 3)

The convolution function is

def convolution(image, kernel, stride=1, pad=0):

    n_h, n_w, _ = image.shape

    f = kernel.shape[0]
    kernel = np.repeat(kernel[None,:], 3, axis=0)
    kernel = kernel.transpose()

    n_H = int(((n_h + (2*pad) - f) / stride) + 1)
    n_W = int(((n_w + (2*pad) - f) / stride) + 1)
    n_C = 1

    out = np.zeros((n_H, n_W, n_C))

    for h in range(n_H):
        vert_start = h*stride
        vert_end = h*stride + f

        for w in range(n_W):
            horiz_start = w*stride
            horiz_end = w*stride + f

            for c in range(n_C):
                a_slice_prev = image[vert_start:vert_end,
                                     horiz_start:horiz_end, :]

                s = np.multiply(a_slice_prev, kernel)
                out[h, w, c] = np.sum(s, dtype=float)

    return out

The code for plotting is

img = plt.imread('cat.png')
kernel = np.arange(25).reshape((5, 5))
out2 = convolution(img, kernel)
plt.imshow(np.squeeze(out2))
plt.show()

The output seems to get a CYAN cover, is the logic of the code correct ?


texts: Join ArcGIS tables in Python of plant greenness in response to prior month's rainfall

texts:
I am using Python 3.8 with ArcGIS Pro 2.5. This code creates a joined table where I match values for plant greenness in the current month with rainfall X number of months into the past. Each loop iterates through about 600 files (the number of files in ws1 and ws2). The code works perfectly but slowly, taking approximately four hours to run. For my work (a grad student in plant biology) I will need to run this code multiple times.

I am interested in executing the first loop in parallel, however, I've been stumped about how to do so. Any advice about how to optimize this code to run in parallel (using the multiprocessing or other package) would be appreciated. I am using an 8-core 16-thread CPU.

Here is what the code does:

The code first iterates through ws1, which contains tables of plant greenness. The date is isolated from the file name, and then I create a new variable X months before this date. The second loop iterates through ws2, which contains tables of precipitation. Similarly, I isolate the date from the filename, and then create a new variable X months into the past. The final loop iterates through ws2 again and finds the historic filename that matches the one created in the second loop.

r from the first loop is associated with plant greenness at the current month, r2 is associated with precipitation at the current month, while r3 from the last loop is associated with historic precipitation. When the dates from all three loops match then I do the add join.

import arcpy, os, glob, datetime
arcpy.env.addOutputsToMap = 0
from datetime import datetime

ws1=glob.glob(r'D:\GIS_Files\NEW_LA_FULL_SERIES\ALL_DATA_2000_2020\CITY_POLYs\*.shp')
ws2 = glob.glob(r'D:\GIS_Files\NEW_LA_FULL_SERIES\ALL_DATA_2000_2020\PRECIP_preprocessed_2000_2020\CITY_ZONAL_TABLES\*.dbf')

for r in ws1:
    basename_BOUND = os.path.basename(r)[35:41]
    basename_BOUND1=str(basename_BOUND)
    D_POLY=datetime.strptime(basename_BOUND1,'%Y%m').date()
    from datetime import datetime
    import dateutil.relativedelta
    EARLIER_POLY=D_POLY-dateutil.relativedelta.relativedelta(months=2)
    STR_PREV_POLY="{:%Y%m}".format(EARLIER_POLY)
    print(STR_PREV_POLY)
    for r2 in ws2:
        basename_ZONAL=os.path.basename(r2)[12:18]
        basename_ZONAL1=str(basename_ZONAL)
        D_PRECIP= datetime.strptime(basename_ZONAL1,'%Y%m').date()
        from datetime import datetime
        import dateutil.relativedelta
        EARLIER_PRECIP=D_PRECIP-dateutil.relativedelta.relativedelta(months=2)
        STR_PREV_PRECIP="{:%Y%m}".format(EARLIER_PRECIP)
        for r3 in ws2:
            basename_FINAL=os.path.basename(r3)[12:18]
            print(basename_FINAL)
            if STR_PREV_POLY==STR_PREV_PRECIP:
                if STR_PREV_PRECIP==basename_FINAL:
                    result = arcpy.JoinField_management(in_data=r, in_field="GEO_id",join_table=r3, join_field="GEO_id", fields=["MEAN","STD"])[0]


texts: Calling a method outside class statically, passing other method's output as parameter

texts:
I have this class:

class adminTemplate {

    public static function load()
    {
        return new self();
    }

    public function sidebarGuide()
    {
        return 'content'; // Very long html markup
    }

    public function wrapSidebars($content)
    {
        ob_start();
        echo "
";
        echo $content;
        echo "
";
        $output = ob_get_contents();
        ob_end_clean();
        return $output;
    }

    // Other methods here

}

Somewhere in my script, I have to call wrapSidebars using sidebarGuide's output as parameter:

echo adminTemplate::load()->wrapSidebars(adminTemplate::load()->sidebarGuide());

It works, but I'm pretty confident there is a more appropriate way.

Is there a proper way of passing methods'output as other method's parameter in a class loaded "statically"?
Besides that, is there a more elegant code structure to accomplish the same "task"?


texts: Merge two list and discarding duplicates

texts:
I am trying to implement a function that merges two ordered lists into a third (ordered) one, but duplicates have to be discarded (basically the last step of a mergesort).

I think that this code can be generalized to an arbitrary number or lists, by keeping a list of indices, rather than 2 explicit ones.

def merge_no_duplicates(list_1, list_2):
    i = j = 0
    import collections
    result = collections.deque()

    while i < len(list_1) and j < len(list_2):
        if len(result) > 1 and list_1[i] == result[-1]:
            i += 1
            continue
        if len(result) > 1 and list_2[j] == result[-1]:
            j += 1
            continue

        if list_1[i] <= list_2[j]:

            result.append(list_1[i])
            i += 1
        elif list_2[j] < list_1[i]:
            result.append(list_2[j])
            j += 1

    # we still need to consume part of list_2
    if i == len(list_1):
        while j < len(list_2):

            if list_2[j] == result[-1]:
                j += 1
                continue

            result.append(list_2[j])
            j += 1

    # still need to consume part of list_1
    if j == len(list_2):
        while i < len(list_1):

            if list_1[i] == result[-1]:
                i += 1
                continue

            result.append(list_1[i])
            i += 1
    return result

Possible improvements: factor out the repetitive parts, for example by using something similar to this helper function:

check_duplicates(my_list, index):
    if my_list[index] == result[-1]:
        index += 1

Unfortunately this won't work (index is a parameter, and will not influence the behavior of i or j). Is this possible at all?


texts: Using jQuery 1.7 .on() and event.stopPropagation to close boxes when clicking in document body

texts:
I have the following code which works but seems like it could be improved. I'm not sure if I'm using event.stopPropagation() correctly or if it is the best solution.

The elements are loaded via AJAX and so need to have .on() (previously .live(), which is now deprecated in jQuery 1.7).

I've used the example given here as a basis.

$('html').on('click', '.poster:not(.active) .image-effect', function (event) {

        var obj = $(this).parent();

        // If there are no .close spans
        if (obj.find('.close').length === 0) {

            // Add the close element by javascript to remain semantic
            obj.find('.quick-view').append('&times;');
        }

        // Close any open Quick Views
        closeQuickView();

        // Add the active class (controls opacity)
        obj.addClass('active');

        // Fade in the Quick View
        obj.find('.quick-view').fadeIn(200, 'easeInOutQuint');

        event.preventDefault();
        event.stopPropagation();

    });

    $('html').on('click', '.active', function () {
        return false;
    });

    $('html').on('click', '.close', function () {
        closeQuickView();
    });

    $('html').on('click', '.quick-view', function (event) {
        event.stopPropagation();
    });

    // Close the QuickView with a button
    $('html').on('click', function () {
        closeQuickView();
    });

    function closeQuickView() {
        $('.poster').removeClass('active');
        $('.quick-view').fadeOut(200, 'easeInOutQuint');
    }

For some reason clicking the document isn't working in Chrome (the closeQuickView is not being called) which may be an indicator that the code is not functioning 100%.

My markup is as follows:

        Content

Is this the right way to approach the scenario? Are there any conflicting functions?


texts: Retrying a request using 'request' library without extra modules

texts:
I am using the request module and wanted to implement some retries for robustness. It seems excessive to use a whole new or extra module just to do a retries so I've put together the following as an exercise to retry requests using only the request library:

var checkUrl = function(url = 'http://localhost', retriesLeft = 0, timeoutMS = 3000) {
  var request = require('request');
  request(url, async function (error, response, body) {
    if (error) {
      if (retriesLeft > 0) {
        console.log(url + ' : not available yet');
        await sleep(timeoutMS);
        checkUrl(url, --retriesLeft);
      }
    } else {
      console.log(url + ' : URL is available');
    }
  });

}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

checkUrl('http://www.example.com/', 3, 5000);

Is this a reasonable approach? It seems to work. It's just a basic example - I've not considered redirects for instance.

Of course this can be wrapped up to make it easier to use and then, ironically, becomes a sort of module but it would not require pulling anything external.


texts: Unit Testing Express Middleware That Verifies Auth Tokens

texts:
I am writing an Express middleware component that'll run on Node 4, which has limited ES2015 support.

The fundamental purpose of this component is to verify JSON web tokens, using the jsonwebtoken module. Here is said component:

const jwt = require("jsonwebtoken");

module.exports = {
  ensureAuthenticated: function(req, res) {
    return new Promise(function(resolve, reject) {
      const token = req.query.token;
      if (!token) {
        return reject({
          status: 401
        });
      } else {
        jwt
          .verify(token, "secret", function(err, decoded) {
            if (err) {
              return reject({
                status: 401
              });
            } else {
              req.user = decoded;
              resolve();
            }
          });
      }
    });
  }
};

I also wrote some unit tests, using Mocha and Chai:

const chai = require("chai");
const proxyquire = require("proxyquire");
const httpMocks = require("node-mocks-http");

const expect = chai.expect;

suite("ensureAuthenticated", function() {

  test("should return 401 when token is \"undefined\"", function() {
    const sut = require("../../middleware");
    const req = httpMocks.createRequest();

    return sut
      .ensureAuthenticated(req)
      .catch(function(outcome) {
        expect(outcome.status).to.equal(401);
      });
  });

  test("should return 401 when token is invalid", function() {
    const jsonwebtoken = { };
    jsonwebtoken.verify = function(token, secret, cb) {
      cb({});
    };
    const req = httpMocks.createRequest({
      query: {
        token: "bar"
      }
    });
    const sut = proxyquire("../../middleware", {
      jsonwebtoken: jsonwebtoken
    });

    return sut
      .ensureAuthenticated(req)
      .catch(function(outcome) {
        expect(outcome.status).to.equal(401);
      });
  });

  test("should add decoded data to req object when token is valid", function() {
    const decoded = {
      username: "dummy username"
    };
    const jsonwebtoken = { };
    jsonwebtoken.verify = function(token, secret, cb) {
      cb(undefined, decoded);
    };
    const req = httpMocks.createRequest({
      query: {
        token: "dummy token"
      }
    });
    const sut = proxyquire("../../middleware", {
      jsonwebtoken: jsonwebtoken
    });

    return sut
      .ensureAuthenticated(req)
      .then(function() {
        expect(req.user).to.equal(decoded);
      });
  });
});

As you can see, the component returns a Promise, which makes it unit-testable. I got the idea from this talk.

I would please like to hear any thoughts you have about the quality of my tests. I am also interested in any general criticism.


texts:
I've created a voting system that's similar to Stack Exchange's in a Ruby on Rails web app. It's working great - as far as I can tell, all the edge cases are caught. This is the action to cast a vote.

There are some conditions I've had to satisfy:

must not allow duplicate voting, even from console requests
one vote per post (can't have an up and a down vote on the same post)
must be logged in

At the moment, I'm updating the record if there's already a vote by this user on this post, but I wonder if that's the most efficient strategy. Would destroying the old row and creating a new record be faster?

I'd particularly appreciate efficiency comments - at the moment, this is a very server heavy action, which I'd like to minimise.

def create
  post = (params[:post_type] == "a" ? Answer.find(params[:post_id]) : Question.find(params[:post_id]))
  existing = Vote.where(:post => post, :user => current_user)

  if existing.count > 0
    if existing.first.vote_type == params[:vote_type].to_i
      render :plain => "You have already voted.", :status => 409 and return
    else
      # There's already a vote by this user on this post, so we may as well update that instead of removing it.
      vote = existing.first
      vote.vote_type = params[:vote_type].to_i
      vote.save!

      state = { :status => "modified", :vote_id => vote.id }
      render :json => state and return
    end
  end

  vote = Vote.new
  vote.user = current_user
  vote.post = post
  vote.vote_type = params[:vote_type]
  vote.save!

  state = { :status => "OK", :vote_id => vote.id }
  render :json => state and return
end

(A quick note on vote types: the Vote.vote_type column has type integer, and the possible values are 0 (upvote) or 1 (downvote)).


texts: Can reverse it the input with less code than these? Java

texts:
So we ask to the user to enter 10 number and then we reverse it.

package *;
import java.util.Scanner;
public class * {
   // n = limit of inputs
   private static final int n = 10;
   static Scanner kb = new Scanner(System.in);
   public static void main(String[] args) {
     //nkb = number from keyboard
     int [] nkb = new int[n];
     // in = number of length
     int in = nkb.length;
     //for input user
     for (int i = 0; i < n; i ++){
       System.out.println("Writte a number: ");
       nkb[i] = kb.nextInt();
     }//end for
     for (int i = 0; i < n; i ++){
       System.out.println("In these position "+i+" now we have these number: "+nkb[in-1-i]);
     }//end for reverse
   }//end method
}//end class

It's possible to make it with less code?
I check already and they told me that we can use List<Integer> and call Collections.reverse()... but how?


texts: Converting an input string to a list of sub lists with numbers

texts:
I am learning Python 3. One thing I am doing to get some repetition is going through checkio. It is a website with coding exercises. One of the exercises gives an input string as follows:

str_to_nbrs("(2,2),(6,2),(2,6)")

str_to_nbrs("(3,7),(6,10),(9,7)")

I need the output of this code to produce a list of sub lists with the pairs of numbers so I can put them into variables to use for calculations.

This exercise actually has to do with x and y coordinates and circles. I am not sure why this input was in the form of a string. But, it gives me a chance to learn how to use the tools to convert a string like this to numbers that I can use in mathematical processes.

I figured out how to accomplish what I need. I am relatively new to Python 3. But, from what I have seen already, it is a well-thought-out and efficient language. I would bet there is a better way to do it with less code.

Please note that I added the big obvious comments to explain what the code is doing. They are not part of my regular coding style.

One more thing: I am still trying to come up with a convention for variable names. I have started lists with "l_". I try to give things meaningful names, but also try to keep them relatively short. I know "l_work" isn't a good name. But, I just wanted to finish that section of code, and used that...err...unimaginative name.

import re

# str_to_nbrs("(2,2),(6,2),(2,6)")

def str_to_nbrs(data):
    print("String input:")
    print(data)
    print()
    new_data = re.sub(r"\(","",data)
    new_data = new_data + ","

    print("Remove left parenthesis and add a comma a the end for split method:")
    print(new_data)
    print()

    l_data = new_data.split("),")
    l_data.pop()
    print("Reformatted string data in a list:")
    print(l_data)
    print()

    l_work = []
    l_nbrs = []
    l_all = []

    for i in l_data:
        l_work = i.split(",")
        for j in l_work:
            l_nbrs.append(int(j))
        l_all.append(l_nbrs)
        l_nbrs = []
    print("Integers in sub lists:")
    print(l_all)
    print()
    print("---------------------")
    print()

str_to_nbrs("(2,2),(6,2),(2,6)")
str_to_nbrs("(3,7),(6,10),(9,7)")


texts: Getting list from an Oracle database and storing it in an object

texts:
I have two admin groups - VCS, and VPN. For each group, I need to get the list of all the people in that group, along with their IDs.

What is the best way to do this?  Could you please suggest if it is good enough?

Also, should I use a map to store the data instead of creating a new object GetAdminInfo?

public class GetAdminInfo
{
private List<String> persons;
private List<String> personIds;

public List<String> getPersonIds() {
    return personIds;
}
public void setPersonIds(List<String> personIds) {
    this.personIds = personIds;
}

public List<String> getPersons() {
    return persons;
}
public void setPersons(List<String> persons) {
    this.persons = persons;
}
}

This is the method I have written in my DAO class.

public static GetAdminInfo fetchPersonIdInfo(String adminGroup) throws SQLException
{
    GetAdminInfo personInfo =null;
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet rs = null;
    List<String> personId = new ArrayList<String>();
    List<String> persons = new ArrayList<String>();
    try {
        connection = createConnection();
        statement = connection.prepareStatement("SELECT PERSON_ID,PERSONS FROM ADMIN_INFO WHERE ADMINGROUP = ?");
        statement.setString(1, adminGroup);
        rs = statement.executeQuery();
        if(rs.next())
        {
            personInfo = new GetAdminInfo();
            adminGroup = rs.getString(COLUMN_ADMINGROUP)!=null?rs.getString(COLUMN_ADMINGROUP):"";
            personId.add(rs.getString(1));
            persons.add(rs.getString(1));
            personInfo.setDeviceIds(deviceId);
            personInfo.setPersonIds(personId);
        }

    } finally{
        rs.close();
        conn.close();
        statement.close();
    }

    return personInfo;
}


texts: An asynchronous solution to send validation email

texts:
I intend to send validating message to User's email to complete a registration  with the following codes:

def register(request):
    """1. register a new user
       2. generate activating code
       3. send validating email
       4. prompt to check activating email.
    """
    if request.method == "GET":
        form = UserForm()
    if request.method == "POST":
        form = UserForm(request.POST)
        print(vars(form))
        if form.is_valid():
            #1. Create User and save to sever
            user = User.objects.create_user(
                      form.cleaned_data['username'],
                      first_name=form.cleaned_data['first_name'],
                      last_name=form.cleaned_data['last_name'],
                      email=form.cleaned_data['email'],
                      password=form.cleaned_data['password'])
            user.is_active = False
            user.save()

            #2. Create activate code and save to server.
            uuid_code = str(uuid.uuid4()).replace("-", '')
            activate_code = ActivateCode(user=user, code=uuid_code)
            activate_code.save()

            #3. Send Validation Email
            activate_link = "http://%s/user/activate/%s" %(request.get_host(), uuid_code)
            activate_message = """\
            You're almost done!
            Click here to complete your registration
            """ % activate_link
            send_mail(subject="Complete Registration With Code Journey",
                      message="Click here to complete your registration: %s" %activate_link,
                      html_message=activate_message,
                      from_email="anexmaple@mail.com",
                      recipient_list=[form.cleaned_data['email'],],
                      fail_silently=False)

           #4. Prompt user to check his email.
            context = {'email': form.cleaned_data['email'],}
            return render(request, "user/validate.html", context)

The problem is that the user/validate.html feedbacks to me very slowly after formulated form was submittd.
I guess it's send_email consuming lots of my patience.

How could I implement step 4 in advance  which immediately show prompt message then send mail unhurried.


texts: Taking the sum and average of the keyboard inputs

texts:
I have an assignment as follows:

  Write a program where you can enter from the keyboard up to 10
  integers. If the number entered is equal to -99, stop reading numbers
  from the keyboard and compute the average and sum of all values
  (excluding -99). Print the average on the screen. Make sure you
  consider all the cases: less than 10 or exactly 10 numbers can be
  entered. After the numbers have been entered you need to make sure
  that the average is computed then.

I came up with the program below. Do you think my program is fine? What could be alternative solutions?

s = 0
for i in range(1, 11):
    a=int(input("Enter a number: "))
    if a==-99:
        s = s+a
        print("The sum of the numbers that you've entered excluding -99:",s-a) # minus a because we want to exclude -99
        print("The average of the numbers that you've entered excluding -99:",(s-a)/(i-1)) # minus a because we want to exclude -99. i-1 in denominator because we excluded -99 from the sum.
        break
    else:
        s = s+a
        print("The sum of the number(s) that you've entered:",s)
        print("The average of the number(s) that you've entered:",s/i)
        continue
input("Press enter to close")


texts: Checking whether a grade combination exists

texts:
Below function checks if a grade exists

  ----------------------------------------------------------------------------
  -- CHECK IF THE VALUES WE PASSED AS PARAMETERS EXISTS AS A ONE ROW RECORD IN THE TABLE
  ----------------------------------------------------------------------------
  function record#exists(
    i_math_grade              pls_integer
   ,i_science_grade           pls_integer
   ,i_english_grade           pls_integer
   ,i_music_grade             pls_integer
   ,i_average                 pls_integer
  )
  return boolean
  is
    l_cnt                     pls_integer;
  begin
    begin
      select count(*)
      into   l_cnt
      from   grade
      where  math_grade    = i_math_grade
        and  science_grade = i_science_grade
        and  english_grade = i_english_grade
        and  music_grade   = i_music_grade
        and  average       = i_average;
    exception
      when no_data_found then
        return false;
    end;

    return l_cnt > 1;

  exception
    when others then
      raise_fa_err('record#exists');
  end record#exists;


texts: Pixel bit-wise LSB extraction to byte array

texts:
I wrote the following code below to extract the least significant bit (LSB) of each pixel and store it into a byte[] array. I was wondering if Java has a more efficient way to do this?

Right now, I am looping over every pixel, extracting the LSB, and updating the current byte by shifting it to the left and adding the LSB. When a byte is filled up, the next byte is then set as the current one. The process is repeated until all pixels' LSBs have been extracted and fed into the byte array.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] pixels = new int[] {
            0xFFFF0000, 0xFFFF0001, 0xFFFF0000, 0xFFFF0001,
            0xFFFF0000, 0xFFFF0001, 0xFFFF0001, 0xFFFF0001,
            0x00000001, 0x00000000
        };
        // Result should be 3 bytes [0101 (5), 0111 (7), 10 (2)]
        System.out.println(Arrays.toString(extractLSB(pixels)));
    }

    public static byte[] extractLSB(int[] pixels) {
        int pixelCount = pixels.length;
        int numberOfBytes = (int) Math.ceil(pixelCount / 4.0);
        int extraBits = pixelCount % 4;
        int overflowIndex = pixelCount - extraBits;
        int currByteIndex = 0;
        int currByteValue = 0;
        byte[] byteBuffer = new byte[numberOfBytes];

        for (int i = 0; i < pixelCount; i++) {
            int currPixel = pixels[i];
            int bitIndex = i % 4;
            int bit = currPixel & 1;

            currByteValue |= bit;

            if (i > overflowIndex && bitIndex == extraBits - 1) {
                byteBuffer[currByteIndex] = (byte) currByteValue;
            } else if (bitIndex < 3) {
                currByteValue <<= 1;
            } else if (bitIndex == 3) {
                byteBuffer[currByteIndex++] = (byte) currByteValue;
                currByteValue = 0;
            }
        }

        return byteBuffer;
    }
}


texts:
I'm trying to figure out whether I can speed up passing large int and float lists to my foreign function:

from ctypes import cdll, c_uint32, c_float, Structure, c_void_p, cast, c_size_t, POINTER

lib = cdll.LoadLibrary('whatever.dylib')

class _BNG_FFITuple(Structure):
    _fields_ = [("a", c_uint32),
                ("b", c_uint32)]

class _BNG_FFIArray(Structure):
    _fields_ = [("data", c_void_p),
                ("len", c_size_t)]
    # Allow implicit conversions from a sequence of 32-bit unsigned
    # integers.
    @classmethod
    def from_param(cls, seq):
        return seq if isinstance(seq, cls) else cls(seq)

    # Wrap sequence of values. You can specify another type besides a
    # 32-bit unsigned integer.
    def __init__(self, seq, data_type = c_float):
        array_type = data_type * len(seq)
        raw_seq = array_type(*seq)
        self.data = cast(raw_seq, c_void_p)
        self.len = len(seq)

# A conversion function that cleans up the result value to make it
# nicer to consume.
def _bng_void_array_to_tuple_list(array, _func, _args):
    res = cast(array.data, POINTER(_BNG_FFITuple * array.len))[0]
    res_list = [(i.a, i.b) for i in iter(res)]
    drop_bng_array(array)
    return res_list

convert_bng = lib.convert_to_bng_threaded
convert_bng.argtypes = (_BNG_FFIArray, _BNG_FFIArray)
convert_bng.restype = _BNG_FFIArray
convert_bng.errcheck = _bng_void_array_to_tuple_list

This means I can call convert_bng with two lists, like so:

convert_bng(float_list, another_float_list)

and get a list of int tuples back. But I'm wondering whether I can send the _BNG_FFIArrays by reference instead, and whether that will be faster (I'm obviously consuming them on the C side, but not changing their values).


texts:
Check if all leaves are at same level. This question is attributed to geek for geeks. Looking for code-review, optimization and best practices.

public class LeavesLevel<T> {

    private TreeNode<T> root;

    public LeavesLevel(List<T> items) {
        create (items);
    }

    private void create (List<T> items) {
        root = new TreeNode<>(items.get(0));

        final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode<T> current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (items.get(left) != null) {
                    current.left = new TreeNode<T>(items.get(left));
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode<T>(items.get(right));
                    queue.add(current.right);
                }
            }
        }
    }

    private static class TreeNode<T> {
        private TreeNode<T> left;
        private T item;
        private TreeNode<T> right;

        TreeNode(T item) {
            this.item = item;
        }
    }

    public boolean refurbish() {
        return recurse (root, 0,  new NodeDepth(-1));
    }

    private static class NodeDepth {
        private int depth;
        NodeDepth(int depth) {
            this.depth = depth;
        }
    }

    public boolean recurse(TreeNode<T> node, int leafLevel, NodeDepth nodeDepth) {
        if (node == null) {
            return true;
        }

        if (node.left == null && node.right == null) {
           if (nodeDepth.depth == -1) {
               nodeDepth.depth = leafLevel;
               return true; // if tree contains a single leaf node, then
           }
           return leafLevel == nodeDepth.depth;
        }

        return recurse (node.left, leafLevel + 1, nodeDepth) && recurse (node.right, leafLevel + 1, nodeDepth);
    }
}

public class LeafLevelTest {

    @Test
    public void test1() {
        /**
         *
         *           12
                   /    \
                 5       7
               /          \
              3             1
         *
         */
        LeavesLevel<Integer> ll1 = new LeavesLevel<>(Arrays.asList(1, 5, 7, 3, null, null, 1));
        assertTrue(ll1.refurbish());
    }

    @Test
    public void test2() {
        /**
         *       12
                /    \
              5       7
             /
            3
         *
         */
        LeavesLevel<Integer> ll2 = new LeavesLevel<>(Arrays.asList(1, 5, 7, 3));
        assertFalse(ll2.refurbish());
    }

    @Test
    public void test3() {
        /**
         *
         *
                    12
                    /
                  5
                /   \
               3     9
              /      /
             1      2
         *
         *
         */
        LeavesLevel<Integer> ll3 = new LeavesLevel<>(Arrays.asList(1, 5, null, 3, 9, null, null, 1, null, 2));
        assertTrue(ll3.refurbish());
    }

}


texts: Arduino code to control motor speed based on MPU-6050 sensor

texts:
I have been trying to create arduino code where my MPU6050 reads its angle and based on that angle, change the motor speed. For example, 45° is the max motor speed, 22° is roughly half speed, and so on.

I have a 5065 200kv brushless motor going to a ESC with a bec which I can attach to the Arduino. I have modified some self-balancing drone code from a tutorial that used a proportional-integral-derivative controller. What I want to do is take out the PID and do a comparison: if the angle is between 5° and 45° then servo write (angle × 44), because if I multiply the maximum angle by 44 I will get around 2000, which is the original top speed of the code. Although mine can go faster, and I will change it later after testing. I am fairly new with Arduino and I have not used the MPU6050 before.

#include <Wire.h>
#include <Servo.h>

Servo right_prop;

int16_t Acc_rawX, Acc_rawY, Acc_rawZ,Gyr_rawX, Gyr_rawY, Gyr_rawZ;

float Acceleration_angle[2];
float Gyro_angle[2];
float Total_angle[2];

float elapsedTime, time, timePrev;
int i;
float rad_to_deg = 180/3.141592654;

double throttle=0; //initial value of throttle to the motors

void setup() {
  Wire.begin(); //begin the wire comunication
  Wire.beginTransmission(0x68);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(250000);

 right_prop.attach(3);

  time = millis();
}
void loop() {

/////////////////////////////I M U/////////////////////////////////////
    timePrev = time;
    time = millis();
    elapsedTime = (time - timePrev) / 1000;

     Wire.beginTransmission(0x68);
     Wire.write(0x3B);
     Wire.endTransmission(false);
     Wire.requestFrom(0x68,6,true);

     Acc_rawX=Wire.read()<<8|Wire.read();
     Acc_rawY=Wire.read()<<8|Wire.read();
     Acc_rawZ=Wire.read()<<8|Wire.read();

     Acceleration_angle[0] = atan((Acc_rawY/16384.0)/sqrt(pow((Acc_rawX/16384.0),2) + pow((Acc_rawZ/16384.0),2)))*rad_to_deg;
     /*---Y---*/
     Acceleration_angle[1] = atan(-1*(Acc_rawX/16384.0)/sqrt(pow((Acc_rawY/16384.0),2) + pow((Acc_rawZ/16384.0),2)))*rad_to_deg;

   Wire.beginTransmission(0x68);
   Wire.write(0x43); //Gyro data first adress
   Wire.endTransmission(false);
   Wire.requestFrom(0x68,4,true); //Just 4 registers

   Gyr_rawX=Wire.read()<<8|Wire.read();
   Gyr_rawY=Wire.read()<<8|Wire.read();

   /*---X---*/
   Gyro_angle[0] = Gyr_rawX/131.0;
   /*---Y---*/
   Gyro_angle[1] = Gyr_rawY/131.0;

   /*---X axis angle---*/
   Total_angle[0] = 0.98 *(Total_angle[0] + Gyro_angle[0]*elapsedTime) + 0.02*Acceleration_angle[0];
   /*---Y axis angle---*/
   Total_angle[1] = 0.98 *(Total_angle[1] + Gyro_angle[1]*elapsedTime) + 0.02*Acceleration_angle[1];

    Serial.println(Total_angle[1]);

if( Total_angle[1]> 5 && Total_angle[1]< 45)
{
right_prop.write(Total_angle[1]*44);
}
else{
right_prop.write(0);
}
}

//end of loop void


texts: Securely shuffling an array with 75 numbers in Go

texts:
I have a SHA512 hex string consisting of my random input and that of the user.

Since rand.Seed only accepts a int64 I can never generate enough possibilities to shuffle an array with numbers 1-75: 75! = 2.480914e+109.

So my plan was to loop over the hex string 11 times, each time converting 10 hex characters to decimal and keep on shuffling the numbers.

func Shuffle(t []int, hex string) {
    for j := 0; j < 11; j++ {
        shuffleSeed, _ := strconv.ParseInt(hex[j*10:(j+1)*10], 16, 64)
        rand.Seed(shuffleSeed)
        for i := 1; i < len(t); i++ {
            r := rand.Intn(i + 1)
            if i != r {
                t[r], t[i] = t[i], t[r]
            }
        }
    }
}

items := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
    31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
    46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
    61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75}

hex := "099b5721eaa9b5bcd87a07366aa175a1fb5b6fa6e5671b93ef443df927474198ec2ae959928f95c46f9fe9621575aa4e1e6f70780b059044da17737fcc99a322"
Shuffle(items, hex)

What do you think about this? I'm not a cryptography expert, not a math expert and certainly not a Go expert (I started yesterday).

Taken from another post I shuffled an array with [1,2,3] and here are the occurrences of each after 1 million times:

167136
166403
166877
166520
166925
166145


texts: Laravel - Add different style to type of product

texts:
I'm working on a project where I have products. Each product can either be a theme, plugin or a plan. Now my idea was to add different styles to each of the types. For instance, Theme is red, Plugin is blue etc... Now in my blade file I have handled this in the following way:

@if($product->productable_type == "App\Theme")
{{ $product->productable_type  }}
@elseif($product->productable_type == "App\Plugin")
{{ $product->productable_type  }}
@else
{{ $product->productable_type  }}
@endif

But is this the best way to handle these kinds of situations? It does not look clean at all. What is the best way to handle this?

The product DB looks like this.:

Products
    - id
    - productable_type (Either "App\Theme" or "App\Plugin" etc...)
    - productable_id
    - name
    - description
    - etc...

Thanks in advance!