texts: Approximation search source reconstruction localization algorithm

texts:
Goal
To determine the coordinates of some signal source in a 3D space, given the coordinates of four observers and the time at which each saw the signal, as well as the velocity of the signal.
Algorithm
The algorithm is more-or-less comprised of two pieces: the approximation search algorithm, and the localization algorithm. Approximation search can be described simply as follows:
Suppose we have some function, f(x), and we want to find an x such that f(x) = y. We begin by choosing some search interval, [xi, xf], and we probe some evenly-spaced points along this interval with some step, da. We remember the point with the least error, and feed that error back into the algorithm. We recursively increase accuracy, reducing da and restricting the search interval to around each progressively better solution. We stop when we've reached the maximum number of iterations (configurable).
The localization bit is simply the computation of the error. I could explain it, however I find that the code does so itself far better than I could hope to in words.
Issues
In my opinion, the code is a bit messy and slightly more difficult to read than I'd like. Similarly, I'm not sure how I feel about the nested loops. Of course, I don't want to overcomplicate things simply to get rid of nested loops, however if there's a nicer way to do this, I'm all ears.
It's also slow. This is Python, of course, so I shouldn't expect it to perform like a similarly implemented algorithm in, say, C/C++, however I'm certainly interested in increasing search speed.
Lastly, it's been a while since I've done anything in Python, so I'm interested in a critique of my style. The goal is readability, and not necessarily 'standards' compliance.
Tear it apart. Don't hold back!
import math
from dataclasses import dataclass

@dataclass
class Approximate:

    ai: float;  af: float
    da: float;   n : int

    # Default values
    aa: float = 0
    ei: float = -1
    a : float = 0
    e : float = 0
    i : int   = 0

    done: bool = False
    stop: bool = False

    def step(self):

        if (self.ei < 0) or (self.ei > self.e):

            self.ei = self.e
            self.aa = self.a

        if (self.stop):

            self.i += 1

            if (self.i >= self.n):

                self.done = True
                self.a = self.aa

                return  # Max iter

            # Restrict to window around 'solution'
            self.ai = self.aa - self.da
            self.af = self.aa + self.da

            self.a = self.ai

            # Increase accuracy
            self.da *= 0.1
            self.ai += self.da
            self.af -= self.da

            self.stop = False

        else:

            # Probe some points in [ai,af] with step da
            self.a = self.a + self.da

            if (self.a > self.af):

                self.a = self.af
                self.stop = True

def localize(recv):

    ax = Approximate(0, 5000, 32, 10)
    ay = Approximate(0, 5000, 32, 10)
    az = Approximate(0, 5000, 32, 10)

    dt = [0, 0, 0, 0]

    while not ax.done:
        ay = Approximate(0, 5000, 32, 10, 0, 0)

        while not ay.done:
            az = Approximate(0, 5000, 32, 10, 0, 0)

            while not az.done:

                for i in range(4):
                    x = recv[i][0] - ax.a
                    y = recv[i][1] - ay.a
                    z = recv[i][2] - az.a

                    baseline = math.sqrt((x * x) + (y * y) + (z * z))

                    dt[i] = baseline / 299800000

                    # Normalize times into deltas from zero
                baseline = min(dt[0], dt[1], dt[2], dt[3])

                for j in range(4):
                    dt[j] -= baseline

                error = 0

                for k in range(4):
                    error += math.fabs(recv[k][2] - dt[k])
                    ay.e = error
                    ax.e = error

                az.step()

            ay.step()

        ax.step()

    # Found solution
    print(ax.aa)
    print(ay.aa)
    print(az.aa)
```


texts:
I am trying to create a class to queue up a series of commands. (Not really a queue as events happen based on time). Each command has a callback (Action) that get's called. However, each Action has a different set of parameters (signature), so I am using an object[] to pass them and then have to do lots of casting.

Example: the Queue class:

class RfxQueue {
    public enum CMD {DISPLAY, REPLACE_TMPLT, SCALE_DVE, etc };
    private Dictionary<CMD, Action<object []>> actions = new Dictionary<CMD,Action<object[]>>();
    // Struct to hold command info
    public struct QItem
    {
        public CMD cmd;           // The CMD to exec
        public long ttd;          // Time to be executed
        public object[] param;    // Parameters to Action
    }
    private List<QItem> q = new List<QItem>();   // The queue of events

    // Create a new callback
    public void addAction(CMD cmd, Action<object []> action)
    {
        actions.Add(cmd, action);
    }

    // Add to Q
    public void pushEvent(CMD Cmd, float Delay, params object[] Param)
    {
        q.Add(new QItem() { cmd = Cmd, param = Param, ttd = DateTime.Now.AddMilliseconds(Delay * 1000).Ticks });
    }

    // This is actually done in a thread. Simplified here
    private void execEvent()
    {
        QItem item;
        // item is pulled from q here
        actions[item.cmd].Invoke(item.param);
    }
}

And the owner class creates events like this:

// "q" is a RfxQueue and the internal Invoke is required to run on main thread
q.events.Add(RfxQueue.CMD.SCALE_DVE, new Action<object[]>(o =>
{
    dispatcher.Invoke(new Action<string, string, bool>((a,b,c) =>
    {
        _cgManager.ScaleDVE(a, b, c);
    }), (string)o[0], (string)o[1], (bool)o[2]);
}));
q.events.Add(RfxQueue.CMD.PLAY_ANIMATION, new Action<object[]>(o =>
{
    dispatcher.Invoke(new Action<VideoTemplate, string>((v, s) => {
        _cgManager.playAnimation(v, s);
    }), (VideoTemplate)o[0], (string)o[1]);
}));

Lastly, an event is added like this:

// Play animation "inserton" in 3 seconds
q.add(RfxQueue.CMD.PLAY_ANIMATION, template, 3f, "inserton");

Is there a way to do this without all that casting? Thanks!


texts:
Project Euler problem 9 says:

  A Pythagorean triplet is a set of three natural numbers, \$a < b < c\$, for which, $$a^2 + b^2 = c^2$$
  For example, \$3^2 + 4^2 = 9 + 16 = 25 = 5^2\$.

  There exists exactly one Pythagorean triplet for which \$a + b + c = 1000\$.
  Find the product \$abc\$.

My code finds the correct solution to the problem. The problem is it takes 47.6 seconds to get it, so I'd like to optimize it, but don't know exactly how to do so further. I've already reduced the range of the for loops.

import time
s=time.time()
a=0
b=0
c=0

for i in range(1,499): #max value for any side of the triangle must be less      than the semiperimeter
    for j in range(i,499):
        for k in range(j,499):
            if(i+j+k==1000 and i**2+j**2==k**2):
                a=i
                b=j
                c=k
                break #the solution is unique, so when it finds a solution, it doesnt need to go through any other loops.
print(a*b*c,time.time()-s)


texts: "Multi" scope guard using template argument deducing feature

texts:
Using modern C++ feature template argument deduction for class templates and folding expressions it is possible to implement "multi" scope guard utility, which have right order of functor calls:
#include <utility>

template< std::size_t I, typename F >
struct wrapper { F f; };

template< std::size_t I, typename F >
constexpr
F &
get(wrapper< I, F > * sg) noexcept
{
    return sg->f;
}

template< typename index_sequence, typename ...F >
struct scope_guard_base;

template < std::size_t ...I, typename ...F >
struct scope_guard_base< std::index_sequence< I... >, F... >
    : wrapper< I, F >...
{
    using base = scope_guard_base;
    scope_guard_base(F &... f) : wrapper< I, F >{std::forward< F >(f)}... { ; }
    ~scope_guard_base() { (get< (sizeof...(I) - 1 - I) >(this)(), ...); }
};

template< typename ...F >
struct scope_guard
    : scope_guard_base< std::index_sequence_for< F... >, F... >
{
    scope_guard(F &&... f) : scope_guard::base(f...) { ; }
};

#include <iostream>

template< std::size_t I >
struct F
{

    F() { std::cout << I << std::endl; }

    void operator () () const { std::cout << I << std::endl; }

};

int main()
{
    F< 0 > const f{};
    scope_guard _{f, F< 1 >{}, F< 2 >{}};
}

Output:

0
1
2
2
1
0

Live example.


texts:
I am new to programming and I have just written my first program. It takes files from an SD card and copies then into a new named folder and has the option to name the files themselves or simply move them into the named folder.

As I am new I am unsure of the correct convention in terms of layout or structure of a program. Would a 'real' program look like this and how should it be structured?

Dir.chdir '/home/moot/pickaxe/pics' #replace this with destination directory

$pic_names = Dir['/media/moot/**/*.{CR2,cr2,JPG,jpg}'] #replace this with sd card directory

def folder
 puts "Enter the folder name"
 while $folder_name = gets.chomp
 if File.exist?("#{$folder_name}")
   puts "This folder already exists, choose a unique name"
 else
   require 'fileutils'
   FileUtils::mkdir_p "/home/moot/pickaxe/pics/#{$folder_name}"
   break
   end
  end
end

def files
  puts "Do you want to name the files? Answer y/n"
  while question = gets.chomp
    if question == "y"
      puts "What do you want to call them?"
      $file_name = gets.chomp
      print "Downloading #{$pic_names.length} Files: "
      pic_number = 1
      $pic_names.each do |name|
      print 'ˁ˚ᴥ˚ˀ  '
      new_name = if pic_number < 10
      "#{$file_name} 0#{pic_number} .CR2"
    else
      "#{$file_name} #{pic_number} .CR2"
    end
    require 'fileutils'
    include FileUtils
    cp(name, new_name)
    pic_number = pic_number + 1
    end
    break
    elsif question == "n"
    print "Downloading #{$pic_names.length} Files: "
        $pic_names.each do |name|
        print 'ˁ˚ᴥ˚ˀ  '
    new_dir = "/home/moot/pickaxe/pics/#{$folder_name}"
    require 'fileutils'
    include FileUtils
    cp(name, new_dir)
    end
    break
    else
      puts "Please answer y/n"
    end
  end
end

folder
Dir.chdir "/home/moot/pickaxe/pics/#{$folder_name}"
files
puts "Move Complete."


texts:
I am creating a package to be used in our company that adds the root of the project to the system path.

I will add a source_root.config file in our root directory.

add_root_path.py

import sys
import inspect
from pathlib import Path
from inspect import getsourcefile

CUR_FILE = Path(getsourcefile(lambda:0)).name
SOURCE_ROOT_DEFAULT_FILE = 'source_root.config'

def _get_dir_of_importer_file():
    """ the directory of the file importing the package"""
    frames_stack = inspect.stack()
    for frame in frames_stack:
        # first file that's not importlib._bootstrap and not current file
        if 'py' in frame.filename and Path(frame.filename).name != CUR_FILE:
            file_name = frame.filename
            break

    return Path(file_name).resolve().parent

def find_source_root(source_root_file=SOURCE_ROOT_DEFAULT_FILE):
    importer_dir = _get_dir_of_importer_file()
    while True:  # can go wrong if package is not used correctly
        files_in_dir = map(Path.resolve, importer_dir.glob('*'))
        for file in files_in_dir:
            if file.name == source_root_file:
                return importer_dir
        importer_dir = importer_dir.parent

def append_root_to_path(source_root_file=SOURCE_ROOT_DEFAULT_FILE):
    source_root = find_source_root(source_root_file)
    sys.path.append(source_root.resolve().as_posix())

This is done in order to properly import the files inside the project and because using PYTHONPATH in windows is not that convenient for pytest and alembic (meaning not running the files directly via python.exe).


texts:
What do you think of my Brainf*ck interpreter?
What else can be done to increase speed?

#!/usr/bin/env python3

class InfiniteArray:
    def __init__(self):
        self.pstack, self.nstack = [], []
    def __getitem__(self, index):
        s = self.pstack if index >= 0 else self.nstack
        i = index if index >= 0 else -index + 1
        if i >= len(s):
            return 0
        return s[i]
    def __setitem__(self, index, value):
        s = self.pstack if index >= 0 else self.nstack
        i = index if index >= 0 else -index - 1
        if i >= len(s):
            s.extend([0 for _ in range(len(s), i+1 + 100)])
        s[i] = value
    def __str__(self):
        return str(list(reversed(self.nstack))) + ' | ' + str(self.pstack)

class StateMachine:
    def __init__(self, code, jump_table, debug=False):
        self.arr = InfiniteArray()
        self.pointer = 0
        self.i = 0
        self.code = code
        self.jt = jump_table
        self.debug = debug
        self.instrcount = 0

    def putc(self):
        from sys import stdout
        stdout.write(chr(self.arr[self.pointer]))
        stdout.flush()

    def getc(self):
        from sys import stdin
        c = stdin.read(1)
        self.arr[self.pointer] = ord(c)

    def plus1(self):
        self.arr[self.pointer] += 1

    def minus1(self):
        self.arr[self.pointer] -= 1

    def mvright(self):
        self.pointer += 1

    def mvleft(self):
        self.pointer -= 1

    def matchl(self):
        if not self.arr[self.pointer]:
            self.i = self.jt[self.i]

    def matchr(self):
        if self.arr[self.pointer]:
            self.i = self.jt[self.i]

    def nextcell(self):
        self.i += 1
        self.instrcount += 1

    def __str__(self):
        return str(self.arr) + '\n\n' + ''.join(map(str, self.code))

    def run(self):
        import datetime as dt
        ops = {'+': self.plus1,
               '-': self.minus1,
               '>': self.mvright,
               '<': self.mvleft,
               '.': self.putc,
               ',': self.getc,
               '[': self.matchl,
               ']': self.matchr }
        start = dt.datetime.now()
        while self.i < len(self.code):
            c = self.code[self.i]
            ops[c]()
            self.nextcell()
            if self.debug:
                print(self)
        end = dt.datetime.now()
        print(int(self.instrcount/(end-start).microseconds * 10**6), "instr/second")

def extract(file):
    code = []
    for c in file.read():
        if c in '><+-.,[]':
            code.append(c)
    jump_table = dict()
    stack = []
    count = 0
    for i, c in enumerate(code):
        if count < 0:
            raise SyntaxError("2muh ]")
        if c == '[':
            stack.append(i)
            count += 1
        if c == ']':
            jump_table[i] = stack[-1]
            jump_table[stack[-1]] = i
            stack.pop()
            count -= 1
    if count > 0:
        raise SyntaxError("unmatched [ at positions " + ', '.join(map(str, stack)))

    return code, jump_table

def main():
    from sys import argv
    options = {'debug': False}
    for i, name in enumerate(argv[1:]):
        print('no. {}: {}'.format(i+1, name))
        try:
            if name == '-':
                f = open('/dev/stdin')
            elif name.startswith('-'):
                if name == '-debug':
                    options['debug'] = True
                continue
            else:
                f = open(name)
        except:
            print("Error: no such file :<")
            continue
        try:
            code, mt = extract(f)
            f.close()
        except SyntaxError as e:
            print("Error:", e)
        finally:
            s = StateMachine(code, mt, debug=options['debug'])
            s.run()

if __name__ == '__main__':
    main()


texts:
I just started picking up Elixir (I don't have any functional programming background either), I would appreciate any feedback you have!

The kata is about writing two functions:

uppercase/1: takes a string and upcases every other word
unvowel/1: takes a string and removes the vowels from every other word

And here's my solution:

defmodule Schizo do
  @moduledoc false

  require Integer

  @vowels ~w[a i u e o]

  @doc ~S"""
  Upcases every other word in a sentece.

  ## Examples

      iex> Schizo.uppercase("elixir is pretty rad")
      "elixir IS pretty RAD"

  """
  def uppercase(str) do
    str
    |> transform_every_other_word_with(&String.upcase/1)
  end

  @doc ~S"""
  Removes the vowels from every other word in a sentence.

  ## Examples

      iex> Schizo.unvowel("how are things really?")
      "how r things rlly?"

  """
  def unvowel(str) do
    str
    |> transform_every_other_word_with(&(String.replace(&1, @vowels, "")))
  end

  defp transform_every_other_word_with(str, transformer) do
    str
    |> String.split(" ")
    |> transform_every_other_item_with(transformer)
    |> Enum.join(" ")
  end

  defp transform_every_other_item_with(list, transformer) do
    list
    |> Stream.with_index
    |> Enum.map(transform_odd_index_item_with(transformer))
  end

  defp transform_odd_index_item_with(transformer) do
    fn
      ({item, index}) when Integer.is_even(index) -> item
      ({item, index}) when Integer.is_odd(index) -> transformer.(item)
    end
  end
end


texts: Optimal way of skipping certain values in a for loop

texts:
What would be the fastest way of skipping certain values in a for loop? This is what I intend to do in its most basic form, with about 20 more keys to omit.

for (var key in arr ) {
    if ( key != 'ContentType' && key != 'FileRef' ) {
        arrayPushUnknown( columns, formatTitle( key ), true, key )
    }
}


texts: Better way to get the XML attribute value?

texts:
I have an xml file from which I want to extract the value of attribute custName from the very first child. The code below works where I am using the dom parser. Is there a third-party library with which I can do the same with less code and more neatly?

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = (Document) db.parse(new File(
        tempDir));
    Node node = ((Document) document).getFirstChild();
    String custName= node.getAttributes()
        .getNamedItem("custName")
        .getNodeValue();
    assertEquals( "scott",custName);

Update:- Did the above approach use DOM4J (sorry but I am not sure)?


texts: Program to output the same highest numbers in an array

texts:
Here is my program to find the largest number(s) in a list of elements, possibly non-unique (in Python):

item_no = [5, 6, 7, 8, 8]
max_no = 0
for i in item_no:
    if i > max_no:
        max_no = i
        high = [i]
    elif i == max_no:
        high.append(i)

Example input: [5, 6, 7, 8, 8]

Example output: [8, 8]

How can I make this program more effective and shorter?

Any help would be highly appreciated.

This code is based on help received on Stack Overflow.


texts:
Base functionality:

Reading a CSV file and inserting in database after replacing values with web macro.
Reading values from CSV @ first header information NO,NAME next to that, then read one by one values from CSV and put into web macro context like below:

context.put("1","RAJARAJAN")

Web macro will replace $(NO) ==>1 and $(NAME)==>RAJARAJAN values taken from CSV once the web macro replacement is done.
Add in statement batch.  Once it reaches 1000, execute the batch.

The code is running as per functionality but it takes 4 minutes to parse 50,000 records.  I need a performance improvement or a change in logic.

Note: I use web macro to replace $(NO) in merge query.

Bala.csv

NO?NAME  ==================>Header Information
1?RAJARAJAN
2?ARUN
3?ARUNKUMAR

Connection con=null;
Statement stmt=null;
Connection con1=null;
int counter=0;
 try{
      WebMacro wm = new WM();
      Context context = wm.getContext();
      String strFilePath = "/home/vbalamurugan/3A/Bala.csv";
      String msg="merge into temp2  A using
      (select '$(NO)' NO,'$(NAME)' NAME from dual)B on(A.NO=B.NO)
               when not matched then  insert (NO,NAME)
                  values(B.NO,B.NAME) when matched then
                  update set A.NAME='Attai' where A.NO='$(NO)'";
      String[]rowsAsTokens;
      con=getOracleConnection("localhost","raymedi_hq","raymedi_hq","XE");
      con.setAutoCommit(false);
      stmt=con.createStatement();
      File file = new File(strFilePath);
      Scanner scanner = new Scanner(file);
     try {
         String headerField;
         String header[];
         headerField=scanner.nextLine();
         header=headerField.split("\\?");
         long start=System.currentTimeMillis();
         while(scanner.hasNext()) {
             String scan[]=scanner.nextLine().split("\\?");
             for(int i=0;i<scan.length;i++){
                 context.put(header[i],scan[i]);
             }
       if(context.size()>0){
             String m=replacingWebMacroStatement(msg,wm,context);
             if(counter>1000){
                 stmt.executeBatch();
                 stmt.clearBatch();
                 counter=0;
             }else{
                 stmt.addBatch(m);
                 counter++;
             }

           }
       }
   long b=System.currentTimeMillis()-start;
   System.out.println("=======Total Time Taken"+b);
     }catch(Exception e){
        e.printStackTrace();
    }
  finally {
     scanner.close();
   }
          stmt.executeBatch();
          stmt.clearBatch();
          stmt.close();
    }catch(Exception e){
      e.printStackTrace();
      con.rollback();

  }finally{
      con.commit();

  }

 // Method For replace webmacro with $
  public static String
  replacingWebMacroStatement(String Query, WebMacro wm,
      Context context)   throws Exception {

Template template = new StringTemplate(wm.getBroker(), Query);
template.parse();
String macro_replaced = template.evaluateAsString(context);
return macro_replaced;
}
 // for getting oracle connection
 public static Connection
  getOracleConnection(String IPaddress,
  String username,String  password,String Tns)throws SQLException{

  Connection connection = null;
  try{
  String baseconnectionurl ="jdbc:oracle:thin:@"+IPaddress+":1521:"+Tns;
  String driver = "oracle.jdbc.driver.OracleDriver";
  String user = username;
  String pass = password;
  Class.forName(driver);
  connection=DriverManager.getConnection(baseconnectionurl,user,pass);
  }catch(Exception e){
   e.printStackTrace();
  }
  return connection;
}


texts: Text tokenizer - extract words and positions from text

texts:
I have Set of character delimiters (DELIMITERS), eg . ,  etc. Using this I want to split text and get words with their position in text.
String.split() works fine if you want only words. The same with StringTokenizer. Wrote some simple method to deal with this, but maybe there is a better way to achieve this result?

public List<String> extractWords(String text){
    List<String> words = new ArrayList<>();
    List<WordPos> positions = new ArrayList<>();
    int wordStart = -1;
    for(int i=0; i < text.length(); i++){
        if(DELIMITERS.contains(text.charAt(i))){
            if(wordStart >=0){ //word just ended
                String word = text.substring(wordStart, i);
                positions.add(new WordPos(wordStart, i));
                words.add(word);
            }
            wordStart = -1;
        }else{ //not delimiter == valid word
            if(wordStart < 0){ //word just started
                wordStart = i;
            }
        }
    }
    return words;
}

// inner static class for words positions
public static class WordPos{
    int start;
    int end;
    public WordPos(int start, int end){
        this.start = start;
        this.end = end;
    }
}


texts: Using a service interface to get user input from dialogs

texts:
I haven't worked with WPF/MVVM for a while, but now I'm back fixing some issues with one of my old apps and remembering the struggles I always had when dealing with asking for user input (eg. showing a dialog) from a view model.

I've put some thought into it and decided to try routing user input requests through a service interface so that it can be mocked/tested, while keeping the view logic out of my view model.

public interface IUserInputService
{
    UserRegistration PromptUserRegistration();
}

I then wrote a generic method that creates a new instance of a view and view model, connects them together, shows the dialog and then returns the dialog view model and result (eg. accepted, cancelled) back to the caller. Finally, the caller can extract information from the returned view model and return the actual desired result.
The view models have events which are called when the view model is "done", eg: Accepted and Cancelled. These are hooked up using the generic method.

public class UserInputService : IUserInputService
{
    // Implementation of the service interface using the generic method below
    public UserRegistration PromptUserRegistration()
    {
        var result = ShowDialog<UserRegistrationDialog, UserRegistrationViewModel>((v, vm) =>
        {
            vm.Accepted += (s, e) => v.DialogResult = true;
            vm.Cancelled += (s, e) => v.DialogResult = false;
        });

        if (result.State != DialogState.Accepted)
        {
            return null;
        }

        return new UserRegistration
        {
            FirstName = result.ViewModel.FirstName,
            LastName = result.ViewModel.LastName
        };
    }

    // The generic method
    private DialogResult<TViewModel> ShowDialog<TView, TViewModel>(
        Action<TView, TViewModel> viewModelConnected
    )
        where TView : Window, new()
        where TViewModel : ViewModelBase, new()
    {
        TViewModel viewModel = new TViewModel();
        TView view = new TView();
        view.DataContext = viewModel;

        viewModelConnected(view, viewModel);

        view.ShowDialog();

        DialogState state;
        switch (view.DialogResult)
        {
            case true:
                state = DialogState.Accepted;
                break;
            case false:
                state = DialogState.Declined;
                break;
            default:
                state = DialogState.Cancelled;
                break;
        }

        return new DialogResult<TViewModel>(state, viewModel);
    }
}

Now I can pass around the service interface using DI/IoC and view models can ask for user input without caring how (eg. via dialog or mocking).

The other types (DialogResult and DialogState) are these:

public enum DialogState
{
    Accepted,
    Declined,
    Cancelled
}

public class DialogResult<TViewModel>
{
    public DialogResult(DialogState state, TViewModel viewModel)
    {
        State = state;
        ViewModel = viewModel;
    }

    public DialogState State { get; }
    public TViewModel ViewModel { get; }
}

So my questions are...

Is this a good approach?
What would you do differently and why?
Any other suggestions regarding code quality?

I want to stick to the principles of MVVM as much as possible (though within reason) while keeping things testable... Let me know what you think.


texts:
I'm trying to filter a list composed of multiple dictionaries for useless entries and non-ideal fields. An entry is useless if Mem['visibility'] == "redacted" and then should be removed from the list. An entry is non-ideal when any of the fields are empty, and these should be filled with a 0 instead or if Mem['~whatever~'] is a list in which case the list should be transformed into a single string with all the objects in that list.

class Filter:
    @staticmethod
    def members(memberlist):
        for Mem in memberlist[:]:
            for Item in Mem:
                if not Mem[Item]:
                    Mem[Item] = 0
                if (type(Mem[Item]) is list):
                    Mem[Item] = ', '.join(Mem[Item])
            if(Mem['visibility'] == "redacted"):
                print(Mem)
                memberlist.remove(Mem)
        return(memberlist)

Sample memberlist:

[{'roles': [], 'rank': 'No SCB account', 'type': 'main', 'stars': 2, 'visibility': 'visible', 'sid': 'imperium', 'handle': 'freakyeagle'}, {'roles': [], 'rank': 'Fleet Member', 'type': 'main', 'stars': 1, 'visibility': 'visible', 'sid': 'imperium', 'handle': 'cadimus'}, {'roles': [], 'rank': 'Fleet Member', 'type': 'main', 'stars': 1, 'visibility': 'visible', 'sid': 'imperium', 'handle': 'belleal'}]

How can I make this as simple/efficient as possible?


texts: Reading lines of integers into a list of lists

texts:
I have a text file containing integers in different lines which I want to read into a list of lists.

So

01
11 14
45 50 09

should become

((1)
 (11 14)
 (45 50 9))

The real file is longer so I want to read it in using CL instead of transforming it using Emacs' macros etc. It is important that every line becomes exactly one list and the data is stored as integers, i.e. 09 becomes 9.

I ended up with the following (using the external library split-sequence):

(defun read-data (&optional (file "data.txt"))
  "Returns the numerical data in FILE as a list of lists."
  (with-open-file (data file)
    (loop :for line = (read-line data nil nil)
          :while line
          :collect (map 'list #'parse-integer (split-sequence #\Space line)))))

which is great because it does the job, I needed only two minutes for it and I knew exactly what I wanted to do. Nevertheless, I found the chain read-line, split-sequence and map a bit too much for this rather simple job. Is there a simpler way just using read which I am just missing?


texts:
I have a script for school that mimics the cp command. Part of the assignment is to modify the script so that the while loop (that assigns stdin to the variable filelist) is instead done with sed.

The last argument needs to be saved to the variable to because that could be a directory depending on other user input in the script.

while [ "$#" -gt 1 ]
do
        filelist="$filelist $1"
        shift
done

to="$1"

Is this finished product good? How could I polish it up?

filelist=$(echo $* | sed 's/ [^ ]*$//')
to=$(echo $* | sed 's/^.* \([^ ]*\)$/\1/')


texts:
Is there a more efficient way of exponentiating a multidimensional matrix?
This is how I am currently doing it:

import numpy as np
from scipy import linalg

A = np.random.normal(0,0.01, (3, 2,2))
P = np.zeros((3,2,2))
for i in range(3):
     P[i] = linalg.expm( np.multiply(A[i], 0.5))

Note that my real array is much larger and any effort to speed up the process is greatly appreciated.


texts:
I recently ran into some issues with a plugin and outlined the issue in this post and wanted to know if the modifications I've made below cover the scenarios that the with scope blocks would have covered.

I've modified some code to remove the with operator and I'm wondering if I've replicated everything properly in doing so.

var test = new Function('$f','$c','with($f){with($c){return{'+ declarations +'}}}'));

Where $f and $c are passed objects (From what I could tell, $f shouldn't ever have a property of $c). The declarations variable is a string that has a colon in it (EX: "value:color") and available within the scope.

Here is my modified code:

var test = function($f, $c, declarations) {
        var result = {};
        var value = "";
        var split = declarations.split(":");
        if (split.length < 2) {
          throw new Error("Declaration is in an invalid format");
        }
        if ($f[$c] !== undefined && $f[$c][split[1]]) {
          value = $f[$c][split[1]];
        }
        else if ($c[split[1]]) {
          value =  $c[split[1]];
        }
        else if ($f[split[1]]) {
          value =  $f[split[1]];
        }
        else {
          value =  "" + split[1];
        }
        var key = split[0];
        result[key] = value;
        return result;
};

Everything appears to work as it did previously, but this modification now handles the use case where the declarations variable could have a dash in it (EX: "value:background-color").  Additionally the declarations variable is passed into the function, to ensure it's defined.


texts:
This is K.I.S.S, but how about some error and misuse control? I am wishing it were .NET.

<?php

function array_group_by($arr, $key_selector) {
    $result = array();
    foreach($arr as $i){
        $key = $key_selector($i);
        if(!array_key_exists($key, $result)) {
            $result[$key] = array();
        }
        $result[$key][] = $i;
    }
    return $result;
}

 $data = array(
        array(1, "Andy", "PHP"),
        array(1, "Andy", "C#"),
        array(2, "Josh", "C#"),
        array(2, "Josh", "ASP"),
        array(1, "Andy", "SQL"),
        array(3, "Steve", "SQL"),
    );

$grouped = array_group_by($data, function($i){  return $i[0]; });

var_dump($grouped);

?>


texts: Loading a pseudo-class instance from JSON

texts:
Is there a better way to do this?

function Person(name)
{
    this._type='Person';
    this.name=name;

    this.hello = function(){
        alert('Hello '+this.name);
    };
}

function object_to_instance(key, value)
{
    if (!value.hasOwnProperty('_type'))
        return value;

    var obj= eval('new '+value._type+'()');

    for (var property in value)
        obj[property]=value[property];
    return obj;
}

var people = [new Person('Harry'), new Person('Sally')];

var people_json = JSON.stringify(people);

var new_people = JSON.parse(people_json, object_to_instance);
new_people[0].hello();


texts:
I have to implement a "user-friendly" URL for an employment website. The URL /jobs{parameters?} may be composed of up to three searching criteria separated by hyphens (i.e. -); each criterion is separated by a tilde (i.e. ~). The parameters string has the following structure: -keywords-employmentTypes-locations. keywords and employmentTypes are optional. location is mandatory unless there are no parameters, the route should handle all these cases:

/jobs

/jobs-canada     /jobs-canada~paris~usa

/jobs-full_time-canada  /jobs-full_time~part_time-canada~paris
/jobs-engineer-canada  /jobs-engineer~c++-canada~paris

/jobs-engineer-full_time-canada  /jobs-engineer~c++-full_time-canada~paris

The following class parses the string parameters and fill all criteria in variables:

class JobUrlBuilder
{
    const DEFAULT_LOCATION = 'france';

    public $keywords;
    public $employmentTypes;
    public $locations;

    public $allEmploymentTypes;

    function __construct($allEmploymentTypes = [])
    {
        $this->setAllEmploymentTypes($allEmploymentTypes);
    }

    /**
     * @param string $parameters
    */
    public function setParameters($parameters)
    {
        $parameters = explode('-', ltrim($parameters, '-'));
        if (empty($parameters[0])) {
            array_shift($parameters);
        }

        if (count($parameters) === 3) {
            $this->keywords  = $parameters[0];
            $this->employmentTypes = $parameters[1];
            $this->locations = $parameters[2];
        } else if (count($parameters) === 2) {
            $areEmploymentTypes = $this->areEmploymentTypes(explode('~', $parameters[0]));

            $this->keywords  = $areEmploymentTypes ? null : $parameters[0];
            $this->employmentTypes = $areEmploymentTypes ? $parameters[0] : null;
            $this->locations = $parameters[1];
        } else if (count($parameters) === 1) {
            $this->keywords  = null;
            $this->employmentTypes = null;
            $this->locations = $parameters[0];
        } else {
            $this->keywords  = null;
            $this->employmentTypes = null;
            $this->locations = self::DEFAULT_LOCATION;
        }

        $this->keywords = $this->keywords ? explode('~', $this->keywords) : [];
        $this->employmentTypes = $this->employmentTypes ? explode('~', $this->employmentTypes) : [];
        $this->locations = $this->locations ? explode('~', $this->locations) : [];

        return $this;
    }

    /**
    * @param array $items
    */
    public function areEmploymentTypes($items)
    {
        $jobTypes = array_map(function ($v)
        {
            return mb_strtolower($v);
        }, $this->allEmploymentTypes);

        return ! array_diff($items, $jobTypes);
    }

    /**
    * @param array $employmentTypes
    */
    public function setAllEmploymentTypes($employmentTypes)
    {
        $this->allEmploymentTypes = $employmentTypes;
    }

    public function hasDefaultLocation()
    {
        return in_array(self::DEFAULT_LOCATION, $this->locations);
    }
}

I don't like this code (spaghetti code, no separation of concerns...). I think there is a better implementation. I'm also open to other URL structures - I know I can simply use input parameters and call it a day, but I should implement a clean URL. I have added unit tests to handle all cases. I think it might help you understand the code.


texts:
I'm trying to define parameters for my API. It's a super basic one and the first I've made. I'm trying to instantiate my class and set parameters but to me it seems super messy. Is this really the best way to set a bunch of properties on a class and check them?

API Class:

class Api {
    private $_fields;
    public  $parameters;

    public function __construct($fields) {
        // Set fields
        $this->_fields = $fields;

        // Define parameters and their defaults
        $aperture = $fields['aperture'] ? $fields['aperture']['value'] : null;
        $focalLength = $fields['focal_length']['value'] ? $fields['focal_length']['value'] : null;
        $calculatedAperture = $fields['aperture']['value'] ? $fields['aperture']['value'] * $fields['crop_factor']['value'] : null;

        $width = (float) $fields['width']['values'];
        $height = (float) $fields['height']['value'];
        $sensor = Api::getInfo(
            "sensors",
            "crop_factor",
            $fields["crop_factor"]["value"]
        );

        if (!$sensor) {
            $sensor = [
                'width' => $width ? $width : null,
                'height' => $height ? $height : null
            ];
        }

        // Set parameters
        $this->parameters = [
            'original' => [
                'aperture' => $aperture ? (float) $aperture : null,
                'focal_length' => $focalLength ? (float) $focalLength : null,
            ],
            'calculated' => [
                'aperture' => null,
                'focal_length' => (float) $fields['focal_length'] * $fields['crop_factor']['value']
            ],
            'crop_factor' => (float) $fields['crop_factor']['value'],
            'sensor' => $sensor ? $sensor : null
        ];

        var_dump($this->parameters);

        $this->responseJson = $this->checkFields();
    }
}

Sometimes certain parameters will contain nothing, so I'm using a ternary to check the value and then set something depending on the result. All parameters I'm going to use Type Juggling to make sure they are the type I want but that too seems super messy. I'm trying to avoid this whole nested ternary inside of ternary but I don't see a way to avoid it.

I would also like to say here that this code does work, although I haven't gone through and made every check.


texts:
Purpose of Code: To simulate scraping the web and updating a db, by, presently, adding randomly generated numbers to a "database".

Have I wired up the followin async code properly? Is there a simpler, more composable way to pass objects around? Or some more idiomatic way?

I have added comments to self-explanatory code to hopefully make it a titch easier on reviewers.

Note: the following mocks what will become a web scraper. So just be aware that the "db" isn't a real db, and "fetching urls" refers to a mock up that will eventually get swapped out, but I hope you see the semantics I intend to sub in.

(ns clj-scraper.core
  (:require [clojure.core.async :as a :refer [>! <! >!! <!! go go-loop chan
                                              buffer close! thread alts!
                                              alts!! timeout
                                              put! take!
                                              pipe pipeline pipeline-async pipeline-blocking]]))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Database - a mockup of what could be a db

(def test-db (agent {:1 {:url  "abc"
                         :vals []}
                     :2 {:url  "bac"
                         :vals []}
                     :3 {:url  "pg"
                         :vals []}))

; append to a path in the test-db
(defn test-append [path x] (send test-db update-in path (partial cons x)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Load from DB

; objects start their journey on this channel
(def db-objs> (chan 1))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Fetch URLs

; test-data mocks fetching a url by returning the string of a random int
(defn test-data [_] (str (rand-int 100)))

(def pages> (chan 1))
(pipeline 4
          pages>
          ; add the fetched page to the object getting passed around
          (map (fn [{:keys [url] :as obj}]
                 (conj obj {:page (test-data url)})))
          db-objs>)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CSS Select Page

; this mock up simply converts a String -> Int
(defn test-select [x] (Integer. x))

(def selections> (chan 1))
(pipeline 4
          selections>
          ; add the converted String to the object getting passed around
          (map (fn [{:keys [page] :as obj}]
                 (conj obj {:scraped (test-select page)})))
          pages>)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Update DB

; add the "scraped value" to the "db"
(go-loop []
  (let [{:keys [id scraped]} (<! selections>)]
    (test-append [id :vals] scraped))
  (recur))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Run Things in Debugging

(doseq [[id data] @test-db] (go (>! db-objs> (conj data {:id id}))))
@test-db ; won't show expected results until async ops are done


texts: Start the Python interpreter with an import statement

texts:
When I'm writing Python, I wanna be able to pull up an interpreter quickly, and import what I need easily. Previously, this involved:

bash4.3 $ python3
>>> import os, sys, readline, lxml

I was irked by the amount of typing in that, so I wrote a couple of tiny bash functions that live in my .bashrc, so I can just do (for example):

bash4.3 $ from os import path
>>>
from os import path: success!
>>>

or:

bash4.3 $ import os, sys, readline, lxml
>>>
imported os, sys, readline, lxml
>>>

Perhaps this might be regarded by some as a non-issue, but for my workflow when I just want to test something quickly, it's really handy.

The functions:

function import () {
  ARGS=$*
  ARGS=$(python3 -c "import re;print(', '.join(re.findall(r'([\d\w]+)[, ]*', '$ARGS')))")
  echo -ne '\0x04' | python3 -i
  python3 -c "import $ARGS" &> /dev/null
  if [[ $? != 0 ]]; then
    echo "sorry, junk module in list"
  else
    echo "imported $ARGS"
  fi
  python3 -i -c "import $ARGS"
}

function from () {
  ARGS=$*
  ARGS=$(python3 -c "import re; s = '$ARGS'.replace(',', ', '); args = ' '.join(re.findall(r'^([\d\w]+) import ([\d\w, ]+)$', s)[0]).split(' '); print('from', args[0], 'import', ' '.join(args[1:]).replace(',', '').replace(' ', ','))")
  echo -ne '\0x04' | python3 -i
  python3 -c "$ARGS" &> /dev/null
  if [[ $? != 0 ]]; then
    echo "junk module in list"
  else
    echo "$ARGS: success!"
  fi
  python3 -i -c "$ARGS"
}

I'm aware python3 -m module exists, however, it requires module to be a fully-fledged module, with an __init__.py and stuff.  If I'm writing a small script that isn't really designed to be a module (i.e, that has module-level expressions that will be run if the module is imported), then I want to import it normally, not with -m.

I'm also aware I could use && and || for short-circuiting over if [[ ]]; then; fi but I consider this more readable.

I'm looking for responses about any part, really, but I'd be most interested to hear whether I'm unknowingly abusing bash in some way (quoting, perhaps?) and about the probable inefficiency of the Python code I'm using to process / sanitise the args.

I'd also be happy to hear about corner cases not caught by my regex / parsing job, and how they sudo rm -rf --no-preserve-root /-ed you.


texts: Web-crawler for yellowpage designed using python

texts:
I've written some code to scrape name, address, and phone number from yellowpage using python. This scraper has got input parameter. If the input is properly filled in and the filled in url exists in yellowpage then the scraper will definitely parse the three categories I mentioned earlier. I tried to make it maintaining the guidelines of OOP. It is working specklessly at this moment. Hope there is something to do betterment of this crawler:

import requests
from lxml import html

class YellowPage:
    @classmethod
    def Crawl(self, name, state):
        page = requests.get("https://www.yellowpages.com/search?search_terms=" + name + "&geo_location_terms=" + state).text
        tree = html.fromstring(page)
        for items in tree.xpath("//div[@class='info']"):
            name = items.findtext(".//span[@itemprop='name']")
            address = items.findtext(".//span[@class='street-address']")
            phone = items.findtext(".//div[@itemprop='telephone']")
            print(name, address, phone)

YellowPage.Crawl("pizza","florida")


texts: Adding time offsets to create future dates

texts:
How can I shorten this (working) code to create future dates in ruby for use as params in URLs?

I'm doing:

require 'cgi'
require 'time'

now=Time.new()
now_year=now.strftime('%Y').to_i
now_month=now.strftime('%m').to_i
now_day=now.strftime('%d').to_i
now_hour=now.strftime('%H').to_i

start_hour=(now_hour + 1)
end_hour=(now_hour + 2)

start_datetime=Time.new(now_year, now_month, now_day, start_hour)
end_datetime=Time.new(now_year, now_month, now_day, end_hour)

starts=CGI.escape(start_datetime.utc.strftime("%Y-%m-%dT%H:%M:%S.%3NZ"))
ends=CGI.escape(end_datetime.utc.strftime("%Y-%m-%dT%H:%M:%S.%3NZ"))

and it works, but it seems long and clumsy.  Is there an easier way?


texts: Faster way to perform function calculation in Python?

texts:
I'm interested in whether there is a way to further improve a "fast" version of a function used in a homework assignment I received recently (I've already submitted the completed work).

from math import log

def func_fast(mass, density):
    return sum(map((log(mass * density)).__truediv__, range(1,10001)))

def func_slow(mass, density):
    total = 0.0
    for i in range(10000):
        masslog = log(mass * density)
        total += masslog/(i+1)

    return total

mass = 2.5
density = 12.0

The fast version times in around 2-2.5ish seconds while the slow version nets 6-7 seconds.


texts: Toggle functions for drop down for a clock time widget

texts:
I'm fairly new to JQuery/JavaScript and I'm trying to refactor the following code:

$('#hour').click(function() {
  $('#clockHours').slideToggle();
  $('#clockMinutes').hide();
});

$('#minutes').click(function() {
  $('#clockMinutes').slideToggle();
  $('#clockHours').hide();
});

//print clicked onto views
$('.timeSelect').click(function() {
  var text = $( this ).text();
  $('#hourView').val( text );
});

$('.minuteSelect').click(function() {
  var text = $( this ).text();
  $('#minuteView').val( text );
});

I haven't had much luck figuring out how to improve the code. Here is a CodePen of the current working code and here's what I have tried.


texts:
I'm new to Go, so I implemented a few sorting algorithms for practice. For example, I have an in-place insertion sort, and a bubble sort:

func bubbleSort(arr []int) {
   for i := 1; i < len(arr); i++ {
      if arr[i] < arr[i - 1] {
            tmp := arr[i - 1]
            arr[i - 1] = arr[i]
            arr[i] = tmp
            i = 0
      }
   }
}

func insertionSort(arr []int) {
   for i := 0; i < len(arr); i++ {
      for j := 0; j < i; j++ {
         if arr[j] > arr[i] {
           tmp := arr[j]
           arr[j] = arr[i]
           arr[i] = tmp
         }
      }
   }
}

However, when I went to implement merge sort, I found it most natural to use return values, because I couldn't seem to find a clean way to merge the results in place. Is there a good way to do this in Go, and would it even make sense to do so in-place? Or would it lead to difficulties when attempting to move to a concurrent implementation using goroutines? Code:

func merge(pt1 []int, pt2 []int) []int {
   totalLen := len(pt1) + len(pt2)
   arr := []int{}

   for i := 0; i < totalLen; i++ {
      // remove the smallest from the 2 slices and add it to the final
      if pt1[0] < pt2[0] {
         arr = append(arr, pt1[0])
         pt1 = pt1[1:]
      } else {
         arr = append(arr, pt2[0])
         pt2 = pt2[1:]
      }

      // break if a slice has been emptied
      if len(pt1) == 0 || len(pt2) == 0 {
         break
      }
   }

   arr = append(arr, pt1...)
   return append(arr, pt2...)
}

// merge sort algorithm
func mergeSort(arr []int) []int {
   arrLen := len(arr)

   if arrLen > 1 {
      pt1 := mergeSort(arr[arrLen/2:])
      pt2 := mergeSort(arr[:arrLen/2])
      arr = merge(pt1, pt2)
   }

   return arr
}

Any general style tips are also greatly appreciated (link to full code).


texts: User input validation that might be unbreakable for C++

texts:
I am new to programming and have been having a lot of trouble with user input validation. Everything I found online I could break and I finally put this function together that appears to be unbreakable. It is for int and double specifically.

I am curious about how it might be critiqued by experienced programmers. How did I do? What can be improved? What are some issues I might run into? One issue I ran into was when I #include<Windows.h>, max() becomes an issue in this code, so I had to use #define NOMINMAX. I wonder if there is a way around that as well. I am using this code with Visual C++ in Visual Studio.

#include<iostream>
#include<string>
#include<limits>

using namespace std;

template<class T>
void input(T& input, int low, int high, string message)
{
input = low - 1;
while (input < low || input > high)
{
    cout << message;
    while ((cin >> input).fail() || cin.peek() != '\n')
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << message;
    }
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}


texts: Update single common column in multiple has-many relationships rails

texts:
I want to update a single column in 4 tables. All relationships are has-many among them.

Private schools has many private classes
Private classes has many lesson plans
Lesson plans has many quizzes
Lesson plans has many documents

The code I am working with is:

@private_school.private_classes.each do |private_class|
            private_class.lesson_plans.each do |lesson_plan|
              lesson_plan.update_attribute("price_type", @private_school.price_type)
              lesson_plan.quizzes.update_attribute("price_type", @private_school.price_type)
              lesson_plan.documents.update_attribute("price_type", @private_school.price_type)
            end
          end

Is this a best approach to follow or is there any more option to tackle this? What are best practices about this scenario?


texts: Is this implementation of the ECIES cipher correct?

texts:
I downloaded source code of cryptosms and implemented the ECIES cipher in my work for Java mobile.

I doubt validity of this step (full code of my method is below):

        engine.init(true, (CipherParameters) k, (CipherParameters) pubKey,
                new IESParameters(Z.getX().toBigInteger().toByteArray(), R
                        .getQ().getEncoded(), 64)); //here is the problem

In particular the line that I commented: is that correct way to implement ECIES? All works ok but I have a suspect that it doesn't share the secret KDF in secure mode.

The project is dead and I can't contact authors.

 public byte[] cifra(byte[] data, byte[] key) throws Exception {

        boolean failure = true;
        ECDomainParameters domainParams= EllipticUtils.getECDomainParameters();
        IESEngine engine = new IESEngine(new ECDHBasicAgreement(),
                new KDF2BytesGenerator(new SHA1Digest()), new HMac(
                        new SHA1Digest()));

        ECPoint publicPoint = domainParams.getCurve().decodePoint(key);
        ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                publicPoint, domainParams);
        ECPrivateKeyParameters k = null;
        ECPublicKeyParameters R = null;
        ECPoint Z = null;

        SHA256SecureRandom PRNG = SHA256SecureRandom.getIstance();
        PRNG.initPRNG();

        while (failure) {

            BigInteger privNum = new BigInteger(PRNG.getPRNG()
                    .generateSeed(16
                            ));

            k = new ECPrivateKeyParameters(privNum, domainParams); // this is
            // just a container
            R = EllipticUtils.generatePublicKey(k); // R = kP

            // calculate Z=hkQ
            BigInteger z = new BigInteger(domainParams.getH().toByteArray()); // z=h
            z = z.multiply(privNum); // z=hk

            Z = pubKey.getQ(); // Z=Q
            if (Z instanceof ECPoint.F2m) {
                ECPoint.F2m Z2 = new ECPoint.F2m(Z.getCurve(), Z.getX(), Z
                        .getY()); // clone
                Z = Z2.multiply(z); // Z=zQ <=> Z=hkQ
            }
            if (Z instanceof ECPoint.Fp) {
                ECPoint.Fp Z2 = new ECPoint.Fp(Z.getCurve(), Z.getX(), Z
                        .getY()); // clone
                Z = Z2.multiply(z); // Z=zQ <=> Z=hkQ
            }
            if (!Z.isInfinity())
                failure = false; // see step 2
        }

        // step 3 and 4:
        // setup KDF(xz,R) - see new IESParameters(...)
        // pass the parameters for step4
        engine.init(true, (CipherParameters) k, (CipherParameters) pubKey,
                new IESParameters(Z.getX().toBigInteger().toByteArray(), R
                        .getQ().getEncoded(), 64)); //here is the problem

        // step 4 generate C and t
        byte[] cAndT = engine.processBlock(data, 0, data.length);

        // collect the result in format
        // byte[0] = length of R (encoded)
        // R in encoded form
        // C and t as coming from the engine
        byte[] publicBytes = R.getQ().getEncoded();
        byte[] out = new byte[1 + publicBytes.length + cAndT.length];

        out[0] = (byte) publicBytes.length; // WARN this will crash if
        // key.length > 255
        System.arraycopy(publicBytes, 0, out, 1, publicBytes.length);
        System.arraycopy(cAndT, 0, out, 1 + publicBytes.length,
                cAndT.length);

        return out;
}


texts:
I am working on an iOS project and I'm in charge of testing most parts of it. As I write some tests, I often have the need to wait for an asynchronous method to finish, and then test that something did not happen.

For example, try to login with an invalid username and password, wait until the network communications are finished, then test that the user was not able to login

Swift has some nifty methods for testing these sort of things; the ones I use the most are expectationForPredicate and waitForExpectationsWithTimeout. These methods are good for testing that something happened after the asynchronous method finishes. However, to test that something did not happen (which is what I want), there doesn't seem to be anything designed specifically for this.

I can't use predicates because that will cause the test to timeout early
I cannot modify the code being tested because it is an app lifecycle callback and we testers generally do not modify any code, we just test

Which is why I designed this method

extension XCTestCase {
    func waitFalseExpectationsUntilTimeout(timeout: NSTimeInterval, expectations: [XCTestExpectation], handler: XCWaitCompletionHandler?) {

        class CompleteSelector {
            @objc func fullFillExpectations(timer: NSTimer) {
                let expectations = timer.userInfo as! [XCTestExpectation]
                for expc in expectations {
                    expc.fulfill()
                }
            }
        }

        let smaller = timeout < 0 ? 0 : timeout.advancedBy(-0.5)

        NSTimer.scheduledTimerWithTimeInterval(smaller, target: CompleteSelector(), selector:
            Selector("fullFillExpectations:"), userInfo: expectations, repeats: false)

        waitForExpectationsWithTimeout(timeout, handler: handler)
    }
}

The main thing the function does is to schedule a timer and fulfill all expectations just before the waitForExpectationsWithTimeout method times out. Is this the best way to deal with this situation? What can I improve with this method (apart from commenting)? Any concurrency issues I should be worried about?

To add some context, waitForExpectationsWithTimeout will cause the test to fail if non of the expectations are fulfilled before it timesout, which is why I had to fulfill all expectations just before this timeout occurs


texts: Using Python to rename multiple csv files in Windows

texts:
I need to rename a large list of csv files that are generated from 3 different servers. The files are produced with a date stamp as the extension, which I need to move in each file name to retain the date stamp.
The file name format before editing is as:

billing.pps-svr01.csv.2015-09-01
billing.pps-svr02.csv.2015-09-01
billing.pps-svr03.csv.2015-09-01

The file name format after editing should be:

billing.pps-svr01.2015-09-01.csv
billing.pps-svr02.2015-09-01.csv
billing.pps-svr03.2015-09-01.csv

My question is in regard to code efficiency and best practice. The following code seems to work in testing, however I'm very new to Python and programming in general and I'd like to know if there are any other ways to solve this problem that are more efficient...for example, could this be accomplished in a one-liner or something else? I should also note that I intend to incorporate this into a much larger script that parses these files after they've been renamed. Any feedback and/or suggestions would be great.
import os

os.chdir(r'C:\Users\Extract')

for filename in os.listdir('.'):
    if filename.startswith('billing.pps-svr'):
        name = filename.split('.')
        name = name+[name.pop(0-2)]
        new_name = '.'.join(name)
        os.rename(filename, new_name)


texts:
From some generated code I get a
javax.xml.datatype.XMLGregorianCalendar and I want to convert it to a LocalDateTime without any zone-offset (UTC).
My current code accomplishes it, but I think it must be possible to acheaf the same result in a more elegant (and shorter) way.
    public static LocalDateTime xmlGregorianCalendar2LocalDateTime(XMLGregorianCalendar xgc) {
        // fix the time to UTC:
        final int offsetSeconds = xgc.toGregorianCalendar().toZonedDateTime().getOffset().getTotalSeconds();
        final LocalDateTime localDateTime = xgc.toGregorianCalendar().toZonedDateTime().toLocalDateTime(); // this simply ignores the timeZone
        return localDateTime.minusSeconds(offsetSeconds); // ajust according to the time-zone offet
    }


texts: Password strength checker (Udemy course)

texts:
This program is a project out of Udemy course. Kindly request you to review my code and suggest insights to better it. It takes your password hashes (sha1) and then sends hashedpassword[:5] to https://haveibeenpwned.com/ website. Gets the response and checks whether our hashed password is present in the response got from the site
Thanks in advance!!
import requests
from ezhashlib import hashlib
import sys

def req_api_data(query_char):

   '''Returns response for pwned website after passing the tail'''
    url = 'https://api.pwnedpasswords.com/range/' + query_char
    res = requests.get(url)
    if res.status_code!=200:
        raise RuntimeError(f'Error fetching: {res.status_code}, check the api and try again')
    else:
        return res

def get_pw_lead_count(hashes,hashes_to_check):

    hashes = (line.split(':') for line in hashes.text.splitlines())# Splits the responsex
    for h,count in hashes:
        if hashes_to_check == h:
                  return count
    return 0

def pwned_api_check(password):

    sha1password = hashlib.sha1(password.encode('utf-8 ')).hexdigest().upper()
    # Generatng the sha1 for your password
    head,tail = sha1password[:5],sha1password[5:]
    res = req_api_data(head)
    #sending the head to website
    return get_pw_lead_count(res,tail)
    #Sending website response and tail for checking whether tail exists in the list of responses got from website.

def main():

    args=list(input().split())
    for passwords in args:
        count = pwned_api_check(passwords)
        if count:
             print(f"Change your \"{passwords}\" password as it's pwned {count} times")
        else:
            print("You've used a good password!!")

main()


texts:
I like to know if there will be any performance issue if an xmlhttp object is created every time.  For example, in the below code:

function currentTime(){
    var obj = null;

    if(window.XMLHttpRequest){
        obj = new XMLHttpRequest();
    } else {
        obj = new ActiveXObject("Microsoft.XMLHTTP");
    }

    obj.open("GET", "current_time.php", true);
    obj.send(null);
    obj.onreadystatechange = function(){

        if(obj.readyState == 4 && obj.status == 200){
            var element = document.getElementById("current_time");
            element.innerHTML = obj.responseText;
        }
    };
}

setInterval("currentTime();", 1000);

or

var obj = null;
function createObj(){
    if(window.XMLHttpRequest){
        obj = new XMLHttpRequest();
    } else {
        obj = new ActiveXObject("Microsoft.XMLHTTP");
     }
}

function currentTime(){
     obj.open("GET", "current_time.php", true);
     obj.send(null);
     obj.onreadystatechange = function(){

        if(obj.readyState == 4 && obj.status == 200){
            var element = document.getElementById("current_time");
            element.innerHTML = obj.responseText;
        }
    };
}

createObj();
setInterval("currentTime();", 1000);

In the first example, the XMLHttpRequest object is created every time (1 sec).

In the second example, the object is created once.


texts: Is this the right way to space four news blocks right from each other?

texts:
I am working on a website and I've created four text/image news blocks.  I am not sure if it's the right / most efficient way to do this.

See my code here at jsfiddle

HTML:

Lorem ipsum dolor sit amet, consectetur adipisicing elit

Lorem ipsum dolor sit amet, consectetur adipisicing elit

Lorem ipsum dolor sit amet, consectetur adipisicing elit

Lorem ipsum dolor sit amet, consectetur adipisicing elit

        fasdfasf

CSS:

body{
background: url("../img/bg.jpg") repeat-x;
}

#wrapper{
margin: 0 auto;
width: 980px;
}

#header{
float: left;
width: 100%;
height: 70px;
}

#logo img{
float: left;
margin-top: 20px;
}

#headNews{
float: left;
margin-top: 20px

}

.headNewsItem{
float: left;
margin-right: 4px;
width: 242px;
height: 184px;
}

#headNewsItemLast{
float: left;
width: 242px;
height: 184px;
}

.headNewsItem  img {
display: block;
}

#headNewsItemLast img{
display: block;
}

.textContainer{
font-family: Arial;
line-height: 21px;
font-size: 14px;
color: #c8cbcb;
height: 40px;
padding: 10px 15px;
background-image: linear-gradient(#262828,#1c1e1e);
}

#midSection{
float:left;
width: 100%;
height: 800px;
margin-top: 20px;
background-color: #FFF;

}


texts: Node.js error handling using merely if else without try catch

texts:
I'm confused why you need to use try catch. I made a simply utils like this, and use it on my models' callback.

in my utils/error.js

module.exports.handleError = (err, errMsg, res) => {
    res.json({
        success: false,
        msg: `${errMsg}. ${err}`
    })
}

Then I have this in my router controller

router.get('/tasks', (req, res) => {

    Task.getTasks((err, resp) => {
        if(err){
            return handleError(err, 'Failed to get tasks', res)
        }

        res.json({
            success: true,
            msg: {tasks: resp}
        })
    })
})

What can be improved? And what is the drawback of using this approach?


texts: Adapter class displaying characters' info

texts:
I have finished creating an adapter class which displays characters' info.
When I looked back and reviewed my own code, I think the code fragment below somehow could be broken into smaller methods.

...
private static class ViewHolder {
    ImageView imgIconState;
    ImageView imgCharacterStatus;
    TextView txtName;
}

@Override
public View getView(int index, View view, ViewGroup viewGroup) {
    ViewHolder characterProfile;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.character_item, null);
        characterProfile = new ViewHolder();
        characterProfile.imgIconState = (ImageView) view.findViewById(R.id.icon_state);
        characterProfile.imgCharacterStatus = (ImageView) view.findViewById(R.id.character_state);
        characterProfile.txtName = (TextView) view.findViewById(R.id.name);
        view.setTag(characterProfile);
    } else {
        characterProfile = (ViewHolder) view.getTag();
    }

    Character character =  mLeBluetoothLightsList.get(index);
    characterProfile.imgIconState.setImageResource(mIconStateRrs[character.getIconStatus()]);
    characterProfile.imgCharacterStatus.setImageResource(character.isAlive() ? R.drawable.alive : R.drawable.dead);
    characterProfile.txtName.setText(character.getCharacterName());

    if (Config.IS_DEBUG) {
        Log.i(mClassName, "getView - Index: " + index
                + "| Icon status: " + character.getIconStatusForLog()
                + "| Character status: " + character.isAliveForLog()
                + "| Name: " + character.getCharacterName());
    }

    return view;
}
...

I am attempting to write a 3 to 10 lines function, but I find it hard to break it smaller.

Should I refactor this or leave it as it is? If the answer is the former, please give me some advice.


texts: Using setTimeout to get scrolling chat window to work, but doesn't feel like the ideal solution

texts:
My friend and I are working on a bare-bones chat web app, using Angular on the front end. He's using Swampdragon for some of the real-time stuff.

My task that I set out to achieve was to get the chat window to scroll to the bottom when a chat room is loaded (most relevant bit is $dragon.onChannelMessage):

app.controller('ChatRoomCtrl',
        ['$scope', '$dragon', 'ChatStatus', 'Users', function (
            $scope, $dragon, ChatStatus, Users) {
    $scope.channel = 'messages';
    $scope.ChatStatus = ChatStatus;

    $scope.idToUser = function(id) {
        var user;
        user = $scope.users.filter(function(obj) {
            return obj.pk == id;
        });
        return user[0].display_name;
    };
    Users.getList().then(function(users) {
        $scope.users = users;
    });

    $dragon.onReady(function() {
        $dragon.subscribe('messages', $scope.channel).then(function(response) {
            $scope.dataMapper = new DataMapper(response.data);
        });
    });

    $dragon.onChannelMessage(function(channels, message) {
        if (indexOf.call(channels, $scope.channel) > -1) {
            if (ChatStatus.messages[message.data.room].indexOf(message.data) == -1) {
                message.data.posted = new Date(message.data.posted);
                $scope.$apply(function() {
                    ChatStatus.messages[message.data.room].push(message.data);

                    setTimeout(function() {
                        scrollToBottom();
                    }, 30);
                });
            }
        }
    });
}]);

Or, when a new message is pushed:

app.controller('RoomCtrl', ['$scope', 'Rooms', 'Messages', 'ChatStatus', function($scope, Rooms, Messages, ChatStatus) {
    $scope.changeRoom = function(room) {
        ChatStatus.selectedRoom = room;
        Messages.getList({'room': room.id}).then(function(messages) {
            angular.forEach(messages, function(message, key) {
                message.posted = new Date(message.posted);
            });
            ChatStatus.messages[room.id] = messages;

            setTimeout(function() {
                scrollToBottom();
            }, 30);
        });
    }
    $scope.rooms = Rooms.getList()
    .then(function(rooms) {
        ChatStatus.rooms = rooms;
        ChatStatus.selectedRoom = rooms[0];
        $scope.rooms = rooms;
    })
}]);

In both controllers, I refer to the scrollToBottom function:

function scrollToBottom() {
    var chatWindow = document.querySelector('.the-chats');
    var mostRecent = chatWindow.querySelector('li:last-child');
    var mostRecentDimensions = mostRecent.getBoundingClientRect();
    var chatWindowScrollY = chatWindow.scrollTop;

    chatWindow.scrollTop = mostRecentDimensions.bottom + chatWindowScrollY;
}

If I remove the setTimeout from the first controller, it'll scroll to what is the last item in the list before the new message is pushed, while the second controller will error out.

If the setTimeout is in place, this does what I want it to do. However, it feels like a bad solution; it certainly doesn't feel like an 'Angular' way.

I've read a bit about promises, deferred objects, $q, etc., but the examples always seem to use it in the context of AJAX-types of calls, so I don't know if that applies here. But that's really what I'm looking for, right? Push the new message, then do the scroll?


texts:
I have kinda problem with oop in c#, I need to do a task to school but I completely new in oop. At this moment I have no idea how I can even start this, I mean I don't know how to make that program counts people... like e.g. click spacebar and it will make counter of people increase. Maybe someone could help me to solve this out. The task is:

Create a class(called Counter) that will check how many people entered the building(like the gate in the entrance counts how many people entered or how many is inside already). The class should contain a methods that will singly increase amount of people or singly decreases amount of them, the third method should show how many is inside already. Last but not least, the constructor for counter should be set as 0.

I managed to create some code, I'm not sure if it's good solution for this task, for sure there's a way to make it better, or to optimize this, I still learn this, so I just ask you guys for the opinion about it, or maybe some hints.

Sorry for my broken English!

using System;

namespace zaliczenie6test
 {
    class Program
     {
       static void Main(string[] args)
        {
           Counter gate = new Counter();
           char wybor;

            Console.WriteLine("If you want to enter the building(through
            the gate) press 'p', if you want to leave the building press
            'd', if you want check how many people is inside press 'c'
             : ");
        do
        {
            Console.Write("Enter your choice: ");
            wybor = char.Parse(Console.ReadLine());
            if (wybor == 'p')
            {
                Counter gate2 = new Counter();
                gate2.IncNr(wybor);
                gate.Count(wybor);
            }
            else if(wybor == 'd')
            {
                Counter gate3 = new Counter();
                gate3.DecNr(wybor);
                gate.Count(wybor);
            }
        } while (wybor != 'c');
        if (wybor == 'c')
        {
            gate.CheckNr(wybor);
        }

        Console.ReadKey();
    }
}

   class Counter
  {
    private int _licznik;
    private int quantity;
    public int Licznik { get { return _licznik; } set { _licznik =
    value; }
  }

    public Counter()
    {
        _licznik = 0;
    }

    public void IncNr(char wybor)
    {
        if(wybor=='p')
        {
            Licznik += 1;
            Console.WriteLine("The amount of people that just enteredthe
            building through the gate: {0}\n",Licznik);
        }
    }
    public void CheckNr(char wybor)
    {
        if(wybor=='c')
        {
            Console.WriteLine("The current amount of people: {0}",
            quantity);
        }
    }

    public void Count(char wybor)
    {
        if(wybor == 'p')
        {
            quantity += 1;

        }
        else if(wybor == 'd')
        {
            quantity -= 1;
        }
    }

    public void DecNr(char wybor)
    {
        if(wybor == 'd')
        {
            Licznik += 1;
            Console.WriteLine("The amount of people that just passed the
            gate toward the exit is: {0}\n", Licznik);
        }
    }
  }
}


texts:
I have managed to build an inheritance hierarchy for shape class object and I am wondering if there is a better solution to combine the following 2 hierarchies.

To begin, I have a 4 shapes classes triangle, line, oval and square which 3 of (line, oval and square) inherit from abstract class SimpleTwoPointShape and this abstract class with triangle class inherits from an abstract class SimpleShape. In addition triangle, oval and square classes implement SimpleShapeAreaInterface interface. The objects of the classes are created when there are enough points (x,y) to draw the shape (which is selected to draw at that time, as each shape has the necessary number of points to draw it). Points are putted on a canvas as my class where the drawings are being done extend JPanel and override paintComponent.

As the necessary number of points are putted on the canvas the shape is created with all the necessary details and is added to a List and repaint is called, which causes the paintComponent method to be called where inside a loop that loops through all shapes and depending on which kind of shape it is creates a corresponding wrapper class object (triangleDrawer, lineDrawer, ovalDrawer and squareDrawer) which have the method to draw the shape. This 4 wrapper class inherit from an abstract class SimpleDrawer (has a setColor method) and the abstract class implements interface ShapeDrawerInterface which has the draw method.

private class MouseWatcher extends MouseAdapter {

        public void mousePressed(MouseEvent e) {
            // reset the rotation to 0 otherwise things get messy.
            currentRotation = 0;

            if (currentPoints == null) { // must be starting a new shape
                currentPoints = new ArrayList<>();
                Point firstPoint = new Point();
                firstPoint.x = e.getX();
                firstPoint.y = e.getY();
                currentPoints.add(firstPoint);
            } else {
                Point nextPoint = new Point();
                nextPoint.x = e.getX();
                nextPoint.y = e.getY();
                currentPoints.add(nextPoint);
                if (currentPoints.size() == shapeToDraw.getNumberOfPoints()) {
                    shapeToDraw.setVertices(currentPoints);
                    shapeToDraw.setColour(main.getCurrentColor());
                    shapeToDraw.setThickness(main.getCurrentThickness());
                    shapeToDraw.setShapeType(currentShapeType);
                    shapes.add(shapeToDraw);
                    setCurrentShapeType(currentShapeType);
                    currentPoints = null;
                }
            }
            //repaint(); // causes paintComponent() to be called
        }
    }

@Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // Graphics2D needed to set line thickness
        Graphics2D g2d = (Graphics2D) g;

        Stroke s = g2d.getStroke(); // save stroke to restore later

        // rotate the drawing by the current rotation amount
        double rotateTheta;
        rotateTheta = currentRotation * Math.PI / 180;
        g2d.rotate(rotateTheta, this.getWidth() / 2, this.getHeight() / 2);

        // Loop though the ArrayList drawing
        // all the shapes stored in it
        for(int i=0;i<shapes.size();i++){
            new ContextDrawing(drawingFactory.getDraweShape(shapes.get(i))).executeStrategy(g2d, currentBrightness);
        }

        g2d.setStroke(s);  // restore saved stroke
        if (currentPoints != null) { // draw dot where line started
            g2d.setColor(currentColor);
            for (int i = 0; i < currentPoints.size(); i++) {
                g2d.fillOval(currentPoints.get(i).x, currentPoints.get(i).y, 3, 3);
            }
        }
    }

The hierarchy so far for this is as fallows:

Is there a better inheritance hierarchy to use for this classes? Are there any design patterns apart from factory that can apply here?


texts: measuring the time taken to copy a std stl container

texts:
I'm trying to measure the time taken to copy a std::vector<someObject>. Would like to know if this is a correct approach. I tried to do some trivial computations on the copy to prevent the compiler from optimizing out the copy. Should I explicitly write a copy-constructor?

#include <iostream>
#include <new>
#include <chrono>
#include <algorithm>
#include <random>
#include <vector>
using namespace std;

int NUM_OF_ELEMENTS;
int NUM_OF_TRIALS;
char CONTAINER_TYPE;

template<size_t OBJECT_SIZE>
class NonPrimitiveType
{
public:
    int x[OBJECT_SIZE/4];
    NonPrimitiveType()
    {
        for(int i=0;i<OBJECT_SIZE/4;i++)
        {
            x[i] = i;
        }
    }
};

template <typename T, size_t OBJECT_SIZE>
void copyContainer()
{
    T container;
    container.reserve(NUM_OF_ELEMENTS);
    for (int i=0;i<NUM_OF_ELEMENTS;i++)
    {
        container.push_back(*(new NonPrimitiveType<OBJECT_SIZE>));
    }

    long long hash = 0;
    auto begin = chrono::high_resolution_clock::now();
    for (int i=0;i<NUM_OF_TRIALS;i++)
    {
        T copy = container;
        hash = hash + copy.at(0).x[1];
    }
    auto end = chrono::high_resolution_clock::now();
    long long totalTime = chrono::duration_cast<chrono::nanoseconds>(end - begin).count() / NUM_OF_TRIALS;
    printf("%c;%d;%d;%lu;%llu\n",CONTAINER_TYPE, NUM_OF_ELEMENTS, (int)OBJECT_SIZE, totalTime, hash);
}

int main(int argc, char *argv[])
{
    NUM_OF_ELEMENTS = atoi(argv[1]);
    CONTAINER_TYPE = *argv[2];
    NUM_OF_TRIALS = atoi(argv[3]);

    copyContainer<vector<NonPrimitiveType<16>>, 16>();
    copyContainer<vector<NonPrimitiveType<64>>, 64>();
    copyContainer<vector<NonPrimitiveType<256>>, 256>();
    copyContainer<vector<NonPrimitiveType<1024>>, 1024>();
    copyContainer<vector<NonPrimitiveType<4096>>, 4096>();

    return 0;
}


texts:
I got this basic script which I'll be using to check if the answer is right. The only problem is that I'll be using with many forms. That's why I need this code to be more like DRY code.

            function checkAnswer()
        {
            var answer = document.getElementById("answer").value;
            if (answer.toLowerCase() == "correct answer")
            {
                alert("Well done!");
            }
            else
            {
                alert("Too bad!");
            }

            var answer2 = document.getElementById("answer2").value;
                     if (answer2.toLowerCase() == "correct answer")
            {
                alert("Well done!");
            }
            else
            {
                alert("Too bad!");
            }

            var answer3 = document.getElementById("answer3").value;
            if (answer3.toLowerCase() == "correct answer")
            {
                alert("Well done!");
            }
            else
            {
                alert("Too bad!");
            }
        }


texts: Caching an integer - distinguishing no value from zero

texts:
I would like to store an integer value in the application cache.

The GetOrSet method should always return an int, and never be null. If there is no cached value, then the getDataCallback function will provide the integer.

But I need the cache check to return a nullable int in order to distinguish no value from a 0 integer value.

I am looking for any faults in the code below, or possible improvements.

It probably looks very simple to others, but I find working with nullable ints quite confusing.

public int GetOrSet(string cacheKey, Func<int> getDataCallback)
{
    int? data = (int?)HttpContext.Current.Application[cacheKey]; // this should return null if there is no value stored in the cache
    if (! data.HasValue)
    {
        int intData = getDataCallback();
        HttpContext.Current.Application[cacheKey] = intData;
        return intData;
    }
    else
    {
        return data.Value;
    }
}

Update

Big thanks to both @Nkosi and @Flater for their help.

I marked @Flater's answer as correct because I had to chose one only. But I really hated having to do this as both answers were equally helpful and I used both their suggestions in the end.  I would encourage anybody reading this to check them both out.


texts: Caesar Cipher encoding process (customizable input and shifting) in Python

texts:
So this code already works, but I would like to shorten it using list comprehension. Would it be better if it was in 1 line, or many? (I do know that readability is more important than short code, but I would like to master list comprehension, ternary operators, and conditional expressions).
Oh yes, if there is ANYTHING I can do to make my code better, more efficient, more readable and shorter, I would LOVE to know!

#Caesar Cipher, only lowercase and spaces
listString = [x for x in input('What would you like to encode? ')]
change = int(input('How much would you like to shift? '))
change %= 26
def encode(listString,change):
  encoded = []
  for c in listString:
    if ord(c) + change > 122:
      encoded.append(chr(ord(c) + (change - 26)))
      continue
    encoded = [" " if x == chr(32 + change) else x for x in encoded]
    encoded.append(chr(ord(c) + change))
  return "".join(encoded)

print(encode(listString,change))


texts: Remove duplicates from array and save it to another one

texts:
So I have been tasked to make an array without duplicated values from another existing array.
So I did it, but I want to know is there some other better way to do that.
Example input/output:
Input: 10, 15, 10, 5, 1, 3
Output: 10, 15, 5, 1, 3
So here is my code.
#include <stdio.h>

int main(void) {
  const int MAX_ARRAY_SIZE = 5;

  int m[MAX_ARRAY_SIZE], p[MAX_ARRAY_SIZE];

  for(int i = 0; i < MAX_ARRAY_SIZE; i++) {
    printf("Enter number: ");
    scanf("%d",&m[i]);
  }
  int k = 0;
  int dup = 0;
  for(int i =0; i < MAX_ARRAY_SIZE; i++) {
    for(int j = i +1; j <MAX_ARRAY_SIZE; j++) {
        if(m[i] == m[j]) {
            dup = 1;
        }
    }
    if(dup != 1) {
      p[k++] = m[i];
    }
    dup = 0;
  }

  printf("The new array without repeated values\n");
  for(int i = 0; i < k; i++) {
    printf("%d\n",p[i]);
  }

  return 0;
}

I'm not sure if this is the right and simple way I do that. I want some suggestions.
Thanks in advance. :)


texts:
I'm rewriting a simple app using HTML/CSS/JavaScript that creates animations with images using intervals, and there's a bunch of buttons that controls these animations.

It's scaling and becoming really messed up, with logic mixed with DOM manipulations via jQuery all through one JavaScript script file.

I've decided to use the Module design pattern.  Based on my description of the app, is there a problem with this callback implementation for a module, or with the module implementation?

In this example, what is the best approach to declare private variables and give access to them through the public API? Getters and setters? Are they really necessary? I want to write readable code but I don't want to over-architect things.

(function($) {

  $.Module = function(options){
    var module = {
      options: $.extend({
        callbacks: {
          start: false
        }
      }, options),
      start: function(callback){
        //console.log('private start method');
        if(typeof callback === "function") {
            callback();
        }
      }
    }

    // public api
    return {
      start: function(){
        //console.log('public start method');
        module.start(module.options.callbacks.start);
      }
    }
  }

}($));

var myModule = $.Module({
  callbacks: {
    start: function(){
      console.log('start callback!');
    }
  }
})

myModule.start();

Here is a sample.

this next issue is actually just for the sake of learning

That seems to work to me so far. But I've seen other implementations that have some code that look like this:

callback: function(method) {
    if(typeof method === "function") {
        var args = [];

        for(var x = 1; x <= arguments.length; x++) {
            if(arguments[x]) {
                args.push(arguments[x]);
            }
        }

        method.apply(this, args);
    }
},

I'm not sure what this last code is supposed to do. Is it intended to return data to the callback function I registered when instantiating the module?


texts: Setting color of specific keywords in a textview

texts:
I'm developing an Android app to view C-programs.  I wanted to give a simple color scheme to the text which is stored in database, retrieved as a string and then passed on to the textview.

The code I have written assigns the green color to header file declarations and brackets, the blue color is assigned to numbers, printf, scanf, and the red color is assigned to datatypes such as int, char, float.

It is, however, very inefficient.  Before applying this color scheme, my app was displaying the textview activity instantly.  Now, depending on the length of the C-programs, it takes up to 4 to 5 seconds, which is really poor performance.

It takes one keyword at a time, then iterates the complete text of textview looking for that particular keyword only and changes its color, sets the text again.  Thus, it traverses text of the entire textview 29 times as I have defined 29 keywords in String arrays (namely keywordsgreen, keywordsblue, keywordsred).

The activity's onCreate() function:

textView  = (TextView) findViewById(R.id.textView1);
textView.setText(programtext);
textView.setBackgroundColor(0xFFE6E6E6);

//The problem starts here

String [] keywordsgreen={"#define","#include","stdio.h","conio.h","stdlib.h","math.h","graphics.h","string.h","malloc.h","time.h","{","}","(",")","<",">","&","while ","for "};
for(String y:keywordsgreen)
{
fontcolor(y,0xff21610B);
}

String [] keywordsred={"%d","%f","%c","%s","int ","char ","float","typedef","struct ","void "};
for(String y:keywordsred)
{
fontcolor(y,0xFFB40404);
}

String [] keywordsblue={"printf","scanf","\n","getch","0","1","2","3","4","5","6","7","8","9"};
for(String y:keywordsblue)
{
fontcolor(y,0xFF00056f);
}

The fontcolor() function:

private void fontcolor(String text,int color)
{
    Spannable raw=new SpannableString(textView.getText());
    int index=TextUtils.indexOf(raw, text);
    while (index >= 0)
    {
      raw.setSpan(new ForegroundColorSpan(color), index, index + text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      index=TextUtils.indexOf(raw, text, index + text.length());
    }
    textView.setText(raw);
}


texts:
I wrote a PHP class in Zephir to increase performance, but it is still very slow and memory consuming. To compare, I wrote several variants of the same code, but unpack() is always nearly as slow at storing the data in a csv file.

Is there any way to optimize this code? About 30% of the whole program time is spent in unpack.

class Hdb implements \Iterator, \Countable {
    /**
     * File handle.
     * @var resource
     */
    protected fh;

    protected line_count = 0;
    protected position = 0;

    protected row = [];

    public function __construct(string file) -> void {
        let this->line_count = floor((filesize(file)) / 12);
        let this->fh = fopen(file, "r");
    }

    public function readLine() {
        var timestamp;
        var value;
        var status;

        let timestamp = unpack("L", fread(this->fh, 4));
        let value     = unpack("f", fread(this->fh, 4));
        let status    = unpack("I", fread(this->fh, 4));

        let this->position++;

        return [
            "timestamp": timestamp[1],
            "value":     value[1],
            "status":    status[1]
        ];
    }

    // ... The standard Iterator stuff.

Gist


texts: Pass service to view model or leave thin controller as is

texts:
I have the following action:

    public PartialViewResult Analyze()
    {
        var viewModel = new WelcomeAnalyzeViewModel
        {
            IsDrugsPanelVisible = !Service.IsMDStandalone(),
            IsDevicesPanelVisible = Service.IsSubscribedToMedTech(),
            IsCompaniesPanelVisible = !Service.IsCTStandalone(),
            IsCountriesPanelVisible = !Service.IsCTStandalone() || (Service.IsCTStandalone() && Service.HasImsAddOn()),
            IsFinancePanelVisible = !Service.IsCTStandalone()
        };

        return PartialView("Analyze", viewModel);
    }

I'm not sure if I should just pass the Service property to the constructor of the WelcomeAnalyzeViewModel or leave this code as is but from the perspective of a thin controller this doesn't feel right.

The Service property contains an object to a permission service (IPermissionService) which can be used for other applications outside of the web environment.

Would it be acceptable for one service to call another service, so for instance I create an AnalyzeService which contains methods with calls to IPermissionService methods?


texts:
I am just looking to improve my indentation on my current code. I'd be happy to hear any reviews and improvements.
public class DataAccess
{

    public List<ComplaintModel> GetComplaint(string _OrderNumber)
    {
        throw new NotImplementedException();
    }

    public void InsertComplaint(
        DateTime _Date,
        string _OrderNumber,
        string _CustomerName,
        string _CustomerContactName,
        string _Telephone,
        string _Email,
        string _CustomerReference,
        string _Product,
        string _PackSize,
        string _BatchNumber,
        DateTime _BestBeforeDate,
        string _QuantityInvolved,
        string _Details,
        string _Comments)
    {
        using(MySqlConnection conn = new MySqlConnection(ConnectionString.ConnString))
        {
            List<ComplaintModel> complaint = new List<ComplaintModel>();

            complaint.Add(new ComplaintModel { Date = _Date,
                OrderNumber = _OrderNumber,
                CustomerName = _CustomerName,
                CustomerContactName = _CustomerContactName,
                Telephone = _Telephone,
                Email = _Email,
                CustomerReference = _CustomerReference,
                Product = _Product,
                PackSize = _PackSize,
                BatchNumber = _BatchNumber,
                BestBeforeDate = _BestBeforeDate,
                QuantityInvolved = _QuantityInvolved,
                Details = _Details,
                Comments = _Comments});

            conn.Execute(@"INSERT INTO customer_complaints
                        (date_taken, order_number, customer_name, customer_contact, telephone, email, customer_reference, product, pack_size, batch_lot_number,
                        best_before_date, quantity_involved, details, comments)
                        VALUES (@Date, @OrderNumber, @CustomerName, @CustomerContactName, @Telephone, @Email, @CustomerReference, @Product, @PackSize, @BatchNumber,
                        @BestBeforeDate, @QuantityInvolved, @Details, @Comments)", complaint);
        }
    }
}


texts: Basic API wrapper around a Restful service - follow-up

texts:
This is a follow up from my previous post: Basic API wrapper around a Restful service

I'm writing a basic wrapper around a restful service that returns a list of Stores. Naturally, I want to make it completely testable (that's a major requirement!).

I have split out my TopmanClient class so that just deals with the rest client bits (using RestSharp).

I then inject the TopmanClient class into my TopmanRepository:

public class TopmanClient : ITopmanClient
{
    private readonly IRestClient _restClient;
    private const string BaseUrl = "https://public.Topman.com/";
    private const string AcceptTenant = "uk";
    private const string AcceptLanguage = "en-GB";

    public TopmanClient()
    {
        _restClient = new RestClient(BaseUrl);

        _restClient.AddDefaultHeader("Accept-Tenant", AcceptTenant);
        _restClient.AddDefaultHeader("Accept-Language", AcceptLanguage);
    }

    public IRestRequest Request(string url)
    {
        return new RestRequest(url);
    }

    public IRestResponse<T> Execute<T>(IRestRequest request) where T : new()
    {
        return _restClient.Execute<T>(request);
    }
}

public class TopmanRepository : ITopmanRepository<Store>
{
    private readonly ITopmanClient _topmanClient;
    public TopmanRepository(ITopmanClient topmanClient)
    {
        _topmanClient = topmanClient;
    }

    public List<Store> Get(string query)
    {
        var request = _topmanClient.Request("stores");

        request.RootElement = "Stores";
        request.AddQueryParameter("q", query);

        var response = _topmanClient.Execute<List<Store>>(request);

        return response.Data;
    }
}


texts:
I have a Ruby function which generates and saves a report. I'm looking for a Clean Code way of writing this:

def generate
  violations = relevant_violations
  comments = convert_to_cleaned_up_comments(violations)
  text = convert_to_text(comments)
  save_to_file(text)
end

But I hate single-use low-semantic-value variables like these. So here's my first re-write:

def generate
  save_to_file(
    convert_to_text(
      convert_to_cleaned_up_comments(
        relevant_violations)))
end

And even though the flow is now in the reverse order, I find this quicker to grasp. There's less junk getting in the way.

But maybe a map/reduce or block style of programming would provide the same clarity but show data flow in the direction written, top to bottom.

EDIT: I re-wrote it so that the code can be read mostly top-to-bottom, not bottom-to-top:

corpus.rake — the reporting script

def generate_and_save
  save_to_file Violation
    .select(&:within_past_30_days?)
    .map(&:to_corpus_friendly_comment)
    .join "\n"
end

def save_to_file(text)
  File.open(LOCAL_PATH, 'w') { |f| f.write text }
end

violation.rb — the Violation class

  def to_corpus_friendly_comment
    facts
      .downcase
      .gsub(/\b(\d+f?|\w|pic|inspection)\b/, ' ')
      .gsub(/\W/, ' ')
      .gsub(/(foods?|please|days|use)/, '')
      .gsub(/  +/, ' ')
      .strip
  end

  def within_past_30_days?
    date > 30.days.ago
  end

...enabled by object-oriented refactoring; moving the functions into the Violations object enabled method chaining. One part I don't like is that .join "\n" is a lower level of abstraction than the other lines in generate_and_save.


texts: String manipulations: transform "a-b-c" into "a(b(c))"

texts:
function dashesToParentheses(str) {
    var list = str.split('-');
    return str.replace(/-/g, '(') + repeatString(')', list.length - 1);
}

function repeatString(str, times) {
    if (times == 1)
        return str;

    return new Array(times + 1).join(str);
}

dashesToParentheses('a-b-c') // "a(b(c))"
dashesToParentheses('a-b') // "a(b)"
dashesToParentheses('a') // "a"
dashesToParentheses('') // ""

dashesToParentheses works correct. Can I make it simpler or/and faster?


texts:
I find myself often use warp reduction in CUDA, then needing to broadcast (share) the scalar result amongst all threads.  My question is, what is the idiomatic way to do so with clean expressive code that is also efficient?  I wrote this simple template to do so, please review and comment.  Or if you know a better way, please share ;)
template <class T>
__inline__ __device__ T Share(T x) {
    __shared__ T shared;
    if (threadIdx.x == 0)
        shared = x;
    __syncthreads();
    return shared;
}


texts:
I am trying to estimate a good approximation for the arclength of the curve \$ y = \sqrt{1-x^2}\$ for \$x \in [0, 1]\$. I did this using a Bezièr curve, and made it so that the area under the two curves are alike. In order to estimate the error I want to calculate the differences in arclength. The arclength of a quarter circle is \$\frac14\pi\$ so it boils down to estimating

$$\mathrm{Difference}= \frac{L - \frac12\pi}{\frac12\pi}$$

Where \$L\$ is the arclength of my Bezièr curve. The problem, or rather my question is how to find a good method for estimating this arclength.

I tried using recursion and the Pythagorean theorem. I calculate the distance between \$P\$ and \$Q\$. Then I calculate the distances \$PR\$ and \$QR\$, where \$R\$ lies between \$P\$ and \$Q\$. If \$\mathrm{abs}( d(PR) + d(QR) - d(PQ)) < \mathrm{Error}\$ I return the length \$d(PR) + d(QR)\$.

This is painfully slow. Setting digits = 15 takes about 30 seconds on my computer and digits = 16 takes about a minute.

Have I implemented this method incorrectly, or in a highly inefficient way?

from decimal import *
import decimal
from math import pi
getcontext().prec = 100

nu = 2-(66-15*pi)**0.5/float(3)

def bezier(t):
    f = (1-t)**3 + 3*(1-t)**2*t + 3*(1-t)*t**2*nu
    g = 3*(1-t)**2*t*nu + 3*(1-t)*t**2 + t**3
    return (f, g)

def arc_length(start_t = 0, stop_t = 1, error = 10**(-6), length = 0):
    mean_t = 0.5*(start_t + stop_t)
    P = bezier(start_t)
    Q = bezier(mean_t)
    R = bezier(stop_t)

    length_one = decimal.Decimal(pyt(P, Q))
    length_two = decimal.Decimal(pyt(Q, R))
    if abs(length_one + length_two - length) < error:
        return length_one + length_two
    else:
        return arc_length(start_t, mean_t, error, length_one) + arc_length(mean_t, stop_t, error, length_two)

def pyt(P, Q):
    return ((P[0] - Q[0])**2 + (P[1] - Q[1])**2)**0.5

if __name__ == '__main__':

    digits = 5
    error = 10**(-digits)
    t1 = 0
    t2 = 1
    length = arc_length(0, 1, error)
    print length
    diff = (length - decimal.Decimal(pi)/decimal.Decimal(2))/(decimal.Decimal(pi)/decimal.Decimal(2))
    print diff