texts: Computing the square root of a 64-bit integer

texts:
When sieving primes up to some 64-bit number n I need to determine an upper bound for the greatest potential factor of n, which is the greatest integer that is not greater than the (true) square root of n.

Computing this as std::sqrt(double(n)) is fraught with pitfalls. The standard IEEE double has only 53 bits in its significand, which means that some rounding is often inevitable. One consequence is that the result cannot safely be converted to uint32_t even though the true result could never exceed 32 bits. For example, sqrt(double(uint64_t(0) - 1)) usually rounds up to \$2^{32}\$ and if that is cast to uint32_t then the result becomes 0.

Currently I'm using a function like this:

uint32_t max_factor32 (uint64_t n)
{
   double r = std::sqrt(double(n));

   if (r < UINT32_MAX)
   {
      uint32_t r32 = uint32_t(r);

      return r32 - (uint64_t(r32) * r32 > n);
   }

   return UINT32_MAX;
}

Obviously, this works only if the value returned by sqrt() is reasonably close to the true result, so that the cast to integer yields either the desired result or a number that is exactly one greater.

I think this code should be reasonably safe, even in the face of floating-point hardware/software operating with unknown rounding modes and at an unknown level of strictness. But is that truly so?

Different rounding modes should not affect the correctness of the function, but what about different compiler settings for optimisation and floating point strictness? It seems to me that normally a compiler should only err on the side of excess precision by not rounding intermediate results to IEEE double, in which case my code should work fine as it is. Can different compiler switches throw a monkey wrench into my scheme or is the code safely portable to worlds and compilers unknown?

P.S.: what I want to avoid is the 'tail wagging the dog' style caveats like "this code works only with a strictly-conforming compiler and with strict floating-point precision enabled". On the other hand, if the function max_factor32() were to mess up quietly then the result of the containing program would likely be wrong, and even crashes are possible in cases like the above example where 0 is returned when the true result would be UINT32_MAX.


texts:
I'm implementing a "live analytics" feature and I need to always keep track of the last N items that were added to a collection so I figured I'd make a circular buffer since I couldn't find one.

I tried to figure out to use Interlocked but couldn't find out how to use Increment or CompareExchange in an obviously correct way - so I took the lock.

Review/advice is appreciated.

public class CircularBuffer<T>
{
    private readonly T[] _data;
    private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
    private int _i = 0;
    private bool _isOneCycleFinished = false;
    private readonly int _size;

    public CircularBuffer(int size)
    {

        if (size < 0)
        {
            throw new ArgumentException($"{nameof(size)} cannot be negative");
        }
        _i = 0;
        _data = new T[size];
        _size = size;
    }

    public IEnumerable<T> Latest()
    {
        try
        {
            _lock.EnterReadLock();
            if (!_isOneCycleFinished)
            {
                return _data.Take(_i).ToList();
            }
            return _data.Concat(_data).Skip(_i).Take(_size).ToList();
        }
        finally
        {
            _lock.ExitReadLock();
        }
    }

    public void Add(T t)
    {
        try
        {
            _lock.EnterWriteLock();
            _i = (_i + 1)%_size;
            if (!_isOneCycleFinished && _i == 0)
            {
                _isOneCycleFinished = true;
            }
            _data[_i] = t;
        }
        finally
        {
            _lock.ExitWriteLock();
        }
    }
}


texts: Modular arithmetic brute-force congruence finder

texts:
My full code is running too slow. I do profile.run to my project and found out this function consumes a lot of time.

The main problem is just to return an array containing all \$x\$ satisfying both of these equations with some large primes like \$23857201\$.

$$(x^3+v) \mod P = 0$$

$$(3xx + 3hx + h^2) \mod P = 0$$

     def afind(h,v):
        p=[]
        for x in range(23857201):
           if (x**3+v) % 23857201 == 0 and (3*x*x+3*h*x+h**2)*h%23857201==0:
              p.append(x)
     return p

It took 21.69 sec for afind(1,940). I tried Cython, but it didn't help. How can I speed this up?


texts: generate a 2d array that could be used to create an image with Java

texts:
This Python code
im_data = np.ones((100,100))
im_data[20:50,20:50]=np.zeros((30,30))

can generate a 2d array that could be used to create an image
plt.axis('off')
axi = plt.imshow(im_data, cmap='Greys')

I'm trying to do the same job with Java
class Arr100{
    public static void main(String[] args){
        System.out.println("H");
        int[][] arr = new int[100][100];
        for(int i=0; i<arr.length; i++){
            for (int j=0; j<arr[i].length; j++){
                arr[i][j]=1;
            }
        }
        for(int i=20; i<50; i++){
            for (int j=20; j<50; j++){
                arr[i][j]=0;
            }
        }
    }
}

In terms of GPU and memory, is there a better way to do the same thing?


texts:
I just solved the Hash Tables: Ransom Note problem on Hackerrank using both Java-8 and Java-7.  Given m words in a magazine and the n words in the ransom note, print Yes if a kidnapper can replicate his ransom note exactly (case-sensitive) using whole words from the magazine; otherwise, print No.  1 ≤ m, n ≤ 30000.

I am looking for suggestions regarding the efficiency, coding style and if this is the best way to solve this kind of problem.

Java-7

public class RansomeNotesJava7 {

    public static void main(String[] args) throws Exception{
        Scanner in = new Scanner(new File("input.txt"));
        int m = in.nextInt();
        int n = in.nextInt();
        String magazine[] = new String[m];
        for(int magazine_i=0; magazine_i < m; magazine_i++){
            magazine[magazine_i] = in.next();
        }
        String ransom[] = new String[n];
        for(int ransom_i=0; ransom_i < n; ransom_i++){
            ransom[ransom_i] = in.next();
        }

        if(getRansom(m,n,magazine,ransom))
            System.out.println("Yes");
        else
            System.out.println("No");
    }

    private static boolean getRansom(int m, int n, String[] magazine, String[] ransom) {

        if(m < n)
            return false;

        Map<String, Long> magazineMap = getFrequencyMapFromArray(magazine); //Arrays.stream(magazine).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        Map<String, Long> ransomMap =  getFrequencyMapFromArray(ransom); //Arrays.stream(ransom).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(magazineMap);
        System.out.println(ransomMap);

        for(String key : ransomMap.keySet()){
            if(!magazineMap.containsKey(key))
                return false;

            if(magazineMap.get(key) < ransomMap.get(key))
                return false;
        }

        return true;

    }

    private static Map<String, Long> getFrequencyMapFromArray(String[] arr) {

        Map<String, Long> map = new HashMap<>();

        for(String key : arr){
            if(map.containsKey(key))
                map.put(key, map.get(key)+1);
            else
                map.put(key, new Long("1"));
        }
        return map;
    }
}

Java-8

public class RansomNotes {

    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        int m = in.nextInt();
        int n = in.nextInt();
        String magazine[] = new String[m];
        for (int magazine_i = 0; magazine_i < m; magazine_i++) {
            magazine[magazine_i] = in.next();
        }
        String ransom[] = new String[n];
        for (int ransom_i = 0; ransom_i < n; ransom_i++) {
            ransom[ransom_i] = in.next();
        }

        if (getRansom(m, n, magazine, ransom))
            System.out.println("Yes");
        else
            System.out.println("No");
    }

    private static boolean getRansom(int m, int n, String[] magazine, String[] ransom) {

        if (m < n)
            return false;

        Map<String, Long> magazineMap = getFrequencyMapFromArray(magazine);
        Map<String, Long> ransomMap = getFrequencyMapFromArray(ransom);
        System.out.println(magazineMap);
        System.out.println(ransomMap);

        return (ransomMap.entrySet().stream()
                .filter(i -> (!magazineMap.containsKey(i.getKey()) || magazineMap.get(i.getKey()) < i.getValue()))
                .count() == 0);

    }

    private static Map<String, Long> getFrequencyMapFromArray(String[] arr) {

        return Arrays.stream(arr)
                     .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    }

}


texts: Fastest conversion of ISO 8601 string into javascript Date object

texts:
On StackOverflow I got a great answer to a question I had about creating a Date object from an ISO 8601 string with the ability to reposition into local time.

From there I wanted to see if I could make it any faster. We process a ton of dates in batches of 10,000 or more sometimes on slow phones.

This is the best I could do.

const isoToDate = (iso8601, ignoreTimezone = false) => {
  // Differences from default `new Date()` are...
  // - Returns a local datetime for all without-timezone inputs, including date-only strings.
  // - ignoreTimezone processes datetimes-with-timezones as if they are without-timezones.
  // - Accurate across all mobile browsers.  https://stackoverflow.com/a/61242262/25197

  const dateTimeParts = iso8601.match(
    /(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:([+-])(\d{2}):(\d{2}))?)?/,
  );

  // Create a "localized" Date.
  // If you create a date (without specifying time), you get a date set in UTC Zulu at midnight.
  // https://www.diigo.com/0hc3eb
  const date = new Date(
    dateTimeParts[1], // year
    dateTimeParts[2] - 1, // month (0-indexed)
    dateTimeParts[3] || 1, // day
    dateTimeParts[4] || 0, // hours
    dateTimeParts[5] || 0, // minutes
    dateTimeParts[6] || 0, // seconds
    dateTimeParts[7] || 0, // milliseconds
  );

  const sign = dateTimeParts[8];
  if (sign && !ignoreTimezone) {
    const direction = sign === '+' ? 1 : -1;
    const hoursOffset = dateTimeParts[9] || 0;
    const minutesOffset = dateTimeParts[10] || 0;
    const offset = direction * (hoursOffset * 60 + minutesOffset * 1);
    date.setMinutes(date.getMinutes() - offset - date.getTimezoneOffset());
  }

  return date;
};

It's about double the speed of the SO answer and 4-6x faster than moment.js and date-fns packages.

The key difference is a single regex that returns all the matching groups at once.

Here's a regex101 with some examples of it matching/grouping.

Is there anything obvious that can be improved upon here?  Thanks!


texts: Bash script to reconfigure the screen orientation when entering or exiting tablet mode

texts:
I'm writing a bash script for my tablet laptop to flip the screen depending on a file in Manjaro Linux. My current script is the following:

while true
do
    state=$(cat /sys/devices/platform/thinkpad_acpi/hotkey_tablet_mode) #This file indicates if it's in tablet mode or not
    if [[ $state == 0 && $oldState == 1 ]]
    then
        xrandr --output LVDS1 --rotate normal
        xsetwacom --set "$a" Rotate none
        xsetwacom --set "$b" Rotate none
        xsetwacom --set "$c" Rotate none
        oldState=0
    elif [[ $state == 1 && $oldState == 0 ]]
    then
        xrandr --output LVDS1 --rotate inverted
        xsetwacom --set "$a" Rotate half
        xsetwacom --set "$b" Rotate half
        xsetwacom --set "$c" Rotate half
        oldState=1
        /home/eto/scripts/backlight 0
    fi
    sleep 1s
done

The code in the if statements don't matter, but what I'm worried about is the entire logic of how it checks the tablet mode. Is there a better way to check the tablet mode indicator file rather than a while loop? I feel like this is a very inefficient way of doing so as it reads the disk quite frequently, but I don't see how else I could approach this. Any input is appreciated as I'm very much an amateur with coding.


texts: Better way to achieve looped output result

texts:
I have 4 variables - say A, B, C and D

Each variable can have 4 values - say 1, 2, 3 and 4

I need to generate all possible combinations of values

Example of Expected Output:

 A B C D
---------
 1 1 1 1
 1 1 1 2
 1 1 1 3
 1 1 1 4
 1 1 2 1
 1 1 2 2
 1 1 2 3
 .
 .
 .
 4 4 4 1
 4 4 4 2
 4 4 4 3
 4 4 4 4

I have wrote following loop

for ($A = 1 ; $A < 5 ; $A++){
 for ($B = 1 ; $B < 5 ; $B++){
  for ($C = 1 ; $C < 5 ; $C++){
   for ($D = 1 ; $D < 5 ; $D++){
    echo $A.$B.$C.$D;
   }
  }
 }
}

Is there any faster or better way to achieve above result?


texts:
I wrote a function that basically works like sprintf, but instead returns the formatted string (std::string). I haven't worked on this long, and I'm aware there are tons of improvements that could be made (alloc/realloc perhaps?). I was just looking for some advice before taking the next step.

GLOBAL string format(const string& format, ...)
{
    LOCAL const size_t initialSize = 64;

    string returnVal;

    char buffer[initialSize];
    int length;

    va_list args;

    va_start(args, format);
    {
        length = vsnprintf(buffer, initialSize, format.c_str(), args);
    }
    va_end(args);

    char bufferCorrectSize[length];

    va_start(args, format);
    {
        vsnprintf(bufferCorrectSize, length + 1, format.c_str(), args);
    }
    va_end(args);

    return bufferCorrectSize;
}

Ignore GLOBAL and LOCAL. They are just aliases for static I defined for organization.


texts: Check whether '.' and '/' are escaped properly

texts:
I'm currently using a function to check if a URL has correctly escaped two different characters: . and /.
To escape a character within a string, it requires 2 preceding \'s in the string (i.e.: \\. or \\/).
Here is the code I'm currently using. As you can see I'm matching the string with some regex, and then for every element returned I check if the first character of the string is \.
I feel this could be simplified, how can I make this better and avoid looping through all elements returned by match?

function isValidEscapedString(value) {
  return (value.match(/.?[./]/g)||[]).every((escape) => escape[0] === '\\');
}

console.log(isValidEscapedString('')); // true
console.log(isValidEscapedString('https://stackoverflow.com')); // false
console.log(isValidEscapedString('https:\/\/stackoverflow\.com')); // false
console.log(isValidEscapedString('https://stackoverflow\\.com')); // false
console.log(isValidEscapedString('https:\\/\\/stackoverflow\\.com')); //true

The examples in the code are working as intended.


texts: Hackerrank Submission Optimisation for Melodious Password

texts:
Given question from Hackerrank:

a password consists of exactly n lowercase English letters.
the password is melodious, meaning that consonants can only be next to
vowels and vowels can only be next to consonants. Example: bawahaha
the password cannot contain the letter y (because it's both a
consonant and vowel).
the first letter of the password can be either
a vowel or consonant.

Given the length, n, of the password,

print all of the possible passwords that meet the conditions above.

Input Format

The line of input contains the integer  (the length of the password).

Constraints

Output Format

Print each of the possible passwords, one per line. The order of the passwords does not matter.

My Code in Python:

import sys
import itertools

n = int(raw_input().strip())

consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z']
vowels = ['a', 'e', 'i', 'o', 'u']

test4 = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z', 'a', 'e', 'i', 'o', 'u']
answer = set(itertools.product(test4, repeat=n))

for letters in answer:
    for j in xrange(len(letters)):
        flag = 1
        if j != len(letters) - 1:
            if letters[j] in vowels and letters[j+1] in vowels:
                flag = 0
                break
            if letters[j] in consonants and letters[j+1] in consonants:
                flag = 0
                break

    if flag:
        for j in letters:
            sys.stdout.write(j)
        print ""

Can this code be optimized in any way?


texts:
I've been working on a configurable tool that finds files by a certain specification and returns a list. I attempted to approach this in a more LINQ way and tried using appropriate design decisions, all while keeping it reasonably efficient.

Here is my Finder class:

public class Finder
{
    public List<string> Extensions;
    public List<string> TargetDirectories;
    public bool Recursive { get; set; }

    private string _currentPath;
    private List<string> _files = new List<string>();

    public Finder()
    {
        Extensions = new List<string>();
        TargetDirectories = new List<string>();

        _currentPath = Directory.GetCurrentDirectory();
    }

    public string[] GetFiles()
    {
        if (_files.Count != 0)
            return _files.ToArray();
        return new string[0];
    }

    public void Find()
    {
        try
        {
            foreach (var directory in TargetDirectories)
            {
                Search(directory);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

    private void Search(string path)
    {
        var pathPoint = new DirectoryInfo($"{_currentPath}{path}");
        var files = Directory.EnumerateFiles(pathPoint.FullName, "*.*")
            .Where(s => Extensions.Contains(Path.GetExtension(s)))
            .ToList();
        files.ForEach(_files.Add);

        if (Recursive)
        {
            var subDirectories = Directory.GetDirectories(pathPoint.FullName);
            foreach (var subDir in subDirectories)
            {
                Search($"{path}/{new DirectoryInfo(subDir).Name}");
            }
        }
    }
}

And here's the usage:

var finder = new Finder();
finder.Extensions.Add(".cs");
finder.Extensions.Add(".dll");
finder.TargetDirectories.Add("/src");
finder.TargetDirectories.Add("/assembly");
finder.Recursive = true;
finder.Find();

foreach (var file in finder.GetFiles())
{
    Console.WriteLine(file);
}

The Output

It returns all of the files within every folder of /src and /assembly. If I change Recursive to false or omit it, the result will be only the files within the targeted directories. Extensions are also specified to retrieve files only of that type.

Here's what the output looks like:

/long/path/name/src/helloworld.cs
/long/path/name/src/class.cs
/long/path/name/src/subdirectory/anotherclass.cs
/long/path/name/assembly/library.dll

This is the intended return.

Design

I store the directory information so I can scale that information and use fields like Name and FullName. The files for specifically that searched directory are inserted into a list and allocated to a returnable list. The return list, _files, is publicly immutable.

Efficiency

I'm unsure if there's any notable difference between using the LINQ in my Search method or using a for loop for iteration in terms of performance. I also believe there might be a way I can simply use the EnumerateFiles return array without converting to a list then back to an array when using GetFiles().

Any suggestions on how I can improve my class? I'm trying to better my C# knowledge and program; any feedback would be considerably helpful and will assist me in further implementing features.

EDIT:
I am adopting suggestions actively. You can see the (amateur) repository here:
https://github.com/TGibsonn/FastCompile


texts:
Problem statement

  The Utopian tree goes through 2 cycles of growth every year. The first
  growth cycle occurs during the monsoon, when it doubles in height. The
  second growth cycle occurs during the summer, when its height
  increases by 1 meter.  Now, a new Utopian tree sapling is planted at
  the onset of the monsoon. Its height is 1 meter. Can you find the
  height of the tree after \$N\$ growth cycles?

  Input Format

  The first line contains an integer, \$T\$, the number of test cases.
  \$T\$ lines follow. Each line contains an integer, \$N\$, that denotes
  the number of cycles for that test case.

  Constraints

1 <= T <= 10
0 <= N <= 60

  Sample Input: #01:

2
3
4

  Sample Output: #01:

6
7

  Explanation: #01:

  There are 2 testcases.

  N = 3:
  * the height of the tree at the end of the 1st cycle = 2
  * the height of the tree at the end of the 2nd cycle = 3
  * the height of the tree at the end of the 3rd cycle = 6

  N = 4:

  the height of the tree at the end of the 4th cycle = 7

This is my accepted solution:

module Main where

import Control.Monad(mapM_)

main = do
    let base_height = 1
    n_test_cases <- readLn
    test_cases <- getList n_test_cases
    mapM_ (\i -> putStrLn $ show $ utopianTreeHeight base_height
        (test_cases !! i)) [0..n_test_cases - 1]

getList :: Int -> IO [Int]
getList n =
    if n == 0
        then return []
    else
        do
            x <- readLn
            xs <- getList (n - 1)
            return (x:xs)

utopianTreeHeight :: Int -> Int -> Int
utopianTreeHeight present_height 0 = present_height
utopianTreeHeight present_height cycles =
    if odd cycles
        then 2 * (utopianTreeHeight present_height (cycles - 1))
    else
        1 + (utopianTreeHeight present_height (cycles - 1))

So, does this solution show good Haskell style? What could be improved? I have doubts especially regarding the way I deal with the IO (which was not provided by Hackerrank), as it was the first time I read about and applied  the Haskell way of doing it.


texts: Advanced multi-conditonal split with an regex in Perl

texts:
I would like to split a string on multiple conditions such as:

After each /;/
After each /{/ or /}/
After each /\w+:/ but not after /\w+:\s+\{/
After each /#\w.*$/

I've found that I can keep a pattern and split before it with

/(?=pattern)/

or split after it (if the pattern has a fixed width)

/(?<=pattern)/

or split after it (if the pattern has a variable width)

/pattern\K/

or even remove the pattern during the operation

/pattern/

With all this knowledge I wrote this:

#!/usr/bin/perl
$_ = do { local $/; <DATA> };
s/\#\w.+\n\K|\n//g;

my @content = split /(?:(?<=[;{}])|(?<=:)(?!\s*\{)|#\w.*\$\K)/, $_;

print join "\n", @content;

__DATA__
carrot;
#orange
apple: {pear; { cabbage; } }
#passion
sprout: celeri;
tomato;

Where the output should be this (after manually reindenting it):

carrot;
#orange
apple: {
  pear;
  {
    cabbage;
  }
}
#passion
sprout:
celeri;
tomato;

I am not really happy with this method for multiple reasons:

I cannot use a x regex in split like split m/re/x to make the regex more readable
I need to treat the exception for the special case /^\s*#.*$/ where I cannot remove CR otherwise I will get for instance #passionsprout:

Can I do a better job?


texts: Are 2 Django URLs pointing at 1 view unorthodox?

texts:
I'm in the process of writing a private messaging system and I have 2 URLs which go to the same view (is that bad?). The logic behind this madness relates to the way user relationships are structured in our system...

     T
    / \___
   C1      \
   |        C2
   P1      /  \
          P2   P3

T = Trainer, C = Coach, P = Participant.

We define this structure in a pretty simple way:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    higher_up = models.ForeignKey('self', blank=True, null=True)
    # ...
    type = models.CharField(max_length=1, choices=TYPES, default='P')

And bam, We've got a DAG. Here's my 2 urls in urls.py:

# talk to lower_down
url(r'^pm/(?P<userprofile_pk>\d+)/$', 'private_message'),

# talk to higher_up
url(r'^pm/$', 'private_message'),

and the private_message view...

def private_message(request, userprofile_pk=''):
    me = request.user.userprofile
    src_pk = me.pk

    if userprofile_pk == '': # /pm/
        you = me.higher_up
        dest_pk = you.pk
    else: # userprofile_pk was not blank /pm/<num>
        you = UserProfile.objects.get(pk=userprofile_pk)
        dest_pk = you.pk

    # Are they allowed to talk?
    if me.is_assoc_with(you):
        return HttpResponseRedirect('/')

    feed_vars = {
        'dest_pk': dest_pk,
        'src_pk' : src_pk,
    }

    return render(request, 'talk/private_message.html', feed_vars)

The me.is_assoc_with(you) bit just checks where me and you are in the userprofile structure. In the above ASCII art diagram, P1 should not be allowed to talk with P2. T can talk to C1, C1 and C2 cannot talk. T and P3 can talk, etc.

Is this an ok pattern to have 2 URLs go to 1 view that handles logic based on the URL?

I do feel like I am reinventing the wheel here. I think there should be a more flexible approach with settings for who can talk to whom factored out of the business logic itself.


texts: SQL Query to perform a "reverse exclusion" on a LEFT JOIN with a select from the left side table

texts:
I have a set of tables that I want to execute a LEFT JOIN on and bring back "excluded" rows.  In addition, I would like the left table's ID included as part of the results set.  Here's some sample data:

Table1_ID

1

3

5

Table2_ID
Table2_Val

1
a

2
b

3
c

4
d

5
c

A simple left join would look like this
SELECT t1.Table1_ID, t2.Table2_Val
FROM Table2 t2
LEFT JOIN Table1 t1 ON t2.Table2_ID = t1.Table1_ID
WHERE t1.Table1_ID IS NULL

And yields the following table

Table1_ID
Table2_Val

NULL
b

NULL
d

However, my desired result is to have for each ID in Table2 that is missing in Table1, return the set of values in Table2 paired with the existing values in table 1.  Like so:

Table1_ID
Table2_Val

1
b

1
d

3
b

3
d

5
b

5
d

So far, the best I've been able to come up with is through using a CROSS JOIN to accomplish this, but I'd like to know if there's a better/more efficient way to handle this.  Here's the code I'm curious about improving:
WITH cte (T1_ID, T2_ID, T2_Value)
AS
(
SELECT t1.Table1_ID, t2.Table2_ID, t2.Table2_Val
FROM Table1 t1 CROSS JOIN Table2 t2
GROUP BY t1.Table1_ID, t2.Table2_ID, t2.Table2_Val
)
SELECT
  cte.Table1_ID,
  t2.Table2_Val
FROM Table2 t2
INNER JOIN cte ON t2.Table2_ID = cte.T2_ID
LEFT JOIN Table1 t1 ON t2.Table2_ID = t1.Table1_ID
WHERE t1.Table1_ID IS NULL


texts: Logging using function as decorator in Guava

texts:
I needed to add a logger into my flow based on FluentIterable from the Guava library. I have a lot of functions and in some cases I would like to add logging when in other cases (for the same function) I would not.

Of course the natural solution for this problem is to use the decorator pattern, so I created something like this:

/**
 * Decorator function that add logging into function passed as parameter.
 *
 * @param  input type
 * @param <O> output type.
 */
public class DecoratorLoggerInfoFunc implements Function {

    /**
     * Original function
     */
    private final Function function;

    /**
     * Current logger.
     */
    private final Logger logger;

    /**
     * "Builder" that takes function and return function decorated by logger.
     *
     * @param function function to decorate.
     * @param       input type
     * @param <O>      output type
     * @return function with logger.
     */
    public static  Function of(Function function) {
        checkNotNull(function, "Function to decorate cannot be null");
        return new DecoratorLoggerInfoFunc(function);
    }

    /**
     * Initialize logger!
     *
     * @param function original function.
     */
    private DecoratorLoggerInfoFunc(Function function) {
        this.function = function;
        this.logger = LoggerFactory.getLogger(function.getClass());
    }

    /**
     * Flow:
     *

     *
Call original function

     *
Log input and output

     *
Return output of original function

     *

     *
     * @param input
     * @return
     */
    @Override
    public O apply(I input) {
        O output = function.apply(input);
        logger.info("Input is {} Output is {}", input, output);
        return output;
    }
}

Is this code a good way to solve my problem? Is there a better way to do this?


texts: Scrabble helper: find the highest score with any 7 letters

texts:
I'm making a python script that accepts 7 letters and returns the highest scoring word along with all other possible words. At the moment it has a few "loops in loops" and others things that will slow down the process.

import json
#open file and read the words, output as a list

def load_words():
    try:
        filename = "dictionary_2.json"
        with open(filename,"r") as english_dictionary:
            valid_words = json.load(english_dictionary)
            return valid_words

    except Exception as e:
        return str(e)

#make dictionary shorter as there will be maximum 7 letters
def quick():
    s = []
    for word in load_words():
        if len(word)<7:
            s.append(word)
    return s

# takes letters from user and creates all combinations of the letters
def scrabble_input(a):
    l=[]
    for i in range(len(a)):
        if a[i] not in l:
            l.append(a[i])
        for s in scrabble_input(a[:i] + a[i + 1:]):
            if (a[i] + s) not in l:
                l.append(a[i] + s)

    return l

#finds all words that can be made with the input by matching combo's to the dictionary and returns them
def word_check(A):
    words_in_dictionary = quick()
    for word in scrabble_input(A):
        if word in words_in_dictionary:
            yield word

#gives each word a score
def values(input):
    # scrabble values
    score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
             "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
             "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
             "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
             "x": 8, "z": 10}
    word_total = 0
    for word in word_check(input):
        for i in word:
            word_total = word_total + score[i.lower()]
        yield (word_total, str(word))
        word_total = 0

#prints the tuples that have (scrabble score, word used)
def print_words(a):
    for i in values(a):
        print i

#final line to run, prints answer
def answer(a):
    print ('Your highest score is', max(values(a))[0], ', and below are all possible words:')
    print_words(a)

answer(input("Enter your 7 letters"))

I have removed some of the for loops and have tried to make the json dictionary I found shorter by limiting it to 7 letter words max. I suppose I could do that initially so that it doesn't need to do that each time i run the script. Any other tips on how to speed it up?


texts:
I decided to write a simple dictionary to use as a cache:

public class CacheDictionary : Dictionary<string, object>, ICacheDictionary
{
    private readonly Dictionary<string, CancellationTokenSource> _expireTasks = new Dictionary<string, CancellationTokenSource>();
    private int _defaultExpiration;

    public CacheDictionary()
    {
        _defaultExpiration = 30;
    }

    public CacheDictionary(int defaultExpiration)
    {
        _defaultExpiration = defaultExpiration;
    }

    public T GetOrDefault<T>(string key, Func<T> createDefault)
    {
        return GetOrDefault(key, createDefault, TimeSpan.FromSeconds(_defaultExpiration));
    }

    public T Set<T>(string key, Func<T> create)
    {
        return Set(key, create, TimeSpan.FromSeconds(_defaultExpiration));
    }

    public T GetOrDefault<T>(string key, Func<T> createDefault, TimeSpan expireIn)
    {
        return (T)(ContainsKey(key) ? this[key] : Set(key, createDefault, expireIn));
    }

    public T Set<T>(string key, Func<T> create, TimeSpan expireIn)
    {
        if (_expireTasks.ContainsKey(key))
        {
            _expireTasks[key].Cancel();
            _expireTasks.Remove(key);
        }

        var expirationTokenSource = new CancellationTokenSource();
        var expirationToken = expirationTokenSource.Token;

        Task.Delay(expireIn, expirationToken).ContinueWith(_ => Expire(key), expirationToken);

        _expireTasks[key] = expirationTokenSource;

        return (T)(this[key] = create());
    }

    private void Expire(string key)
    {
        if (_expireTasks.ContainsKey(key))
            _expireTasks.Remove(key);

        Remove(key);
    }
}

The functionality is simple: I can add items into the dictionary and set a timer to expire them. I am wondering if I did everything right. Should I also implement IDisposable and remove expiration tasks on Dispose? And if I want it to be thread-safe, should I use ConcurrentBag?


texts: Performance tuning on a text file to object conversion

texts:
I'm using an API which returns text in the following format:

#start
#p 09060 20131010
#p 09180 AK
#p 01001 19110212982
#end
#start
#p 09060 20131110
#p 09180 AB
#p 01001 12110212982
#end

I'm converting this to a list of objects:

var result = data.match(/#start[\s\S]+?#end/ig).map(function(v){

    var lines = v.split('\n'),
        ret = {};

    $.each(lines, function(_, v2){
        var split = v2.split(' ');
        if(split[1] && split[2])
            ret[split[1]] = split[2];
    });

    return ret;
});

My concern is that the API returns quite a lot of data, therefore I would like some feedback regarding on how to improve the performance.

For instance, is there any way to reduce the mapping complexity from O(N2) to O(N)?

Also, please suggest regex improvements :)


texts:
I wrote a simple Boot script for converting to and from Roman numerals using instaparse. Here's my EBNF grammar (roman.bnf):

number = thousands hundreds tens ones

I = 'I'
V = 'V'
X = 'X'
L = 'L'
C = 'C'
D = 'D'
M = 'M'

IV = 'IV'
IX = 'IX'
XL = 'XL'
XC = 'XC'
CD = 'CD'
CM = 'CM'

ones = V? I? I? I? | IV | IX
tens = L? X? X? X? | XL | XC
hundreds = D? C? C? C? | CD | CM
thousands = M? M? M?

And here's the Boot script itself (roman.clj):

#!/usr/bin/env boot

(set-env! :dependencies '[[instaparse "1.4.5"]])

(require '[boot.cli :as cli]
         '[instaparse.core :as insta])

(defn digits
  "Returns a lazy sequence of the digits of n in the specified base, starting
  with the least significant digit."
  [base n]
  (->> (iterate #(quot % base) n)
       (take-while pos?)
       (map #(mod % base))))

(defn int->roman
  "Returns the Roman numeral representation of n."
  [n]
  (let [[ones tens hundreds thousands] (concat (digits 10 n) (repeat 0))]
    (->> (letfn [(digit [one five ten n]
                   (case n
                     4 [one five]
                     9 [one ten]
                     (cons (when (<= 5 n) five)
                           (repeat (mod n 5) one))))]
           [(repeat thousands "M")
            (digit "C" "D" "M" hundreds)
            (digit "X" "L" "C" tens)
            (digit "I" "V" "X" ones)])
         (apply concat)
         (apply str))))

(def parser (insta/parser (slurp "roman.bnf")))

(def symbols
  {:I 1 :V 5 :X 10 :L 50 :C 100 :D 500 :M 1000
   :IV 4 :IX 9 :XL 40 :XC 90 :CD 400 :CM 900})

(defn roman->int
  "Converts the Roman numeral string s to an integer."
  [s]
  (let [parsed (parser s)]
    (if-some [failure (insta/get-failure parsed)]
      failure
      (->> (rest parsed)
           (mapcat rest)
           (map first)
           (map symbols)
           (apply +)))))

(cli/defclifn -main
  "Converts to and from Roman numerals."
  [t to ARABIC int "The number to convert to a Roman numeral."
   f from ROMAN str "The number to convert to an Arabic numeral."]
  (cond
    (and to from) (println "Please choose only one conversion.")
    to (println (if (< 0 to 4000) (int->roman to) "Out of range."))
    from
    (let [result (roman->int from)]
      ((if (insta/failure? result) print println) result))))

Here are some examples (test.sh):

./roman.clj -t 1
./roman.clj -t 52
./roman.clj -t 294
./roman.clj -t 2780
./roman.clj -f IX
./roman.clj -f LXIX
./roman.clj -f CCXCV
./roman.clj -f MMDCLXXXII

$ chmod +x roman.clj
$ chmod +x test.sh
$ ./test.sh
I
LII
CCXCIV
MMDCCLXXX
9
69
295
2682

Obviously this is completely impractical due to Clojure's startup time, but meh.

Are there any improvements I can make? I'm especially interested in ways to make the grammar more elegant; for instance, I can't seem to find a good way to remove the repetition in I? I? I? etc., but if there is a way to genericize the maximum number of occurrences, that would be cool. Any improvements on the Clojure side of things would also be most welcome.


texts:
I want to transpose this matrix input:

1.000 2.00 3.0 4.00
5.00 6.000 7.00000 8.0000000
9.0 10.0 11.0 12.00000

And get this output:

1.000 5.00 9.0
2.00 6.000 10.0
3.0 7.00000 11.0
4.00 8.0000000 12.00000

I have a matrix in a file with thousands of lines and millions of columns, so I can't read it into memory (i.e. numpy.transpose is not an option). I have written the solution below, which is very memory efficient, but terribly slow.

import sys
import os

def main():

    path_in = sys.argv[-1]
    path_out = os.path.basename(path_in)+'.transposed'
    separator = ' '

    d_seek = {}
    with open(path_in) as fd_in:
        i = 0
        print('indexing')
        while True:
            tell = fd_in.tell()
            if fd_in.readline() == '':
                break
            d_seek[i] = tell
            i += 1
        print('indexed')
    cols2 = rows1 = i

    with open(path_in) as fd_in:
        line = fd_in.readline()
    rows2 = cols1 = len(line.split(separator))
    del line

    with open(path_in) as fd_in, open(path_out, 'w') as fd_out:
        print('transposing')
        for row2 in range(rows2):
            print('row', row2)
            for row1 in range(rows1):
                fd_in.seek(d_seek[row1])
                s = ''
                while True:
                    char = fd_in.read(1)
                    if char == separator or char == '\n':
                        break
                    s += char
                d_seek[row1] += len(s)+1
                if row1+1 < rows1:
                    fd_out.write('{} '.format(s))
                else:
                    fd_out.write('{}\n'.format(s))

    return

if __name__ == '__main__':
    main()

How can I make it faster? The slow parts are seek and read.

Additional information:

The fields do not have fixed widths, but I know that a field is always an integer or a float and always between 1 and 5 characters and always belonging to the closed interval [0:2]. The field widths differ between lines.


texts: Producing all possible combinations of a list

texts:
I've written a function that produces all combinations of elements in a given list:

createGroups :: [a] -> [[(a, a)]]
createGroups li@(x : xs) = map (\el -> map (\el2 -> (el, el2)) xs) li

These nested maps seem quite messy -- is there a better way to do this?


texts: Better way to Read /Write Memory to/from POCO

texts:
I am communicating with a machine that sends/received structured binary data to my netcore service. The machine supplier's new library uses Memory in their library's API.
I have written the following code for Ser/Des which works, but seems verbose. I know I can wrap some of this in methods/helpers, but it feels cumbersome compared to the "old" Streams & BinaryWriter/BinaryReader approach.
Is there a better way to approach this? A better part of the framework or technique I should be using?
Deserialising from Memory:
public void Read(Memory<byte> data)
    {
      if (data.Length < StaticSize) // StaticSize = 56. Defined by machine's struct.
        throw new ArgumentOutOfRangeException($"Span length too small. Minimum: {StaticSize}, Received: {data.Length}.");

      var s = data.Span;
      MemoryMarshal.TryRead<bool>(s.Slice(0, 1), out _forward);
      MemoryMarshal.TryRead<bool>(s.Slice(1, 2), out _reverse);
      SomeString = Encoding.UTF8.GetString(s.Slice(2, 22)).Replace("\0", string.Empty);
      Dynamics = new TcDynamics(data.Slice(24)); // "TcDynamics" object de-serialized in same manner as this.
    }

Serialising to Memory:
 public void Write(Memory<byte> data)
    {
      if (data.Length < StaticSize) // StaticSize = 56. Defined by machine's struct.
        throw new ArgumentOutOfRangeException($"Span length too small. Minimum: {StaticSize}, Received: {data.Length}.");

      var s = data.Span;
      MemoryMarshal.TryWrite<bool>(s.Slice(0, 1), ref _forward);
      MemoryMarshal.TryWrite<bool>(s.Slice(1, 2), ref _reverse);
      Encoding.UTF8.GetBytes(_someString).CopyTo(s.Slice(2,22)); // Strings are fixed length (21 + termination).
      Dynamics.Write(data.Slice(24)); // "TcDynamics" object serialized in same manner as this.
    }


texts: Choose numbers from a grid, minimising the sum

texts:
Given a 2-D input matrix, I need to pick elements from it.

constraint: you can pick one number at each row, each column
given: number boards are given expected
output: print least sum of numbers what you took!

I think I found a firm framework like method for DPS in python. But I want this to be confirmed, please comment:
def recurse(row, n):
    global mean
    row += 1 #choose next row
    currentsum = sum(boards[row][column] for row, column in enumerate(answersheet[0:row]))
    if currentsum > mean: ## put your bounding function here
        return
    if row == n: ##when you get to bottom of recursion tree
        if currentsum < mean:
            mean = currentsum
            return
    for column in range(n): #recursive part
        if column not in answersheet[:row]: #check if column is already selected! [critical][pythonic]
            answersheet[row] = column
            recurse(row, n)

boards = [[5, 2, 1, 1, 9],
        [3, 3, 8, 3, 1],
        [9, 2, 8, 8, 6],
        [1, 5, 7, 8, 3],
        [5, 5, 4, 6, 8]
        ]
n = len(boards)

answersheet = [-1] * n  #using index as a row,
                        #value as column what you took at that row
row = -1
mean = 9999999
recurse(row, n)
print(f"the least  {mean}")


texts: HTML parsing algorithm for extracting  tags

texts:
My intention is to create a complete HTML parser, so far I made a basic algorithm that iterates trough text and extracts everything in an "a" tag.

It works on everything I tried, but I want a review of what I could do better or what I did right.

#include <iostream>
#include <stdio.h>
#include <vector>
#include <fstream>
#include <streambuf>
#include <sstream>

std::vector<std::string> performCheck(std::string check, std::string text)
{
        int iterator = 0;
        int second_iterator = 0;

        bool is_flag = false;

        std::string returnString = "";
        std::vector<std::string> returnVector;

        for(iterator = 0;iterator < text.size();iterator++)
        {
            if(text[iterator] == '<')
            {

                is_flag = true;

                for(second_iterator = 0;second_iterator < check.size();second_iterator++)
                {
                    if(text[iterator + second_iterator] == check[second_iterator])
                    {
                        returnString = returnString + text[iterator + second_iterator];
                    }
                    else
                    {
                        is_flag = false;
                        returnString = "";
                        break;
                    }
                }

                if(is_flag == true)
                {
                    for(second_iterator = iterator + second_iterator;second_iterator < text.size();second_iterator++)
                    {
                        returnString = returnString +  text[second_iterator];

                        if(text[second_iterator - 2] == '/' && text[second_iterator - 1] == 'a')
                        {
                            returnVector.push_back(returnString);
                            break;
                        }
                    }
                }

            }

        }

    return returnVector;
}

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

    std::string check = "<a href=\"";
    std::vector<std::string> urlmap;

    std::ifstream t("your_file.ext");
    std::stringstream buffer;
    buffer << t.rdbuf();

    std::string textBig = buffer.str();

    urlmap = performCheck(check, textBig);

    for(int iterator = 0;iterator < urlmap.size();iterator++)
    {
        std::cout<<urlmap[iterator]<<std::endl;
    }

    system("PAUSE");

    return 0;
}


texts:
Okay I've just finished writing a nice tiny C program to have an ASCII spinner (works on Windows and POSIX). I'm quite new to C, so any suggestions would be great. This is designed to be a small function in my other programs, so please point out anything that could cause problems when been integrated into a larger program.

The only part I am not 100% sure about is how I handle the standard output buffer when it's printed the next character in the cycle. I don't want the buffer to fill up with invisible backspace characters, so is using fflush on stdout the best way?

#ifdef _WIN32
    #include <windows.h>
    #define sleepThr(x) Sleep(x)
#else
    #include <unistd.h>
    #define sleepThr(x) usleep((x) * 1000)
#endif

#include <stdio.h>

#define INTERVAL 200

int main()
{
    int counter = 0;

    while (1)
    {
        switch (counter)
        {
            case 0:
                printf("\b|");
                break;

            case 1:
                printf("\b/");
                break;

            case 2:
                printf("\b-");
                break;

            case 3:
                printf("\b\\");
                counter = -1;
                break;
        }

        fflush(stdout);

        sleepThr(INTERVAL);

        counter++;
    }

    return 0;
}


texts:
Can you please verify my approach?

using System;

    /*
    * In Factory pattern, we create object without exposing the creation logic.
    * In this pattern, an interface is used for creating an object,
    * but let subclass decide which class to instantiate.
    * */

namespace FactoryMethod
{

Product (abstract)

    /*
    * Faza Class ITree
    *
    * */
    public interface ITree
    {
        string GetTreeName();
    }

Products (concrete)

    /*
    * The Concrete class which implements ITree
    *
    * */

    public class BananaTree : ITree
    {
        public string GetTreeName()
        {
            return "My Name Is Banana Tree";
        }
    }

    /*
    * The Concrete class which implements ITree
    *
    * */
    public class CoconutTree : ITree
    {
        public string GetTreeName()
        {
            return "My Name Is Coconut Tree";
        }
    }

Factory (abstract)

    /*
    * Faza Class TreeType
    * If you want you can add abstract class instad of faza class
    *
    * */
    public interface TreeType
    {
        ITree GetTree(string tree);
    }

Factory (concrete)

    /*
    * Concrete class which implements faza or concrete class
    *
    * */
    public class ConcreteTreeType : TreeType
    {

        public ITree GetTree(string tree)
        {

            if (tree == "COCONUT")
                return new CoconutTree();
            else
                return new BananaTree();

        }
    }

Client code

    /*
    * main app.
    *
    *  */
    class Program
    {
        static void Main(string[] args)
        {
            TreeType oTreeType = new ConcreteTreeType();

            ITree banana = oTreeType.GetTree("COCONUT");
            Console.WriteLine(banana.GetTreeName());

            Console.ReadKey();
        }
    }
}


texts: Counting numbers whose digits all go up or down

texts:
I have created a program which takes a value x and uses this value to create a power of ten value like so 10 ** x.

This has then been used as the maximum number of a range 1..(10 ** x), which has been expanded using the splat * method to create an array of numbers, and then assigned to the variable num_array.

Using the values in this array, I want to find the total number of increasing and decreasing integers within this range. These are integers containing digits that either ascend or descend with each proceeding digit.

For example, if

x = 3

then

num_array = [*1..(10**3)] #=> num_array = [1, 2, 3, 4, .. 998, 999, 1000]

Then numbers like 234 which is ascending and 987 which is descending should be counted. Numbers like 555 fall into both categories so also should be counted but numbers like 482 should not because it doesn't follow either rule.
The each method is used to evaluate which integers follow this rule in the range.

My problem is as the powers of ten increase with each method call at the end of the program, it gets slower and slower to return the end result until it calls total_nums(6) which then takes too long.

Is there a general rule of thumb to help process really large arrays like this so it's much faster for your program to return the end result?
What would you say are your preferred methods for such an approach like this?
And would something like Memoization work here?

def total_nums(x)
   return 0 if x == nil
   return 1 if x == 0

   num = 10 ** x
   num_array = [*1..num]
   total = 0

   num_array.each do |i|
         if i == i.to_s.split("").sort.join.to_i || i == i.to_s.split("").sort.reverse.join.to_i
         total +=1
         end
   end

   return total

end

total_nums(0) #=> 1
total_nums(1) #=> 10
total_nums(2) #=> 100
total_nums(3) #=> 475
total_nums(4) #=> 1675
total_nums(5) #=> 4954
total_nums(6) #=> 12952


texts:
I've made a simple login API request which gets a token as a response. I had to use Toast a few times. Is is possible to make it with only two Toasts Successful/Failed?

public void login(View view){
    RequestQueue queue = Volley.newRequestQueue(this);
    String URL = "http://10.0.2.2:8000/api/login";
    StringRequest request = new StringRequest(Request.Method.POST, URL,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObj = new JSONObject(response);
                        myToken =jsonObj.getString("token");
                        if (myToken != ""){
                            Toast.makeText(getApplicationContext(), "Login successfull !", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "Ooops something is not correct !", Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                         myToken = "";
                        Toast.makeText(getApplicationContext(), "Ooops something is not correct !", Toast.LENGTH_LONG).show();
                         e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener()
                {
                @Override
                public void onErrorResponse(VolleyError error) {
                    myToken = "";
                    Toast.makeText(getApplicationContext(), "Ooops something is not correct !", Toast.LENGTH_LONG).show();
                    NetworkResponse response = error.networkResponse;
                    String errorMsg = "";
                    if(response != null && response.data != null){
                        String errorString = new String(response.data);
                    }
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams()
        {
            Map<String, String> params = new HashMap<String, String>();
            TextInputEditText mail = findViewById(R.id.textInputEditTextEmail);
            TextInputEditText pw = findViewById(R.id.textInputEditTextPassword);
            params.put("email", mail.getText().toString());
            params.put("password", pw.getText().toString());
            return params;
        }
    };
    queue.add(request);
}


texts:
I am always surprised by JavaScript and how simple and elegant JS code can look.
I have a piece of code below that simulates a finance calculator. Please share your thoughts, critiques/feedback on how the code can be improved.

jsFiddle

The calculation is just a simulation, so please ignore. Also please ignore the way I display currency ($$$).

JavaScript:

$(function () {
 // we need to cache selectors to avoid re-reading the DOM
 var amount = $("#amount"),
     duration = $("#duration"),
     interest = $("#interest"),
     income = $("#incomeNeeded"),
     monthlyRate = $("#monthlyRate");

 var updateIncome = function() {
     var amountVal =amount.val().slice(0, -4),
         durationVal = duration.val().slice(0, -6),
         interestVal = interest.val().slice(0, 2);
     var resultIncome = amountVal +'-'+ durationVal +'-'+ interestVal;
     return resultIncome;
 };

 var updateRate = function() {
     var amountVal =amount.val().slice(0, -4),
         durationVal = duration.val().slice(0, -6),
         interestVal = interest.val().slice(0, 2);
     var resultRate = amountVal +'-'+ durationVal +'-'+ interestVal;
     return resultRate;
 };

 $("#slider-range-min").slider({
     range: "min",
     value: 10000,
     min: 1,
     max: 20000,
     slide: function (event, ui) {
         $("#amount").val(ui.value + " $$$");

         // seems like we can use either text() or html()
         income.html(updateIncome());
         monthlyRate.html(updateRate());
     }
 });
 $("#amount").val($("#slider-range-min").slider("value") + " $$$");

 $("#duration-range-min").slider({
     range: "min",
     value: 24,
     min: 1,
     max: 70,
     slide: function (event, ui) {
         $("#duration").val(ui.value + " months");
         income.html(updateIncome());
         monthlyRate.html(updateRate());
     }
 });
 $("#duration").val($("#duration-range-min").slider("value") + " months");

 $("#interest-range-min").slider({
     range: "min",
     value: 12,
     min: 4,
     max: 25,
     slide: function (event, ui) {
         $("#interest").val(ui.value + " %");
         income.html(updateIncome());
         monthlyRate.html(updateRate());
     }
 });
 $("#interest").val($("#interest-range-min").slider("value") + " %");
 });

HTML:

    Max amount:
    <input type="text" id="amount" class="input1">

    duration:
    <input type="text" id="duration" readonly class="input1">

    Interest:
    <input type="text" id="interest" readonly class="input1">

Income needed:
x

Monthly rate:
x


texts:
I have programmed the extended euclidean algorithm. Is this a good approach?

def ext_ggT(a, b):
    x,y, u,v = 0,1, 1,0
    while a != 0:
        q, r = b//a, b%a
        m, n = x-u*q, y-v*q
        b,a, x,y, u,v = a,r, u,v, m,n
    gcd = b
    return gcd, x, y


texts:
A program that will count up the number of words in a text, as well as counting how many times a certain character shows up in the text. Only ignore spaces.
This gave me a lot of trouble as I grappled with list comprehension syntax errors.

class TextAnalyzer:
    def __init__(self, txtFile):
        self.txtContent = open(txtFile)
        self.txtStream = self.txtContent.read()

    def __repr__(self):
        return self.txtStream

    def countChars(self):
        characters = {}
        for char in self.txtStream:
            if char != ' ' and char != '\n':
                if char.lower() not in characters:
                    characters[char.lower()] = 1
                else:
                    characters[char.lower()] += 1
        return [x for x in characters.items()]

    def countWords(self):
        totalWords = 0
        for b, a in enumerate(self.txtStream):
            if a != ' ' and a != '\n' and b != len(self.txtStream)-1 and (self.txtStream[b+1] == ' ' or self.txtStream[b+1] == '\n'):
                totalWords += 1
        return totalWords+1

analyze = TextAnalyzer('Darwin.txt')
totalChars = 0;
print(analyze)
for x, y in sorted(analyze.countChars()):
    totalChars += y
    print('{0}: {1}'.format(x, y))
print('Total Characters: ', totalChars)
print('Total Words: ', analyze.countWords())


texts:
I have created a personal password storage program that takes the user's username, password, and for what account it is for, and stores it in a text file and can also read from them (assuming you type the right name in). What I'm looking to do, is either trim it down (take out none needed code) or finding more effective ways to go about this.

import java.io.*;
import java.util.*;

public class testing_file
{
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);

        System.out.println("Access or create?");
        String select = input.nextLine();

        switch(select)
        {
            case "Create":

                String name, user, password;
                FileOutputStream fop = null;
                File file;
                System.out.println("What account is this for?");
                name = input.nextLine();
                System.out.println("Enter the Username");
                user = input.nextLine();

                try
                {
                    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("c:/"+name+".dnx")));
                    file = new File("c:/"+name+".dnx");
                    fop = new FileOutputStream(file);

                    if (!file.exists())
                    {
                        file.createNewFile();
                    }

                    System.out.println("You may now input your password");
                    password = input.nextLine();

                    pw.write("Account: " + name);
                    pw.println();
                    pw.write("Username: " + user);
                    pw.println();
                    pw.write("Password: " + password);
                    pw.flush();
                    pw.close();
                    System.out.println("Operation Complete");

                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    try
                    {
                        if (fop != null)
                        {
                            fop.close();
                        }
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
                break;

            case "Access":
                String string="";
                System.out.println("Enter the account you wish to view");
                name = input.nextLine();
                String file1 = "c:/"+name+".dnx";

                //reading
                try{
                    InputStream ips=new FileInputStream("C:/"+name+".dnx");
                    InputStreamReader ipsr=new InputStreamReader(ips);
                    BufferedReader br=new BufferedReader(ipsr);
                    String line;
                    while ((line=br.readLine())!=null)
                    {
                        System.out.println(line);
                        string+=line+"\n";
                    }
                    br.close();
                }
                catch (Exception e){
                    System.out.println(e.toString());
                }
                break;

            default:
                System.out.println("Invalid method, terminating program");
                break;
        }
    }
}


texts: Outputting a user's name, day of birth, and test scores in a bar chart

texts:
I've been asked to output the users name, what day of the week they were born on, output a line from a poem corresponding with the day they were born on, and their scores for a vark test. We were told to calculate the month of birth as a number and find the number/ month.

This is the first bit of code I've done and I'm just after some comments/feedback on it

MONTHS = 'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'; //months
document.write ('
Introduce Yourself

');
var userName = ''; //create username variable
userName = prompt('Enter your First Name','Alex'); //prompt user for name

var dateString = prompt('Enter your birth date in the form dd mmm yyyy','26 APR    1988'); //get users date of birth
var substrings = dateString.split(' ');
var day = substrings[0];
var month = substrings[1];
var year = substrings[2];

var monthNumber = month.indexOf(MONTHS);
if (monthNumber >= 0); {
}

var poem = ["Sunday's child is fair and wise", "Monday's child is fair of face",        "Tuesday's child is full of grace", "Wednesday's child is full of woe", "Thursday's child has far to go", "Friday's child is loving and giving", "Saturday's child works hard for a living"];
var daysArray = new Array ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',    'Friday', 'Saturday');
var birthDate = new Date(year, monthNumber/3, day);
var dayNumber = (birthDate.getDay());
var dayName = daysArray[dayNumber];
var dayPoem = poem[dayNumber];
document.writeln ('

My name is:   '+ userName +'

 I was born on a '+ dayName +':  '+dayPoem+'

');

var varkString = prompt('Enter your VARK scores - [visual|aural|read|kinesthetic]','9|3|11|10');
var subStrings = varkString.split('|');
var visual = subStrings[0];
var aural = subStrings[1];
var read = subStrings[2];
var kinesthetic = subStrings[3];
var visualBar = 30*visual;
var auralBar = 30*aural;
var readBar = 30*read;
var kinestheticBar = 30*kinesthetic;
document.write ('
My Vark Scores
');
document.writeln ('
');
document.writeln('('+visual+')
');
document.writeln('('+aural+')
');
document.writeln('('+read+')
');
document.writeln('('+kinesthetic+')
');{
}


texts:
I've read a little about binary heaps/priority queues and decided to try my hand at making my own implementation of one. I'm not the most experienced programmer and I would be really grateful if you guys could take a look at my heap class and tell me if it's a good implementation.

What can I improve here? Any feedback is welcome.

public class Heap<T extends Comparable<? super T>> {

    private T[] array = (T[])new Comparable[10];
    private int size = 0;

    public void insert(T data) {
        if(size+1 > array.length) expandArray();

        array[size++] = data;
        int pos = size-1;
        T temp;

        while(pos != 0 && array[pos].compareTo(array[pos/2]) < 0) {
            temp = array[pos/2];
            array[pos/2] = array[pos];
            array[pos] = temp;
            pos /= 2;
        }
    }

    public T deleteMin() {
        T min = array[0];

        array[0] = array[size-1];
        array[size-1] = null;
        size--;
        int pos = 0;
        T temp;
        boolean done = false;

        while(pos*2+1 < size && !done) {
            int minChild = pos*2+1;
            if(array[minChild].compareTo(array[pos*2+2]) > 0) minChild = pos*2+2;

            if(array[pos].compareTo(array[minChild]) > 0) {
                temp = array[minChild];
                array[minChild] = array[pos];
                array[pos] = temp;
                pos = minChild;
            }
            else done = true;
        }

        return min;
    }

    private void expandArray() {
        T[] newArray = (T[])new Comparable[array.length*2];

        for(int i = 0; i < array.length; i++)
            newArray[i] = array[i];

        array = newArray;
    }
}


texts:
Im at the point where I am designing my api security and I was going with a custom attribute I don't want to use third party systems as they cost money.

I was going to use the client id and the secret id approach and I am asking is this a safe enough way to accomplish it I am interacting to my api through a database layer.

So the first thing that will be called is this bit of code which goes out to find a match against the db and then called by the controller

How should I encrypt the client id though in the database so that it cant be easy guessed.

public bool FindKeysByClientIdByApiKey(Guid apiKey, Guid clientId)

  {

       ApiKeys results = new ApiKeys();

        using (var connection = new SqlConnection(constr))

        {

            return connection.Query<ApiKeys>($"SELECT * FROM {schemaDefination}.[ApiKeys] where ClientId= @ClientId and ApiKey=@ApiKey and isActive=1 and isDeleted!=1",

              new { ApiKey = apiKey, ClientId = clientId }).Any();

        }

  }

Controller Code

public class ApiKeysController : ControllerBase

{

    DBContext db = new DBContext();

    [HttpGet]

    public int Get(Guid ApiKey, Guid ClientdId)

    {

        if (!db.FindKeysByClientIdByApiKey(ApiKey, ClientdId))  {

            return StatusCodes.Status401Unauthorized;

        }else

            return StatusCodes.Status200OK;

    }

}

To Enable or disable this at will I am creating a custom Attribute which will have the following.

public async  Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)

{

        //before

        if(!context.HttpContext.Request.Headers.TryGetValue(ApiKeyHeaderName, out var potentialApiKey))

        {

            context.Result = new UnauthorizedResult();

            return;

        }

        // before

        if (!context.HttpContext.Request.Headers.TryGetValue(ClientId, out var potentialClientId))

        {

            context.Result = new UnauthorizedResult();

            return;

        }

            var getConfigurationResult = Do Stuff here

        await next();

        //after

}

This should mean that I can simply call attribute on my controller would this method work ok. I presume this method will also allow me to decorate my Gets and Puts to ensure that they are also authorize what should I be returning in ApiControllers get so I can make it more generic

[Apikey]


texts:
I need to organize the following objects in a array applying the following rules:

Group all object by source
In each group order them by order property
Rewrite each order property keeping their order starting from 0

I have drafted an initial solution below, the final result is present in the code comment and the script does its job.

But I would like to have your code review specially in term of performance,  as the real world array could contain hundreds of objects.

Please note a new array is created for this example, as I do not need to change the original array in place.

   var data = [
          {
              id: 'g',
              order: '0',
              source: '3-j'
          },
          {
              id: 'c',
              order: '40',
              source: '1-x'
          },
          {
              id: 'd',
              order: '0',
              source: '2-y'
          },
          {
              id: 'b',
              order: '30',
              source: '1-x'
          },
          {
              id: 'e',
              order: '1',
              source: '2-y'
          },
          {
              id: 'h',
              order: '1',
              source: '3-j'
          },
          {
              id: 'a',
              order: '20',
              source: '1-x'
          },
          {
              id: 'f',
              order: '2',
              source: '2-y'
          }
        ];
        var flags = {};
        data.forEach(function (item) {
            flags[item.source] = true;
        });
        var sources = [];
        Object.keys(flags).forEach(function (flag) {
            sources.push(flag);
        });
        sources.sort();
        var newData = [];
        sources.forEach(function (source) {
            var dataFiltered = data.filter(function (item) {
                return item.source === source;
            });
            dataFiltered.sort(function (a, b) {
                return a.order - b.order;
            });
            dataFiltered.map(function (item, index) {
                item.order = index;
            });
            newData = newData.concat(dataFiltered);
        });
        console.log(JSON.stringify(newData));

    /*
       Final result:
        [
            {
                "id": "a",
                "order": 0,
                "source": "1-x"
            },
            {
                "id": "b",
                "order": 1,
                "source": "1-x"
            },
            {
                "id": "c",
                "order": 2,
                "source": "1-x"
            },
            {
                "id": "d",
                "order": 0,
                "source": "2-y"
            },
            {
                "id": "e",
                "order": 1,
                "source": "2-y"
            },
            {
                "id": "f",
                "order": 2,
                "source": "2-y"
            },
            {
                "id": "g",
                "order": 0,
                "source": "3-j"
            },
            {
                "id": "h",
                "order": 1,
                "source": "3-j"
            }
        ]
    */


texts: Basic graphical R code draws an ellipse instead of a circle

texts:
I wrote some very basic R code.

This has at least two problems.

It uses a very basic imperative-programming style instead of good R style.
It draws the result as an ellipse, not a circle.  This effect is barely visible on RGui on Windows, but extremely visible in RStudio on Linux. [Edit: rcs has mentioned that the asp parameter of the image command can fix this. Thanks, rcs.]

There are some debatable issues.  For example, there is no good reason why I draw the radius at the distance that I do, so I consider this to be a "magic" number, and I try to avoid "magic numbers" in code because they cause maintenance problems.  The number is in there because I don't think it's worthwhile specifying a user input or a function argument to control it.

edge<-100
magicradius=.81
magicmargin=.01
width<-(2*edge)+1

x<-c(-edge:edge)
y<-c(-edge:edge)

squarelist<-c(1:((width^2)))

dim(squarelist)<-c(width, width)

counter<-0
for (i in 1:length(x)){
  for (j in 1:length(y)){
    counter<-counter+1
    if( (((magicradius-magicmargin)*(edge))<sqrt( x[i]^2 + y[j]^2  ) )
        &(((magicradius+magicmargin)*(edge))>sqrt( x[i]^2 + y[j]^2 ) ) ){
      squarelist[counter]<-sqrt( x[i]^2 + y[j]^2)
    } else {
      squarelist[counter]<-0

    }
  }
}

gg<-matrix(squarelist,nrow=width,ncol=width)

image(gg)


texts: Joining WorkTypes to WorkGroups via Channels and Users to check authorization

texts:
I need to select some "work types" from a channel. These "channels" are in "work groups" and both channels and work groups need to have permissions to view them (tables are ChannelUsers and WorkGroupUsers to check this). The views that can be selected are as such:

  this.views = {
    "*" : ["*"],
    "index" : [
            "Timers.worktype_id",
            "WorkTypes.worktypename",
            "Timers.start",
            "Timers.end",
            "Users.username",
            "Timers.closed",
            "Users.username",
            "Users.id AS user_id",
            "(Timers.end - Timers.start) AS timer_length"
          ],
    "get" : [
            "Timers.worktype_id",
            "Timers.id AS timer_id",
            "Timers.start",
            "Timers.end",
            "Timers.user_id",
            "Timers.work_id",
            "Timers.closed",
            "ChannelUsers.user_id AS user_id",
            "Users.username"
          ]

The query, however is getting pretty grossly long. Being my first webapp ever I'm not used to chaining this many joins together. Is this at all acceptable? Should I be using some more efficient method of checking authorisation?

let checkQuery = `
            SELECT
              ${view}
            FROM Timers

            INNER JOIN WorkTypes
              ON Timers.worktype_id=WorkTypes.id
              AND WorkTypes.channel_id=?

            INNER JOIN ChannelUsers
              ON ChannelUsers.channel_id=WorkTypes.channel_id
              AND ChannelUsers.user_id=?

            INNER JOIN Channels
              ON Channels.id=ChannelUsers.channel_id

            INNER JOIN Users
              ON Users.id=?

            INNER JOIN WorkGroupUsers
              ON WorkGroupUsers.workgroup_id=Channels.workgroup_id
              AND WorkGroupUsers.user_id=?

            INNER JOIN WorkGroups
              ON WorkGroupUsers.workgroup_id=WorkGroups.id;
          `;
      checkQuery = mysql.format(checkQuery, [_channelID, _user.id, _user.id, _user.id]);

I've heard some conflicting opinions on "views" and "temporary tables" but nothing I'm certain could help here. Any opinions would be greatly appreciated!

(The views are separate as part of a system for "building" many-to-one relationships into the resulting object, i.e building all posts a user has made by their ID into the method result, I cut it here for simplicity).


texts:
Here is a simplified version of my JSON.

{
    "Relations": [
        {
            "Type": "A",
            "Categories": [
                { "Name": "Identity" }
            ]
        },
        {
            "Type": "B",
            "Categories": [
                { "Name": "Identity" },
                {
                    "Name": "Contact Information",
                    "Type": "Phone"
                },
                { "Name": "Addresses" },
                { "Name": "Bank Accounts" }
            ]
        },
        {
            "Type": "C",
            "Categories": [
                { "Name": "Identity" },
                { "Name": "Contact Information" },
                { "Name": "Service Fields" }
            ]
        }
    ]
}

My code generates an IEnumerable (List, but I am open to suggestions if there is a more compatible option) that holds all distinct categories, meaning, when joining its values (using string.Join("\n", collection)) it contains the following JSON:

{ "Name": "Identity" }
{
    "Name": "Contact Information"
    "Type": "Phone"
}
{ "Name": "Addresses" }
{ "Name": "Bank Accounts" }
{ "Name": "Contact Information" }
{ "Name": "ServiceFields" }

This is the code:

List<dynamic> Method()
{
    string jString = File.ReadAllText(@"file.json");
    dynamic jObject = JsonConvert.DeserializeObject<dynamic>(jString);

    // The variable in questions
    var categories = new List<dynamic>();
    foreach (dynamic relation in jObject.Relations)
    {
        foreach (dynamic category in relation.Categories)
        {
            if (!CollectionContainsItem(categories, category))
            {
                categories.Add(category);
            }
        }
    }

    return categories;

    bool CollectionContainsItem(IEnumerable<dynamic> collection, JToken searchedItem)
    {
        foreach (var item in collection)
        {
            if (JToken.DeepEquals(item, searchedItem))
            {
                return true;
            }
        }
        return false;
    }
}

How to improve my code? It seems very cumbersome to me, especially the local method.

Note: I need a dynamic approach. I do not want to create C# classes for the JSON data.

Thanks!


texts: Speed up script that calculates distribution of every character from user input

texts:
I have a data set with close to 6 million rows of user input. Specifically, users were supposed to type in their email addresses, but because there was not pattern validation put in place we have a few months worth of interesting input.

I've come up with a script that counts every character, then combines it that so I can see the distribution of all characters. This enables me to do further analysis and get a sense of the most common mistakes so I can begin to clean the data. My question is: how would you optimize the following for speed?

import pandas as pd
import numpy as np
from pandas import Series, DataFrame
from collections import Counter

df = pd.DataFrame({'input': ['Captain Jean-Luc Picard <picard@starfleet.com>','deanna.troi@starfleet.com','geordi @starfleet.com','data@starfleet.com','rik#er@starfleet.com'],
'metric1': np.random.randn(5).cumsum(),
'metric2': np.random.randn(5)})

l = []
for i in range(len(df.index.values)):
    l.append(dict(Counter(df.ix[i,'input'])))
dist = pd.DataFrame(l).fillna(0)
dist = dist.sum(axis=0)
print(dist)

I've run this over ~1/3 of my dataset, and it takes a while; it's still tolerable, I'm just curious if anyone could make it faster.


texts:
I have the following code below that takes a new row added to my Google Spreadsheet (has a header row) and extracts the video ID. If the ID does not exist in the playlist, it adds the video to the playlist. If it doesn't, it skips it. Not really comfortable with Google Apps Script, so I would like some constructive feedback.
function addVideoToYouTubePlaylist() {
  // retrieve video ID list from the playlist.
  var playlistId = "PL6bCFcS8yqQxSPjwZ9IXFMfVm6kaNGLfi";
  var list = [];
  var pageToken = "";
  do {
    var res = YouTube.PlaylistItems.list(["snippet"], {playlistId: playlistId, maxResults: 50, pageToken: pageToken});
    if (res.items.length > 0) list = list.concat(res.items);
    pageToken = res.nextPageToken || "";
  } while (pageToken);
  var obj = list.reduce((o, e) => Object.assign(o, {[e.snippet.resourceId.videoId]: e.snippet.resourceId.videoId}), {});

  // read the source videos from Google Sheet
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getValues();

  // iterate through all rows in the sheet
  for (var d=1,l=data.length; d<l; d++) {
    var videoId = extractVideoID(data[d][0]);
    if (!obj[videoId]) {
    YouTube.PlaylistItems.insert({
      snippet: {
        playlistId: playlistId,
        resourceId: {
          kind: "youtube#video",
          videoId: extractVideoID(videoId)
          }
        }
      }, "snippet");
    }
    else{
      console.log("Already in playlist");
    }
    sheet.deleteRow(d+1); // delete row after video is checked
  }
}

function extractVideoID(url){
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
    var match = url.match(regExp);
    if ( match && match[7].length == 11 ){
        return match[7];
    }
    else if (!( match && match[7].length == 11 )){
        console.log("Could not extract video ID.");
        var trimmedVideoID = url.replace("https://youtu.be/", "");
        trimmedVideoID = trimmedVideoID.replace('https://www.youtube.com/watch?v=', "");
        trimmedVideoID = trimmedVideoID.replace('https://youtube.com/watch?v=', "");
        trimmedVideoID = trimmedVideoID.replace("&feature=youtu.be", "");
        trimmedVideoID = trimmedVideoID.replace("&feature=share", "");
        console.log(trimmedVideoID);
        return trimmedVideoID;
    }
}


texts:
I am requesting a JSON file that's gzipped. First, I download file:

import urllib.request
testfile = urllib.request.URLopener()
testfile.retrieve("https://xxxxx.auth0.com/1537150574", "file.gz")

After that, I will read the file.gz and get the data.

with gzip.GzipFile("file.gz", 'r') as fin:
    json_bytes = fin.read()
json_str = json_bytes.decode('utf-8')
data = json.loads(json_str)
print(data)

Actually, This above code can work well for me. But I would like to find another way (faster and brief code). Could I have a suggestion?


texts:
Looking at knockout for the first time, would like to know if I'm approaching it correctly.

Here's a live example:
http://jsfiddle.net/fergal_doyle/xhAe8/1/

I have a "car" select, and an "other" input to allow values not present in the select box. When "other" is populated, it over-rides "car" by disabling it and a computed observable is set to the actual chosen car. Only when "other" is emptied, will "car" become enabled again.

HTML:

Car
<select id="car" data-bind="options: cars, value: selectedCar, enable: checkCar"></select>

Other
<input id="other" type="text" data-bind="value: other, valueUpdate:'afterkeydown'"/>

Chosen value:

JS:

function viewModel(){
    var self = this;

    self.cars = ko.observableArray(["Chrysler", "Chevrolet", "Ford", "Lincoln"]);
    self.other = ko.observable("");
    self.selectedCar = ko.observable("");

    self.chosenCar = ko.computed(function() {
        return self.other() || self.selectedCar();
    });

    self.checkCar = ko.computed(function(){
        if(self.other())
            return false;
        else
            return true;
    });
}

ko.applyBindings(new viewModel());


texts:
I am new to making shopify applications. I have made one application which helps merchants add additional features in their stores.

I have written some PHP code that is given below.

$themeList = shopify_call($token,$shop,"/admin/api/2019-07/themes.json",array(),'GET');
$themeList = json_decode($themeList['response'], JSON_PRETTY_PRINT);
$theme_id = $themeList['themes'][0]['id'];

$customTheme = shopify_call($token,$shop,"/admin/api/2019-07/themes/".$theme_id."/assets.json?asset[key]=layout/theme.liquid&theme_id=".$theme_id,array(),'GET');
$customTheme = json_decode($customTheme['response'], JSON_PRETTY_PRINT);
$currentTheme = $customTheme['asset']['value'];
$pos = strpos($currentTheme,"</body>");
$str = "{% include 'back-to-the-top' %}\n";
$currentTheme =  substr_replace( $currentTheme, $str, $pos, 0 );

This code fetches the store theme files and append my customize code into theme file.

I want to know that what is right way to do it. Please check it and tell me that this is right way to do it or not? Please tell me the right way to do it.


texts: Wrapper around a Python API for creating user interfaces

texts:
I am writing a wrapper around the GeUserArea class of Cinema 4D's Python API to enable creating user interfaces using an object orientated interface.

I've already written 2 prototypes, but I am not satisfied with my class-design.
They do work very well, but I decided to start over to make it even more efficient, more clean and better commented, etc.

The GeUserArea class provides drawing on it as it was a field of pixels, so it's a highly dynamic class to enable almost any type of interface you want, when you have the skills.

The baseclass for all objects being rendered is the Renderable class.
Two of the subclasses are View and Lable. The difference between these is, that View does hold a frame attribute that defines a rectangular area while Lable does only hold a position attribute that defines the position of the text being rendered.

The Renderable class implements a tree-like design, so you can add a Renderable instance below another, etc. When an input event (mouse/keyboard) appears, a chain starts that tells the full tree that this event occured. Any Renderable instance should be able to react on an input event. But the view-subclass should also call a method when the mouse clicked into it's area.

(Theese methods are to let the user override them while subclassing, enabling to react on those input events.)

The event itself comes from GeUserArea.InputEvent(self, msg).
From the msg parameter, I can read out if and where a mouse event took place.
After doing so, the event chain starts.

class Renderable:
    def InputEvent(self, msg):
        pass

class View(Renderable):
    def MouseEvent(self, msg, mouse):
        pass

Using the above layout, I'd need to implement a method that manages calling of theese methods, like this:

class Renderable:
    # ..
    def _private_ManageInput(self, msg):
        self.InputEvent(msg)
        for sub in self.subs:
            sub._private_ManageInput(msg)

class View(Renderable):
    # ..
    def _private_ManageInput(self, msg):
        if IsMouseEvent(msg):
            mouse = GetMouse(msg)
            if mouse in self.frame:
                self.MouseEvent(self, msg, mouse)
        Renderable._private_ManageInput(self, msg)

This does already seem a bit dirty to me.

As the mouse position doesn't change within the recursive chain, it makes more sense to give the mouse position as an argument to the Renderable._private_ManageInput() method, which gives a speedup of about 30%.

class Renderable:
    # ..
    def _private_ManageInput(self, msg, mouse):
        self.InputEvent(msg)
        for sub in self.subs:
            sub._private_ManageInput(msg)

class View(Renderable):
    # ..
    def _private_ManageInput(self, msg, mouse):
        if mouse is not None:
            if mouse in self.frame:
                self.MouseEvent(msg, mouse)
        Renderable._private_ManageInput(self, msg, mouse)

The Renderable class does not implement reacting on MouseEvents (as it does not define any area where the mouse could "hit" it), but a method does need arguments for this purpose?  It seems quite dirty to me.

Can you tell me how I can improve this design?


texts:
I am working on a webforms project using c#/aspx/jquery. I'm not sure where to handle my Onclick. Both options (doing it in C# or jquery) seem feasible. Which would be better practice?

Here is the scenario:

I want to build a checkbox which will toggle a textbox's textmode, altering it between Password and SingleLine.

Currently, I have this following code for my markup since I am currently handling it in C#:

<asp:Checkbox ID="CheckBox1" OnCheckedChanged="CheckBox1_OnCheckedChanged"/>

The code:

protected virtual void OnCheckedChange(EventArgs e)
{
     If (CheckBox1.TextMode == TextMode.Password)
          CheckBox1.TextMode = TextMode.SingleLine;
     else
          CheckBox1.TextMode = TextMode.Password;
}

The use case of this is: A user is entering his password. On the same page, he may choose to keep the password hidden or not by checking the checkbox.


texts: Is this routine for determining the epsilon of a Double 100% valid?

texts:
This algorithm is intended to determine the epsilon of a given double precision number. As numbers increase in value, their accuracy decreases. This algorithm will return the smallest increment / decrement possible at any given value.

Given the way floating point numbers are structured, is there logically any situation where this algorithm won't work? It has worked fine for whatever numbers I've thrown at it.

public enum EZeroDirection { TowardsZero, AwayFromZero };

[StructLayout(LayoutKind.Explicit)]
private struct DL
{
    [FieldOffset(0)]
    internal double D;

    [FieldOffset(0)]
    internal long L;
}

/// <summary>
/// Returns the dynamic epsilon of this Double. If the value is NaN or ±Inf, or the initial result overflows, the result will be null.
/// </summary>
/// <remarks>See (http://bit.ly/10KS2wo)</remarks>
/// <param name="dir">Determines if the epsilon is calculated from the delta of its next value towards zero or away from zero. Choose the direction
/// the value moves in. Note: EZeroDirection.TowardsZero allows proper processing of Double.MaxValue and Double.MinValue.</param>
/// <returns>Double?</returns>
public static Double? DynamicEpsilon(this Double a, EZeroDirection dir = EZeroDirection.TowardsZero)
{
    if (!double.IsNaN(a) && a != double.NegativeInfinity && a != double.PositiveInfinity)
    {
        DL dl = new DL();
        dl.D = a;
        dl.L -= ((dir == EZeroDirection.TowardsZero) ? 1 : -1);

        if (!double.IsNaN(dl.D))
        {
            return Math.Abs(a - dl.D);
        }
    }

    return null;
}


texts: Handling Parent-Child Relationship using MVP within a WinForms Application

texts:
I recently asked on Programmers:

How should one handle a Parent-Child relationship using MVP?

Based on the comments received, I tried this:

IParentView

public interface IParentView { }

IChildView

public interface IChildView<V> where V : IParentView {
    void Show(V parentView);
}

IChildPresenter

public interface IChildPresenter<V> where V : IParentView {
    void ShowView(V parentView);
}

CustomerManagementPresenter

public class CustomerManagementPresenter : Presenter<ICustomerManagementView>
    , ICustomerManagementUiHandler
    , IChildViewPresenter<IMainView> {
    public CustomerManagementPresenter(ICustomerManagementView view
        , ICustomerManagementService service) : base(view) {
        view.Handler = this;
        if (service == null) throw new ArgumentNullException("service");
        customerManagementService = service;
    }

    public void LoadCustomers() {
        var customers = customerManagementService.GetCustomers();
        View.ViewModel.Customers = customers;
    }

    public void ShowView(IMainView parentView) { View.Show(parentView); }

    private readonly ICustomerManagementService customerManagementService;
}

IMainView

public interface IMainView : IView, IParentView, IHasUiHandler<IMainViewUiHandler> { }

MainPresenter

public class MainPresenter : Presenter<IMainView>, IMainViewUiHandler {
    public MainPresenter(IMainView view, ICustomerManagementPresenterFactory factory)
        : base(view) {
        view.Handler = this;
        if (factory == null) throw new ArgumentNullException("factory");
        this.customerManagementPresenterFactory = factory;
    }

    public void ManageCustomers() {
        var p = customerManagementPresenterFactory.Create();
        var parent = this.View;
        p.ShowView(parent);
    }
}

CustomerManagementForm

public partial class CustomerManagementForm : Form, IMainView {
    public CustomerManagementForm(CustomerManagementViewModel viewModel) {
        InitializeComponent();

        if (viewModel == null) throw new ArgumentNullException("viewModel");

        customerManagementViewModel = viewModel;
        customerManagementViewModel.PropertyChanged +=
            new PropertyChangedEventHandler(
                customerManagementViewModel_PropertyChanged);
    }

    public ICustomerManagementUiHandler Handler { get; set; }
    public string Message { get; set; }
    public string Title { get { return Text; } set { Text = value; } }
    public CustomerManagementViewModel ViewModel {
        get { return customerManagementViewModel; }
    }

    public void Show(IMainView parent) {
        MdiParent = (Form)parent;
        Show();
    }

    private void CustomerManagementForm_Load(object sender, EventArgs e) {
        Handler.LoadCustomers();
    }

    private void CustomerManagementViewModel_PropertyChanged(
        object sender
        , PropertyChangedEventArgs e) {
        customerManagementViewModelBindingSource.DataSource = ViewModel;
    }

    private readonly CustomerManagementViewModel customerManagementViewModel;
}

I believe I could reduce complexity or repetition with my IChildPresenter and IChildView which are pretty similar. Besides, The Show() methods belongs expressly to the views, whilst ShowView() methods actually belongs to presenters. I tend to follow some such basic nomenclature to make it more understandable.

So now I wonder, what do you guys think of this approach?

Did I miss the point?

Any possible imporvement?


texts: Avoiding instanceOf when finding index of an interface within a list

texts:
I am working on some code and I have come across the following:

private int getPosition() {
     List<IDescriptor> fragmentDescriptors = new ArrayList<IDescriptor>(mDescriptors);

     int position = -1;

     for (IDescriptor fragmentDescriptor : fragmentDescriptors) {
         if (fragmentDescriptor instanceof VideoDescriptor) {
                position = fragmentDescriptors.indexOf(fragmentDescriptor);
         }
     }

     return position;
}

In a situation like this, how can one find an index of a specific implementation within a list without using instanceOf?

Update:
Few points: mDesciptors is a set. The point of the question was: The set of IDescriptor is injected into the class, the class has no idea what the set will contain, it does however know there maybe a IDescriptor that is meant for video.. the problem is the current method relies on VideoDescriptor, therefore if that implementation changes, the position will no longer be found.

I'd like a general review of this.  The method was really just to demonstrate the dependency on VideoDescriptor.


texts: Thoughts on using curly-brackets-less while loop with a try/catch?

texts:
I need to fetch data from an server that isn't always reliable and unfortunately fixing that is out of my hands. My team determined we would attempt the request up to 3 times.

So I thought of using a try-catch inside the while loop but didn't like the extra indentation for no good reason and thought to remove the braces from the while loop.

async function doAjax() {
  const data = { /* stuff */ }
  const retryLimit = 2;
  let retryCount = 0;
  let found = false;

  while (!found && retryCount <= retryLimit) try {
    let serverResponse = await $.get("url", data);
    // Do stuff
  } catch (err) {
    retryCount++;
  }

  // Do more stuff
}

I know my team won't be against this, but I still got curious if there's a consensus or some reason in favor/against writing code this way. Thoughts?


texts:
I am wanting to use a cell editor and a DocumentFilter to prevent the user from entering certain characters into the table cells.

The columns are as follows:

Product ID
Product Description
Inventory Count
Cost
Minimum Quantity

For Inventory Count, Cost and Minimum Quantity I am going to use a JFormattedTextField.

How can this be improved?

public class ProductTableCellEditor extends AbstractCellEditor implements TableCellEditor
{

    private TableCellEditor editor;

    @Override
    public Object getCellEditorValue()
    {
    if (editor != null) {
        return editor.getCellEditorValue();
    }
    return null;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
    {
    JTextField textField = new JTextField();
    textField.setFont(ApplicationStyles.TABLE_FONT);

    switch (column)
    {
    case 0:
        ((AbstractDocument) textField.getDocument()).setDocumentFilter(new ProductTableDocumentFilter());
        editor = new DefaultCellEditor(textField);
        break;
    case 1:
        ((AbstractDocument) textField.getDocument()).setDocumentFilter(new ProductTableDocumentFilter());
        editor = new DefaultCellEditor(textField);
        break;
    case 2:
        throw new UnsupportedOperationException("Not yet supported....");
    case 3:
        throw new UnsupportedOperationException("Not yet supported....");
    case 4:
        throw new UnsupportedOperationException("Not yet supported....");
    default:
        throw new UnsupportedOperationException("Not yet supported....");
    }
    return editor.getTableCellEditorComponent(table, value, isSelected, row, column);
    }
    }


texts: Script for saving top wallpapers from wallbase.cc into a directory

texts:
I am newish to Python and I am looking for some extra eyes on a script I wrote. I wrote this script to learn more about web-scraping and using requests and Beautiful Soup. I use it to connect to the website wallbase.cc and save the top 32 wallpapers from the last 3 days into a directory where I later cycle through displaying them on my desktop.

I'm really looking for some best practices suggestions, whatever you think is appropriate.  I'm open to any constructive criticism.

#!/usr/bin/env python

import os
import requests
import sys
import urllib.request
from bs4 import BeautifulSoup
import hashlib

def get_pic(number_imgs, timespan):
    """Returns a list of the specified number of top images over the specified
    timeframe from wallbase.cc
    """
    url = "http://wallbase.cc/toplist"
    opts = {
        'section':'wallpapers', 'q':'', 'res_opt':'gteq',
        'res':'1920x1080', 'aspect':'1.77', 'purity':'100',
        'board':'21', 'thpp':number_imgs, 'ts':timespan
    }
    htmltext = requests.get(url, params = opts)
    page_urls = []
    img_urls = []
    soup = BeautifulSoup(htmltext.content)
    results = soup.findAll("a")

    for r in results:
        if "http://wallbase.cc/wallpaper/" in r['href']:
            page_urls.append(r['href'])

    for p in page_urls:
        wp_page = requests.get(p)
        wp_soup = BeautifulSoup(wp_page.content)
        wp_results = wp_soup.findAll("img")
        for res in wp_results:
            if "http://wallpapers.wallbase.cc/" in res['src']:
                img_urls.append(res['src'])

    return img_urls

def save_pic(url):
    """Saves a file to disk when given a URL"""
    save_path = sys.argv[1]
    hs = hashlib.md5(url.encode('UTF-8')).hexdigest()
    file_ext = url.split(".")[-1]
    to_save = (save_path + hs + "." + file_ext)
    if to_save != "":
        if os.path.isfile(to_save):
            print(hs + "." + str(file_ext) + "\texists, skipping...")
        else:
            print(hs + "." + str(file_ext) + "\tdownloading...")
            urllib.request.urlretrieve(url, to_save)

if __name__ == "__main__":
    for img in get_pic(32, "3d"):
        save_pic(img)


texts: Increasing visible text with on-click "read more"

texts:
What can I do better?

$(function () {
    "use strict";

    /*
     *  Header text. Vergroot de tekst door op lees meer te klikken
     */
    var heading = $(".header .text h2").height(),
        firstP = $(".header p:first").height(),
        areaSmall = heading + firstP,
        areaBig = $(".header .text").height(),
        box = $(".header .text"),
        readmore = $('.header .text a[title*="meer"]'),
        closeBox = $('.header .text a[title*="Sluit"]');

    $(".header .text").css({ height: areaSmall });

    readmore.click(function () {
        $(".header .text").animate({ height: areaBig }, 1000, "easeInQuart", function () {
            $(".header .text p").css({ visibility: "visible" });
        });
    });

    closeBox.click(function () {
        $(".header .text").animate({ height: areaSmall }, 1000, "easeOutQuart", function () {
            $(".header .text p").css({ visibility: "hidden" });
            $(".header .text p:first").css({ visibility: "visible" });
        });
    });

});