texts: Intersect Method Slows Down Code In Large Selection Of Cells

texts:
I have picture in certain cells. When I run following code (With Intersect Method) in smaller number of selected cells, it runs correctly but when the number of selected cells increase - say above 1000, then code slows down a bit (Intersect Method). Can it be optimized? Code without intersect method runs Ok.Can intersect method further optimize the code?

Code Without Intersect Method:

Sub tagging3()
Dim rng As Range
Dim shp As Shape
Dim m As Long
Dim arr() As String
Dim sample As String

m = 1
ReDim arr(ActiveSheet.Shapes.Count)

For Each shp In ActiveSheet.Shapes
    arr(m) = shp.TopLeftCell.Address
    m = m + 1
Next

For Each rng In Selection
    sample = rng.Address
    rng.Offset(0, 30).Value = "No"
    For m = 1 To ActiveSheet.Shapes.Count
        If sample = arr(m) Then
              rng.Offset(0, 30).Value = "Yes"
              Exit For
        End If
    Next m
Next
End Sub

Code With Intersect Method - Quite Slow

Sub shapesincells()
Dim sh As Shape, isect, rng As Range, n As Integer, arr() As Variant, sample As String
ReDim arr(ActiveSheet.Shapes.Count)
n = 1
For Each sh In ActiveSheet.Shapes
        Set arr(n) = sh.TopLeftCell
        n = n + 1
Next
For Each rng In Selection
    sample = rng.Offset(0, 30).Address
    For n = 1 To ActiveSheet.Shapes.Count
    Set isect = Application.Intersect(arr(n), rng)
            If Not isect Is Nothing Then
               sample = "Yes"
            End If
    Next
    If IsEmpty(sample) Then sample = "No"
Next
End Sub


texts: Elegant Method for Sleeping with Selenium Webscraper

texts:
My goal is to scrape the no. 1 suggestion of the suggestion list on https://finance.yahoo.com for any entry. If there is no suggestion the code should write f"nan_{what_ever_the_entry_was}".

As basis I used the solution from https://stackoverflow.com/questions/50355120/how-to-scrape-the-yahoo-finance-search-auto-suggestion-result-with-selenium-pyth/60496531#60496531.

Since I want to scrape the first suggestion for various values in a list, I created a for-loop. If I had kept the third to last line of the original solution

WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='yfin-usr-qry']"))).send_keys("goog")

the function won't work properly, because the elements are already loaded for the second loop. That's why I added two time.sleep() blocks instead. Now the function works well.

Question

The time.sleep() part does not seem very elegant to me. Is this the best way or are there more elegant/pythonic ways to resolve the problem?

Input

from typing import List
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
options.add_argument('headless')

def get_ticker_symbols(isin_list: List) -> List:
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Program Files (x86)\Google\Chrome\Chromedriver\chromedriver.exe')

    driver.get('https://finance.yahoo.com/')
    driver.find_element_by_xpath("//button[@type='submit' and @value='agree']").click()

    ticker_list=[]
    for isin in isin_list:
        try:
            WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='yfin-usr-qry']"))).send_keys(f"{isin}")
            time.sleep(1)
            ticker = driver.find_element_by_xpath('(//div[@class="_0ea0377c _4343c2a0 _50f34a35"])[1]').text

        except:
            ticker = f'nan_{isin}'
            time.sleep(0.1)

        finally:
            ticker_list.append(ticker)
            driver.find_element_by_xpath("//input[@name='yfin-usr-qry']").clear()

    return ticker_list

get_ticker_symbols(['GB00BD2ZT390','bmw','dasdas', 'nike', 'GB00BK8FL363'])

Output

['GPH.L', 'BMW.DE', 'nan_dasdas', 'NKE', 'HZD.L']


texts:
Inspired by this blogpost I decided to try and make it possible to have ranges of enum members that dwim, aka. that contain the actual members and not a stringified form.

This is the result. I'm looking for comments and wether I overlook a pitfall. Also, maybe EnumMember subset can be expressed in a more performant way?

use Test;

subset EnumMember of Any where .HOW.^name eq "Perl6::Metamodel::EnumHOW";

multi sub infix:<..>( EnumMember $a, EnumMember $b )
{
    die "Can only do ranges for members of the same enum" unless $a.WHAT === $b.WHAT;
    $a.WHAT.^enum_value_list.grep({ $_ === $a fff $_ === $b })
}

enum Foo ( XA => 17, XB => 19, XC => 2, XD => 17, XE => 1, XF => 99 );
enum Goo < YA YB >;

is-deeply( ( XC..XE ).Array, [XC, XD, XE] );
dies-ok({ XA..YB });


texts:
I am developing a service where the user need to sign the seller agreement with Mobile BankID (Swedish e-sign service). To make this work I need to make SOAP request to get the progress status of the signing request in Mobile BankID.

Is this code understandable? How can I make it more clean?

def collect_request(transaction_id):
    '''You can make a delay for 9 seconds before you start to call the Collect
    method. After 9s you begin to make CollectRequest with a 3 seconds delay
    between each collect. First answer will probably be
    OUTSTANDING_TRANSACTION, then USER_SIGN and at last COMPLETE. (After six
    OUTSTANDING_TRANSACTION you get NO_CLIENT, just to indicate that the user
    not yet has started her BankID client.

    After 180 seconds, you will at last get faultStatus EXPIRED_TRANSACTION'''
    time.sleep(9)
    seller_agreement = SellerAgreement.objects.get(id=transaction_id)
    url = '<WSDL URL HERE>'
    client = Client(url)

    val = 'OUTSTANDING_TRANSACTION'
    while True:
        try:
            response = client.service.Collect(policy='logtest001',
                                              provider='bankid',
                                              displayName='Test av Mobilt BankID',
                                              transactionId=transaction_id,
                                              orderRef=seller_agreement.order_ref)
            print response
            if response.progressStatus != val:
                trigger_new_sign_event(seller_agreement.user.id, response.progressStatus)
                val = response.progressStatus
            if (response.progressStatus == 'OUTSTANDING_TRANSACTION' or response.progressStatus == 'USER_SIGN' or response.progressStatus == 'NO_CLIENT'):
                # Try again in 3 seconds
                time.sleep(3)
                continue
            if response.progressStatus == 'COMPLETE':
                # TODO: Save to db
                print "Done!"
            break
        except WebFault, f:
            print f  # Django log?
            trigger_new_sign_event(seller_agreement.user.id, f.fault.faultstring)
            # TODO: cancelled_at?
            break


texts:
I've been using logging libraries recently and somebody told me to try and write my own. I've kept it minimal but the only drawback is I can't log in static classes, due to TClass.

Follow-up

I'm looking for constructive criticism on how to improve it.

How do I declare a logger variable?

private static readonly Logger<CatalogController> Logger = new Logger<CatalogController>();

I guess another drawback is that its pretty long, including the class name (twice) and then all the access modifiers and class names of the logger, it an get pretty ugly.

public class Logger <TClass>
{
    private readonly Type _className;

    public Logger()
    {
        _className = typeof(TClass);
    }

    public void Trace(string message, bool log = false)
    {
        Log(message, ConsoleColor.White, log);
    }

    public void Warn(string message, bool log = false)
    {
        Log(message, ConsoleColor.Yellow, log);
    }

    public void Debug(string message, bool log = false)
    {
        Log(message, ConsoleColor.Cyan, log);
    }

    public void Success(string message, bool log = false)
    {
        Log(message, ConsoleColor.Green, log);
    }

    public void Error(string message, bool log = false)
    {
        Log(message, ConsoleColor.Red, log);
    }

    public void Error(Exception e)
    {
        Log("An error occurred: " + Environment.NewLine + e, ConsoleColor.Red);
    }

    private void Log(string message, ConsoleColor color, bool log = false)
    {
        var oldColor = Console.ForegroundColor;
        Console.ForegroundColor = color;
        Console.WriteLine($"[{DateTime.Now:MM/dd HH:mm:ss}] " + message);
        Console.ForegroundColor = oldColor;

        string logFile;

        switch (color)
        {
            case ConsoleColor.Yellow:
                logFile = "error.log";
                break;
            case ConsoleColor.Cyan:
                logFile = "debug.log";
                break;
            case ConsoleColor.Red:
                logFile = "error.log";
                break;
            default:
                logFile = "trace.log";
                break;
        }

        LogToFile(logFile, $"Occurred at [{DateTime.Now:MM/dd HH:mm:ss}] in [{_className.FullName}]: " + message);
    }

    private static void LogToFile(string file, string content)
    {
        var executionPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        var fileWriter = new StreamWriter(executionPath + "/resources/logging/" + file, true);

        fileWriter.WriteLine(content);
        fileWriter.Close();
    }
}


texts:
I've came up with the following implementation of a very simple cache:

use std::cmp::Eq;
use std::collections::HashMap;
use std::hash::Hash;

pub struct Cache<I, R, F>
    where I: Copy + Eq + Hash, F: Fn(I) -> R
{
    calculation: F,
    values: HashMap<I, R>,
}

impl<I, R, F> Cache<I, R, F> where I: Copy + Eq + Hash, F: Fn(I) -> R {
    pub fn new(calculation: F) -> Cache<I, R, F> {
        Cache { calculation, values: HashMap::new() }
    }
    pub fn value(&mut self, arg: I) -> &R {
        // Pop or calculate new value
        let result = match self.values.remove(&arg) {
            Some(v) => v,
            None => (self.calculation)(arg)
        };
        // Store value
        self.values.insert(arg, result);
        // Return a reference to it
        self.values.get(&arg).unwrap()
    }
}

A simple usage example would be:

fn to_lowercase(value: &str) -> String {
    println!("Calculating \"{}\".to_lowercase()", value);
    value.to_lowercase()
}

fn main() {
    let mut cache = Cache::new(to_lowercase);
    println!("Calculated: {}", cache.value("ABC"));
    println!("Calculated: {}", cache.value("ABC"));
}

Which prints:

Calculating "ABC".to_lowercase()
Calculated: abc
Calculated: abc

However, I feel like my code is much more complicated than it needs to be (specially around the Cache.value implementation), what can be improved here?


texts: Displaying filtered user data using Ajax and PHP

texts:
I want to get my code cleaner and more efficient. This code gets variables form a PHP file and filters it to show the selected user name, all available usergroups on a list box and the groups he is currently into another.
Currently it's working great but it has a lot of delay between the modal shows up and the groups being shown.
JS:
  function saveUserGroup(id){
         $('#useridgr').attr('placeholder','').val('');
         $("#usernamegr").attr('placeholder', 'Nome').val('');
         $('#list_box').html('');   $('#list_box_ini').html('');

   $.ajax({
            type: 'GET',
            url: 'users/' + id + '/users' + '/id',
            data: {'_token': $("input[name='_token']").val()},
            success: function(data){
              $('#useridgr').attr('placeholder',data.id).val(data.id);
              $("#usernamegr").attr('placeholder',data.name).val(data.name);

              loadgroupsdata(data.id, 0);
            }   }); }

        var loadgroupsdata = (uid, type) => {

          $.ajax({
            type: 'GET',
            url: 'usergrupo/' + uid + '/' + type,
            data: {'_token': $("input[name='_token']").val()},
            success: function(data){

              if (type == 0) listbox = '#list_box';
              else listbox = '#list_box_ini';

              loadgroups(uid, listbox, type, data);

            }

          }) }

        function loadgroups(uid, location, type, data){

          $.each(data,function(i,v){
            $(location).append("<option value='"+v.idgrupo+"'>"+v.nome+"</option>");   })

          if(type == 0) loadgroupsdata(uid, 1);

        }

function sendData(type){
  uid = document.getElementById("useridgr").value;

  if(type == 1) listname = 'list_box_ini'; else listname = 'list_box';
  var e = document.getElementById(listname);

  var value = e.options[e.selectedIndex].value;

  $.ajax({
    type: 'GET',
    url: 'savegroup/' + uid + '/' + type + '/' + value,
    data: {'_token': $("input[name='_token']").val()},
    success: function(data){
      saveUserGroup(uid);

    }

  })
}

PHP:
public function getData($uid, $tablename, $index)
  {

    $data = \DB::table($tablename)->where($index, $uid)->first();
    return response()->json($data, 200);

  }

  public function getGroups($id, $type)
  {

    if ($type == 0){
      $data = \DB::table('grupoutilizador')
      -> join ('users', function ($join) use ($id){
        $join->on('users.id', '=', 'grupoutilizador.iduser')
        ->where('users.id', "=", $id );
      }) -> join ('grupo', 'grupo.idgrupo', "=", 'grupoutilizador.idgrupo') ->
      select('users.id', 'users.name', 'grupo.idgrupo', 'grupo.nome')
      -> get();

    } else {
      include 'config.php';

      $usergroups = mysqli_query($conn2, 'SELECT grupo.idgrupo FROM grupo, grupoutilizador WHERE grupoutilizador.idgrupo = grupo.idgrupo AND grupoutilizador.iduser =' .$id);

      $i = 0;

      if ($usergroups->num_rows != 0){
        foreach ($usergroups as $usergroup) {
          $ids[$i] = $usergroup;
          $i++;
        }
      } else {
        $ids[$i] = 0-1;

      }

      $data = \DB::table('grupo')
      ->whereNotIn('grupo.idgrupo', $ids)
      -> get();

    }

    return response()->json($data, 200);
  }

   public function saveGroups($uid, $type, $value){
        if ($type == 1){
          DB::table('grupoutilizador')->insert([
            'iduser' => $uid,
            'idgrupo' => $value,
          ]);

        } else {

          $result = DB::table('grupoutilizador') -> where([
          ['iduser', '=', $uid],
          ['idgrupo', '=', $value],
          ]) -> delete();

              echo $result;

        }
   }


texts:
I have tried to mimic Golang channels in C# and its performance is pretty good compared to golang itself. On my machine, each channel operation of Golang takes ~75 nano-sec and each Chan<T> (in C#) operation takes ~90 nano-sec.

Please let me know if this code can be improved in any way.

class Chan<T>
{
    readonly int size;

    T[] buffer;
    long head = -1;
    long tail = -1;
    long closed = 0;

    public Chan() { this.size = 0; }
    public Chan(int size)
    {
        if (size < 0) throw new ArgumentOutOfRangeException();

        this.size = size;
        this.buffer = new T[this.size];
    }

    object headLock = new object();
    public bool To(T t)
    {
        lock (headLock)
        {
            long localClosed = 0L;

            if (tail - head == buffer.Length) SpinWait.SpinUntil(() => (localClosed = Interlocked.Read(ref closed)) > 0 || tail - head < buffer.Length);
            if (localClosed > 0) return false;

            var newTail = Interlocked.Increment(ref tail);
            buffer[newTail % buffer.Length] = t;

            return true;
        }
    }

    object tailLock = new object();
    public bool From(out T val)
    {
        lock (tailLock)
        {
            long localClosed = 0L;

            if (tail - head == 0) SpinWait.SpinUntil(() => (localClosed = Interlocked.Read(ref closed)) > 0 || tail - head > 0);
            if (localClosed > 0)
            {
                val = default(T);
                return false;
            }

            var newHead = Interlocked.Increment(ref head);
            val = buffer[newHead % buffer.Length];

            return true;
        }
    }

    public void Close()
    {
        Interlocked.Increment(ref closed);
    }
}


texts: Finding peak point in an array by using divide and conquer approach

texts:
It is to find the maximum element in an array which is first increasing and then decreasing. I've tried to write my idea by using divide and conquer approach. Is there any improvable or missing point? My code is following,

def search(arr, low, high):
    if low == high:
        return arr[low]

    mid = low + (high - low) // 2

    if arr[mid] > arr[mid + 1]:
        # if it's peak that a number whose left and right are smaller than it, return it
        if arr[mid] > arr[mid - 1]:
            return arr[mid]
        else:
            return search(arr, low, mid)
    else:
        return search(arr, mid + 1, high)

if __name__ == "__main__":
    arr = [ 70, 80, 9, 6 ]
    arr2 = [60, 70, 72, 74, 88]
    arr3 = [8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1]
    arr4 = [10, 20, 30, 40, 50]
    arr5 = [1, 3, 50, 10, 9, 7, 6]
    arr6 = [120, 100, 80, 20, 0]

    print(search(arr, 0, len(arr) - 1))
    print(search(arr2, 0, len(arr2) - 1))
    print(search(arr3, 0, len(arr3) - 1))
    print(search(arr4, 0, len(arr4) - 1))
    print(search(arr5, 0, len(arr5) - 1))
    print(search(arr6, 0, len(arr6) - 1))

Output:

80
88
500
50
50
120


texts: Can anyone take the for loop out of this code?

texts:
Can anyone refactor this code without the for loop?

<?php

function lorem($paragraph_count = 1, $times = 1, $content = '')
{
    $paragraph = array(
        "Lorem ipsum dolor sit amet ......... Fusce a ante.",
        "Praesent sit amet est. Vestibulum quis elit ......... consectetuer quis, quam.",
        "Suspendisse ac eros. Morbi ......... feugiat at, tincidunt eget, ante.",
        "Proin sit amet ......... nisi lacinia tristique.",
        "Vivamus eu nisl sit amet tortor euismod venenatis ......... Proin tortor. Integer pulvinar."
    );

    for($i = 0; $i <= $paragraph_count; $i++) $content .= "<p>{$paragraph[$i]}</p>\n";

    return str_repeat($content, $times);
}
?>

<?= lorem(2,2); ?>


texts: Small program to download wikipedia articles to pdf

texts:
I made a small app to download wikipedia articles (and optionally those that it links to) as PDFs to take on the go.  I'd eventually like to do a text-to-speech option and save the article as an mp3, though that's the next step.  Any thoughts would be helpful.

import wikipedia
import pdfkit
import os
from gtts import gTTS

class Page:

    def __init__(self):
        """Set default pdfkit options"""
        self.pdfOptions = {
            'page-size': 'Letter',
            'margin-top': '0.75in',
            'margin-right': '0.75in',
            'margin-bottom': '0.75in',
            'margin-left': '0.75in',
            'javascript-delay' : 2000,
            'minimum-font-size': 512
        }

        self.targetDir = os.path.dirname(os.path.realpath(__file__))
        self.includeLinks = False

    def getArticle(self, articleTitle):
        """fetch the article from wiki by title"""
        self.page = wikipedia.page(articleTitle)
        try:
            self.page.summary
        except wikipedia.exceptions.DisambiguationError as e:
            print "Multiple articles with that name: " + e.options

    def setURL(self,URL):
        """fetch the article by URL"""
        pass

    def download(self):
        """download the article (and maybe the articles it links to"""
        if self.includeLinks == False:
            filename = self.targetDir+"/"+self.page.title+'.pdf'
            pdfkit.from_url(self.page.url, filename, options = self.pdfOptions)
        else:
            for link in self.page.links:
                linkedPage = wikipedia.page(link)
                print "Downloading " + linkedPage.url
                filename = self.targetDir+"/"+linkedPage.title+'.pdf'
                pdfkit.from_url(linkedPage.url, filename, options=self.pdfOptions)

    def speak(self):
        pass


texts: How can I make my isSorted function faster?

texts:
I made an isSorted function in Scala and Java as well and when I measured the time of functions' run I saw that the Scala version was very slow. It ran about 3.2 sec for 10000 Int but java version just ran about 10 ms!

How can I make faster my Scala version?

Scala:

def main(args: Array[String]) ={
    println(isSorted(getArray, (x:Int,y:Int) => x<y ))
}
def isSorted[A](items : Array[A], cond: (A,A) => Boolean) : Boolean = items match{
  case Array(_) => true
  case Array(x,y) =>cond(x,y)
  case Array(_*) => cond(items(0),items(1)) && isSorted(items tail,cond)
}

Java:

public static void main(String... args){
    Sorter sorter=new Sorter();
    System.out.println(sorter.isSorted(sorter.getList(),new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
    }));
}
public <A> boolean isSorted(List<A> items, Comparator<A> cond){
    for(int i=1;i<items.size();i++){
            if(cond.compare(items.get(i-1), items.get(i)) < 0){
                return false;
            }
        }
    return true;
}

Any suggestions?

I would like to use Scala, but this bad performance scared me!
Can I keep Scala's syntactic sugar?


texts:
Below is a code to update a google sheet using the database values. The script is working fine but it is rather slow because of the sleep function which I have to put because of the "Quota exceeding error" below. If I remove the sleep time it would work much faster but after a certain number of rows get updated it will throw the below error.

I have to update three columns namely A,B & C of which the value start row is from 4th row onwards. So basically I need advise/recommendations to improve this code on the below points:

To make the query execution faster without getting the below error.
Is there a way to generalise this script, means without hardcoding the spreadsheet name (DB details I can get in a generalised way and read from config, for testing purpose only hardcoded the values)

gspread.exceptions.APIError: {   "error": {
    "code": 429,
    "message": "Insufficient tokens for quota 'ReadGroup' and limit 'USER-100s' of service 'sheets.googleapis.com' for consumer 'project_number:*******'.",
    "status": "RESOURCE_EXHAUSTED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developer console API key",
            "url": "https://console.developers.google.com/project/***/apiui/credential"
          }
        ]
      }
    ]   } }

Python Code:

import psycopg2
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from time import sleep
import datetime

def update_sheet(sheet, table, rangeStart='A', rangeEnd='C'):
 for index, row in enumerate(table):
    range = '{start}{i}:{end}{i}'.format(start=rangeStart, end=rangeEnd, i=index+4)
    cell_list = sheet.range(range)
    for i, cell in enumerate(cell_list):
      start_time = datetime.datetime.now()
      cell.value = row[i]
      sheet.update_cells(cell_list)
      end_time = datetime.datetime.now()
      if (end_time - start_time).total_seconds() < 1:
         sleep(1.01 - (end_time - start_time).total_seconds())

cnx_psql = psycopg2.connect(host="xxx.xxx.xxx.xx", database="postgres", user="postgres",password="******", port="5432")
print('DB connected')
psql_cursor = cnx_psql.cursor()

METADATA_QUERY = '''select product_id,CAST(low_stock_date as TEXT) low_stock_date,sku from test.low_stock_date;'''
psql_cursor.execute(METADATA_QUERY)
results = psql_cursor.fetchall()
cell_values = (results)

scope =  ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('/Users/lins/Documents/GS_secret/secret_key.json',scope)
client = gspread.authorize(creds)
sheet = client.open_by_url('https://docs.google.com/spreadsheets/d/1****zQ/edit#gid=0').sheet1

#Function Call
update_sheet(sheet, cell_values)

psql_curso.close()
cnx_psql.close()


texts: Recursively checking the css class of an iFrame Element

texts:
I am writing some tests in selenium webdriver (on node.js). and have made a custom function to check the css value of an iFrame Element. I'm a coding beginner.

The script tests an app where the user writes the image width they want (just putting in a number) and the image in an iFrame should change width. This is tricky because one must switch iFrames, wait for elements to become stale (as the new image width is loaded) then grab the new element and check its css value.

Often, the tests are flaky because sometimes it checks before the value has changed etc. I finally wrote a function that passed 120 times out of 120 times.

//function looks for 'el', then switches iframe and extracts the desired cssValur, then compares it to the 'value' we expect
Page.checkCssValue = function (el, cssValue, value){
    //find function, the '0' represents the iframe index
    var newEl = this.find(el, 0);
    return newEl.getCssValue(cssValue).then(function(result){
        if(result !== value){
            console.log(result + " and " + value + " Do not Match.")
            return Page.checkCssValue(el, cssValue, value);
        }
        else{
            console.log(result + " and " + value + " Do Match!")
            return result;
        }
    });
};

But I'm not sure if this is considered bad programming and if a while loop would be better?


texts: Searching for index of node using traversing least possible path

texts:
The following is my code where I'm searching for the index of Doubly Linked List's node by traversing least possible paths.

if(size == 0)
    throw new IndexOutOfBoundsException("The list is empty.");

DoublyLinkedNode <E> tmp = head;
if(head.getElement() == element)
   return 0;
else
    for(int i =0; i< size;i++) {
        tmp = tmp.getNext();
        if(tmp.getElement() == element) {
            return i;
       }
        break;
    }
return -1;
    }

I want to improve this.I also did the following to improve it:

public int indexOf(E element) {
if(size == 0)
    throw new IndexOutOfBoundsException("The list is empty.");

DoublyLinkedNode <E> cur = head;
 int index = 0;

while (cur != null) {
    if ( cur.getElement().equals(element)) {
        return index;
    }
    else {
        cur = cur.getNext();
        index++;
    }
}
return -1;
}


texts:
I'm trying to optimize my solution to Wiggle Walk for Kickstart's round 1C.

  Problem

  Banny has just bought a new programmable robot. Eager to test his
  coding skills, he has placed the robot in a grid of squares with R
  rows (numbered 1 to R from north to south) and C columns (numbered 1
  to C from west to east). The square in row r and column c is denoted
  (r, c).

  Initially the robot starts in the square (SR, SC). Banny will give the
  robot N instructions. Each instruction is one of N, S, E or W,
  instructing the robot to move one square north, south, east or west
  respectively.

  If the robot moves into a square that it has been in before, the robot
  will continue moving in the same direction until it reaches a square
  that it has not been in before. Banny will never give the robot an
  instruction that will cause it to move out of the grid.

  Can you help Banny determine which square the robot will finish in,
  after following the N instructions?

  Input

  The first line of the input gives the number of test cases, T. T test
  cases follow. Each test case starts with a line containing the five
  integers N, R, C, SR and SC, the number of instructions, the number of
  rows, the number of columns, the robot's starting row and starting
  column, respectively.

  Then, another line follows containing a single string of N characters;
  the i-th of these characters is the i-th instruction Banny gives the
  robot (one of N, S, E or W, as described above).

  Output

  For each test case, output one line containing Case #x: r c, where x
  is the test case number (starting from 1), r is the row the robot
  finishes in and c is the column the robot finishes in.

  Limits

  Memory limit: 1GB. 1 ≤ T ≤ 100. 1 ≤ R ≤ 5 × 104. 1 ≤ C ≤ 5 × 104. 1 ≤
  SR ≤ R. 1 ≤ SC ≤ C. The instructions will not cause the robot to move
  out of the grid. Test set 1 (Visible)

  Time limit: 20 seconds. 1 ≤ N ≤ 100. Test set 2 (Hidden)

  Time limit: 60 seconds. 1 ≤ N ≤ 5 × 104.

Here's my current solution:

def main():
    T = int(input())  # the number of test cases

    for case in range(1, T+1):
        N, R, C, r, c = map(int, input().split())
        instructions = input()  # string of N, S, E or W
        seen = {(r, c)}

        for i in instructions:
            if i == 'N':
                r -= 1
                while (r, c) in seen:
                    r -= 1
            elif i == 'S':
                r += 1
                while (r, c) in seen:
                    r += 1
            elif i == 'E':
                c += 1
                while (r, c) in seen:
                    c += 1
            else:  # 'W'
                c -= 1
                while (r, c) in seen:
                    c -= 1
            seen.add((r, c))

        print('Case #{}: {} {}'.format(case, r, c))

main()

How can I represent visited areas in the grid so that getting the destination cell for each instruction would be faster?


texts:
SELECT TOP 1 l.ID
FROM Leads l
WHERE
     l.ID NOT IN (SELECT LeadID FROM LeadFollowups)
     AND l.ID NOT IN (SELECT LeadID FROM LeadsWorking)
     AND l.ID NOT IN (SELECT LeadID FROM LeadsDead)
     AND l.ID NOT IN (SELECT LeadID FROM LeadHolds)
     AND l.ID >= (RAND() * (SELECT MAX(ID) FROM Leads))
ORDER BY l.QualityScore DESC

I have a table growing by a 10 to 100 thousand rows a day.  I have several tables to track actions of the current leads that shouldn't be included when grabbing the new lead.  My query is pretty quick now, but as this grows is NOT IN the most efficient solution for this? Especially if I get in to the range of ~10 million rows in the Leads table?


texts:
In learning golang, I wrote a small CLI utility that will take paths as arguments and list out their md5 hash as hex strings. Included are two flags that alter functionality, --check | -c which takes an additional file, hashes both, and returns whether or not they match (and exits with the proper return code), and --text | -t that takes the path to a text file that is presumed to have exactly the contents of the hexified MD5 sum and checks it (as above).

The repository is here and code is below:

package main

import (
    "bytes"
    "crypto/md5"
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "strings"
)

var checkSum, textFile string

// build Flags
func init() {
    const (
        checkSumDefault = ""
        checkSumUsage   = "File to check against"
        textFileDefault = ""
        textFileUsage   = "File that has the md5 hash as its only content"
    )

    flag.StringVar(&checkSum, "check", checkSumDefault, checkSumUsage)
    flag.StringVar(&checkSum, "c", checkSumDefault, checkSumUsage)
    flag.StringVar(&textFile, "text", textFileDefault, textFileUsage)
    flag.StringVar(&textFile, "t", textFileDefault, textFileUsage)
}

func makeHash(fname string) [16]byte {
    data, err := ioutil.ReadFile(fname)
    if err != nil {
        panic(fmt.Sprintf("Failed to read file %s", fname))
    }
    return md5.Sum(data)
}

func main() {
    flag.Parse()
    var result int

    if checkSum != "" {
        // check mode -- against file
        checkSumHash := makeHash(checkSum)
        argHash := makeHash(flag.Arg(0))
        if checkSumHash == argHash {
            fmt.Print("They match!")
            result = 0
        } else {
            fmt.Print("No match")
            result = 1
        }
    } else if textFile != "" {
        // check mode -- against text

        checkSum, err := ioutil.ReadFile(textFile)
        if err != nil {
            log.Println(err)
            log.Fatalf("Can't read text file %s", textFile)
        }
        checkSum = bytes.TrimSpace(checkSum)
        argHash := makeHash(flag.Arg(0))
        if strings.EqualFold(fmt.Sprintf("%x", argHash), string(checkSum)) {
            fmt.Print("They match!")
            result = 0
        } else {
            fmt.Print("No match")
            result = 1
        }
    } else {
        // print mode
        for _, fname := range flag.Args() {
            hash := makeHash(fname)
            fmt.Printf("%x\n", hash)
        }
        result = 0
    }
    os.Exit(result)
}

I feel like I should refactor out the different functions and have each one return its success code. That's something I'll do when I have a little time free to poke at it.

The biggest question, however, is the best way to compare the [16]byte argHash to the []byte checkSum if --text is specified. Currently I'm using bytes.TrimSpace, casting to string,  and comparing that with Sprintf("%x", argHash). Is there a better way? Seems silly to convert both to string rather than comparing bytes, but I don't know a better way to do it.


texts:
Background:
I am completely new to react-native.

Question:
Is there any reason why I shouldn’t do this from an experienced point of view?

Goal:
- have common styles in my react-native app?
- use advantages of VSCode IntelliSense for development.

#common/styles.js

import { Platform, StyleSheet } from 'react-native';

export const styles = StyleSheet.create({
  fontFamily: {
    ...Platform.select({
      ios: {
        fontFamily: 'Baskerville',
      },
      android: {
        fontFamily: 'Noto Sans',
      },
    }),
  },
});

export const fonts = {
  h2: { fontSize: 80 },
  text: { fontSize: 12 },
};

export const BORDER_RADIUS = 5;

export const colors = {
  blue_primary: '#3F51B5',
  blue_secondary: '#E8EAF6',
  green_primary: '#73C700',
  green_secondary: '#F1F8E9',
  white: '#ffffff',
  grey_primary: '#9E9E9E',
  grey_secondary: '#FAFAFA',
  bluegrey: {
    50: '#eceff1',
    800: '#37474f',
    900: '#263238',
  },
};

Here is a plain component using this common styles:

import React from 'react';
import { View, Text } from 'react-native';
import { colors, styles, fonts } from './common/styles';

const PlainComponent = () => (
  <View style={{ flex: 1, backgroundColor: colors.bluegrey['50'] }}>
    <Text style={[fonts.h2, styles.fontFamily, { color: 'red' }]}>Hello</Text>
  </View>
);

export default PlainComponent;


texts: Simple JavaScript library for DOM interactions

texts:
I got this pretty interesting homework assignment, which was to finish off a very simple Javascript library. I couldn't use jQuery.

First, I will show you the raw piece of code that I received, then I will show you my solution and the last piece of code is what I think is the test of all the functions I had to make. I checked it and it worked pretty well- I mean the console output was as expected. I would like to ask you whether my solution is okay or not.

What I was given:

'use strict';

var dom = {
    // TODO: fill in library's API ...

    create: function(tag_name, attrs){

    },

    // Attributes getter / setter
    attr: function(elem, name, value){

    },

    // Append element as last child
    append: function(elem, child){

    },

    // Prepend element as first child
    prepend: function(elem, child){

    },

    // Detach element from dom
    remove: function(elem){

    }
}

What I did:

'use strict';

var dom = {
    // TODO: fill in library's API ...

    create: function(tag_name, attrs){
        var temp = document.createElement(tag_name);
        for(var key in attrs)
            {
            temp.setAttribute(key, attrs[key]);
            }
        return temp;
    },

    // Attributes getter / setter
    attr: function(elem, name, value){
        if(!value) return elem.getAttribute(name);
        elem.setAttribute(name,value);
        return elem;
    },

    // Append element as last child
    append: function(elem, child){
        elem.appendChild(child);
    },

    // Prepend element as first child
    prepend: function(elem, child){
        elem.prepend(child);
    },

    // Detach element from dom
    remove: function(elem){
        var par = elem.parentNode;
        par.removeChild(elem);
    }
}

WHAT I THINK IS A TEST:

'use strict';

describe('Dom library', function () {

  it('should allow to create dom elements', function () {
    var div = dom.create('div');

    expect(div instanceof window.Element).toBeTruthy();
    expect(div.tagName).toBe('DIV');
  });

  it('should allow to create dom elements with attributes', function () {
    var div = dom.create('div',{
        test:'test_value'
    });

    expect(div instanceof window.Element).toBeTruthy();
    expect(div.getAttribute('test')).toBe('test_value');
  });

  it('should allow to append elements', function () {
    var div = document.createElement('div');
    div.innerHTML = '

\

\

';

    var appendee = document.createElement('div');
    dom.append(div, appendee)
    expect(div.children[div.children.length - 1]).toBe(appendee);
  });

  it('should allow to prepend elements', function () {
    var div = document.createElement('div');
    div.innerHTML = '

\

\

';

    var prependee = document.createElement('div');
    dom.prepend(div, prependee)
    expect(div.children[0]).toBe(prependee);
  });

  it('should allow to detach elements', function () {
    var div = document.createElement('div');
    div.innerHTML = '

\

\

';

    var target = div.children[0];
    var detached = dom.remove(target)
    expect(target).toBe(detached);
    expect(div.children[0]).not.toBe(target);
  });

  it('should allow get element attribute', function () {
    var div = document.createElement('div');
    div.setAttribute("test","test_value");

    expect(dom.attr(div, 'test')).toEqual('test_value');
  });

  it('should allow set element attribute', function () {
    var div = document.createElement('div');
    dom.attr(div, 'test', 'test_value');

    expect(div.getAttribute('test')).toEqual('test_value');
  });

});


texts: Calculating the number of rounds required to complete a tournament

texts:
We're running an heads-up tournament on our website, where the goal is to keep playing until a single winner remains. This works much the same as e.g. a tennis tournament bracket.

However, it only works perfectly if the number of participants is a power of 2, and this happens only rarely, so most of the time the first step is to play a round where some number of participants get a free win (a "bye") into the next round, in order to get the number of players down to the closest power of 2.

Everything works just fine, but I have a nagging suspicion that the part that calculates the number of rounds required to complete the tournament can be heavily improved. Here's the code I'm using to calculate it:

function totalRounds($participants)
{
    $closestLowerPow2 = pow(2, (strlen(decbin($participants)) - 1));

    $roundsWithoutByes = (int) log($closestLowerPow2, 2);

    return $participants == $closestLowerPow2
        ? $roundsWithoutByes
        : $roundsWithoutByes + 1;
}

So the length of the binary minus 1 is the closest power. Use log to find out how many rounds that requires, since if e.g. there are 8 participants, then there are 3 rounds to play, as 2³ = 8. Finally, add a round if we need to have a round with byes before that.

Is there a smarter way I'm overlooking? :)


texts: matplotlib get_legend_handles_labels always return empty

texts:
I have a problem when adding elements to the same figure.
The problem is with the legend.
At each iteration I add elements and the corresponding legend.
But I want the legend to include all the different elements from all iterations.

The problem is that the function get_legend_handles_labels() returns empty handles & labels lists.

The code is as follows:

    handles, labels = ax.get_legend_handles_labels()
    for key in legendMap.iterkeys():
        if key not in labels:
            handles.append(h[legendMap[key]])
            labels.append(key)

    ax.legend(handles, labels, loc='center left', bbox_to_anchor=(1, 0.5))
    h1,l1 = ax.get_legend_handles_labels()

h1, l1 are empty rather being the same as handles, labels

The following code does the trick, but I believe there should be more elegant solution:

    legend = ax.get_legend()
    labels = [] if legend is None else [str(x._text) for x in legend.texts]
    handles = [] if legend is None else legend.legendHandles
    for key in legendMap.iterkeys():
        if key not in labels:
            handles.append(h[legendMap[key]])
            labels.append(key)

    ax.legend(handles, labels, loc='center left', bbox_to_anchor=(1, 0.5))

Help is much appreciated, thanks !


texts: Project Euler # 55 Lychrel numbers in Python

texts:
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.

Not all numbers produce palindromes so quickly. For example,

349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337

That is, 349 took three iterations to arrive at a palindrome.

Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome.
A number that never forms a palindrome through the reverse and add process is called a Lychrel number.
Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume
that a number is Lychrel until proven otherwise. In addition you are given that for every number below
ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one,
with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677
is the first number to be shown to require over fifty iterations before producing a palindrome:
4668731596684224866951378664 (53 iterations, 28-digits).

Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.

How many Lychrel numbers are there below ten-thousand?

from time import time

def is_palindrome(number):
    """returns True for a palindrome, False otherwise."""
    to_str = str(number)
    return to_str == to_str[::-1]

def add_reverses(number, count):
    """makes a list of reverses for a number at a maximum iteration of count, breaks if palindrome found below count."""
    reverses = [number]
    for _ in range(count):
        last_number = reverses[-1]
        new_number = int(str(reverses[-1])[::-1])
        if is_palindrome(last_number + new_number):
            reverses.append(last_number + new_number)
            return reverses
        else:
            reverses.append(last_number + new_number)
    return reverses

def count_lychrel_range(number_range, count):
    """returns Lychrel numbers within number_range, assumes count is the maximum iterations for a number."""
    total = 0
    numbers_reverses = {}
    for number in range(number_range):
        numbers_reverses[number] = add_reverses(number, count)
    for number, rev_sequence in numbers_reverses.items():
        if len(rev_sequence) >= count:
            total += 1
    return total

if __name__ == '__main__':
    start_time = time()
    n = 10000
    print(f'Total Lychrel numbers below {n}: {count_lychrel_range(n, 50)}')
    print(f'Time: {time() - start_time} seconds.')


texts:
I have a class Record which keeps entries of strings(implemented using vector of strings). I want to keep the data member private to the class. To get entries, I have defined a member function get_entry which accepts a reference to vector of strings to store results.

Below is the code.

#include <iostream>
#include <vector>
#include <string>

class Record {
public:
        void add_entry(const std::string& entry)
        {
                static int seq = 1;
                entries.push_back(std::to_string(seq++) + " "+ entry);
        }
        void get_entry(std::vector<std::string>& res) const
        {
                for (auto &v: entries)
                        res.push_back(v);
        }

private:
        std::vector<std::string> entries;
};

int main()
{
        Record name;
        name.add_entry("abc");
        name.add_entry("def");
        std::vector<std::string> res;
        name.get_entry(res);
        for (auto &v : res)
                std::cout << v << "\n";
        return 0;
}

Are there other better ways to get entries from such a class? I don't want to make entries data member public and access it directly.


texts: Slow copying of memmap array to numpy array

texts:
I have multiple binary (structured) file, each of 2GB, which I am currently reading in pair, using memmap to cross-correlate the same. I want to minimise the time required by this IO process, in the code.
I am implementing this as a Cython function, though the copying of memmap array to numpy array is quite fast (~3 sec) when same set of files are processed twice, it takes large amount of time if new files are to be read (~71 sec), possibly because of cache memory, this is the same with numpy fromfile as well.
What is the efficient and fastest way of copying the memmap to numpy array?
Any suggestions on the same are appreciated.
Code used:
comf     = np.memmap(file_name,  dtype = dt, mode = 'c')
comf1    = np.memmap(file_name1, dtype = dt, mode = 'c')
cdef np.ndarray tempcomf    =   np.zeros((templen, 1024), dtype = np.int8)
cdef np.ndarray tempcomf1   =   np.zeros((templen1, 1024), dtype = np.int8)
tempcomf     =   comf['data']
tempcomf1    =   comf1['data']

EDIT:
Here is the function used:
cpdef tuple decrypt_file(file_name, file_name1):

    cdef long long int templen = 0
    cdef long long int templen1= 0
    cdef np.ndarray tempcomf   =   np.zeros((templen, 1024),dtype=np.int8)
    cdef np.ndarray tempcomf1  =   np.zeros((templen1, 1024),dtype=np.int8)

    dt       = np.dtype([('header', 'S8'), ('Source', 'S10'), ('header_rest', 'S10'), ('Packet', '>u4'), ('data', '>i1', 1024)])
    comf     = np.memmap(file_name,  dtype = dt, mode = 'c')
    comf1    = np.memmap(file_name1, dtype = dt, mode = 'c')

    templen =   comf['Packet'][-1]-comf['Packet'][0]
    templen1=   comf1['Packet'][-1]-comf1['Packet'][0]

    t_1      =   time.time()
    tempcomf =   comf['data']
    tempcomf1=   comf1['data']
    print('Time take for memarray copy...'+str(time.time()-t_1))
    tempcomf = tempcomf.ravel()
    tempcomf1= tempcomf1.ravel()

    tempcomf_X =   np.array(tempcomf[1::2], order = 'F')
    tempcomf_Y =   np.array(tempcomf[0::2], order = 'F')
    tempcomf1_X=   np.array(tempcomf1[1::2],order = 'F')
    tempcomf1_Y=   np.array(tempcomf1[0::2],order = 'F')

    return tempcomf_X, tempcomf_Y, tempcomf1_X, tempcomf1_Y

Input Data Structure:
The binary file input has 32 bytes header and 1024 bytes data, the focus is on reading the latter memmap array to numpy array.
This is the function where the files are read and the data is separated from the header. If same file set is given twice, memory copy takes ~2 sec, but when a different set of files are given the copying takes ~72 sec.
EDIT - MORE INFORMATION
After further investigation, I found that this problem indeed stems from caching of memory. As part of the test I cleared cache (echo 3 > /proc/sys/vm/drop_caches), which results in longer time for the copy of memmap array to numpy array (to volatile memory).
As part of confirmation of the issue, when I pre-cache the binary files into memory using vmtouch it takes ~3 sec for the copy (memmap to numpy array) to take place.
Though the solution to the problem is not yet found, as even the pre-caching takes ~52 sec, when done by vmtouch, the reason for the problem is related to the caching of memory.
vmtouch OUTPUT:
vmtouch -vt /data/ch01_SOURCE_Binary_20201011_110101.bin
[OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO] 522720/522720

Files: 1
Directories: 0
Touched Pages: 522720 (1G)
Elapsed: 52.403 seconds


texts:
I've two working ways to do so, but which one should I use?

Common part: var textarea = document.getElementById("textarea");

First way:

function updateStatusBar() {
    var text = textarea.value;
    statusBar.value = "Words: " + (text ? text.match(/\b\S+\b/g).length : "0") +
      "  Characters: " + text.replace(/\s/g, "").length +
      " / " + text.replace(/\n/g, "").length;
}

and second way:

function updateStatusBar() {
    var text = textarea.value;
    statusBar.value = "Words: " + (text.split(/\b\S+\b/).length - 1) +
      "  Characters: " + text.replace(/\s/g, "").length +
      " / " + text.replace(/\n/g, "").length;
}

Please review the Words: counting code. Which one should I use?


texts: "Fun with Rotation" - Codechef September Challenge

texts:
Can you please help me in reducing the complexity of the below code?  The problem statement can be found here.

  You are given an array A of N integers. You are to fulfill M queries.
  Each query has one of the following three types:

  C d : Rotate the array A clockwise by d units.
  A d : Rotate the array A anticlockwise by d units.
  R d : Query for the value of the element, currently being the d-th in the array A.

  Input

  The first line contains two numbers - N and M respectively. The next
  line contains N space separated Integers, denoting the array A. Each
  of the following M lines contains a query in the one of the forms
  described above.

  Output

  For each query of type R output the answer on a separate line.

  Constraints

  1 ≤ N ≤ 100000
  1 ≤ M ≤ 100000
  1 ≤ d ≤ N, in all the queries
  1 ≤ elements of A ≤ 1000000

  The array A and the queries of the type R are 1-based.

The solution in Java manages to solve the problem but is facing a time limit exceeded issue, so please advise me on how to optimize the code.

import java.io.BufferedReader;

 import java.io.IOException;

 import java.io.InputStreamReader;

 import java.util.ArrayList;

 public class Main {

    public static void main (String args[]) throws IOException

    {

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        String not[]=in.readLine().trim().split(" ");

        int n=Integer.parseInt(not[0]);

        int q=Integer.parseInt(not[1]);

        String s[]=in.readLine().trim().split(" ");

    ArrayList<Integer>  sarray=new ArrayList<Integer>();

        for(int i=0;i<n;i++)

        {

        sarray.add(Integer.parseInt(s[i]));

        }

        for(int j=0;j<q;j++)

        {

            String r[]=in.readLine().trim().split(" ");

            if(!r[0].equals("R"))
            sarray=swap(sarray,n,Integer.parseInt(r[1]),r[0]);

            else

                System.out.println(sarray.get(Integer.parseInt(r[1])-1));

            }

    }

    private static ArrayList<Integer> swap(ArrayList<Integer> arr, int n, int d,String c) {

        // TODO Auto-generated method stub

        int i, j;
        int temp;

        for(j = 0; j < d; j++)

        {

            //rotate right once

            if(c.equals("A"))

            {

            temp = arr.get(n - 1);

            for(i = n - 1; i > 0; i--)

            arr.set(i,arr.get(i-1));
            arr.set(0,temp);

            }
            else  if(c.equals("C"))
            {

                  temp = arr.get(0);
                  for(i = 0; i < n-1; i++)
                  arr.set(i,arr.get(i + 1));
                  arr.set(n - 1,temp);

            }

        }

        return arr;
    }

 }


texts: Optimizing a JavaScript snippet for portability and readability

texts:
We have an in-house time-tracking application at the office.

We, the employees, can view an overview of our hours on a web page. This web page renders a table, with worked hours per day in table cells, which is styled as a monthly calendar. I wrote a small script which I can copy-paste in my console to get a total of hours worked too much for that month.

A relevant snippet of the HTML.

10
    &nbsp;

        08:33

11
    &nbsp;

        08:25

The JavaScript snippet.

var elementsToParse = $(".link").find("font:not(:empty)");
var totalMinutes = 0;
$.each(elementsToParse, function(index, element) {
    var text = $(element).text();
    var hours = parseInt(text.substr(1, 2));
    var minutes = parseInt(text.substr(3, 2));

    var elementTotal = ((hours * 60) + minutes) - 480;

    totalMinutes += elementTotal;
});

alert('Overtime so far: ' + totalMinutes + ' minutes');

Any thoughts on how to make the script more compact or elegant, while maybe improving readability?


texts:
In my code, when the index is 0, I am supplying the second template which contains the word as arif. With the rest I am supplying the first template which doesn't have the word arif.

I got this result as a result of a posted question, but I am not satisfied with it because of its length.

// Code goes here
"use strict";
angular.module('tcpApp', [])
.controller('MainCtrl', function($scope) {
  $scope.appNames=[{title:'titre1'},
                   {title:'titre2'},
                   {title:'titre3'}];

})
.directive('programName', function ( $compile ) {
        return {
            restrict    : 'AE',
            replace     : true,
            scope       : {
                            name:'@',
                            index:'@'
                        },

            link        : function (scope, element, attr) {
                            scope.callMe = function () {
                                console.log($(element).prop('class'));
                            }

                            var getTemplate = function( index ) {
                              return Number(index) ? '
{{name}}
' : '
{{name}}arif
';
                             }

                             element.html(getTemplate(scope.index));

                            $compile(element.contents())(scope);
                        }
        }
    })

Live Demo to Play


texts:
I have two tables for storing comments

comments

CREATE TABLE `comments` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `text` text NOT NULL,
 `author` int(10) unsigned NOT NULL,
 `time` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

comments_ratings

CREATE TABLE `comments_ratings` (
 `comment` int(10) unsigned NOT NULL,
 `user` int(10) unsigned NOT NULL,
 `vote` tinyint(4) NOT NULL,
 PRIMARY KEY (`comment`,`user`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

users

CREATE TABLE `users` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `email` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

The goal is to select comments along with rating and information about the author as well as whether the logged in user has voted or not and if yes their vote's value.

SELECT
c.id,
c.text,
c.time,
c.author,
u.email AS author_name,
SUM(cr.vote) AS rating,
MAX(if(cr.user = ?, cr.vote, NULL)) AS voted

FROM comments c
LEFT JOIN users u ON u.id = c.author
LEFT JOIN comments_ratings cr ON c.id = cr.comment

GROUP BY c.id
ORDER BY c.id DESC

I used to do a second join on comments_ratings in order to get the vote of the logged in user but I recently switched to this thing that I'm not fully sure on to how it works, I just have my guesses. I wrote it with the help of another question I asked and some luck.

Ultimately what I want to ask is, are there any possible issues I can run into with

MAX(if(cr.user = ?, cr.vote, NULL)) AS voted

And I'm asking performance-wise. I know it may not be very easy to read but all I care about now is performance. Is this alright or I should definitely switch back to an additional join on commments_ratings like LEFT JOIN comments_ratings cr2 ON c.id = cr2.comment AND c.author = cr2.user to get the value of vote?


texts:
I have a qt code that opens some threads and waits for a response, all timed with a QTimer.
For example
(thread1 is declared in the header)
thread1 = new QThread();
OpenCVWorker *worker1 = new OpenCVWorker();
QTimer *workerTrigger1 = new QTimer();
workerTrigger1->setInterval(30);

connect(workerTrigger1, SIGNAL(timeout()), worker1, SLOT(receiveFrame()));
connect(thread1, SIGNAL(finished()), worker1, SLOT(deleteLater()));
connect(thread1, SIGNAL(finished()), thread1, SLOT(deleteLater()));
connect(thread1, SIGNAL(finished()), workerTrigger1, SLOT(deleteLater()));
connect(this,SIGNAL(blockOpencvThread()),worker1,SLOT(blockThread()));
connect(this, SIGNAL(sendSetup1(QString)), worker1, SLOT(receiveSetup(QString)));
connect(this, SIGNAL(stopCameras()), worker1, SLOT(receiveToggleStream()));
connect(worker1, SIGNAL(sendFrame(QImage)), this, SLOT(receiveFrame(QImage)));

workerTrigger1->start();
worker1->moveToThread(thread1);
workerTrigger1->moveToThread(thread1);
thread1->start();
emit sendSetup1(Settings::ipCamera1);

When the program is going to end, I call
emit stopCameras();
if(thread1->isRunning())
{
    thread1->quit();
    thread1->wait();
}

Is this correct?
Thank you very much.


texts: Configuring a JMS Component in akka-camel

texts:
I'm trying to write a JMS Consumer using Akka-Camel.

For now, I'm using FFMQ as a JMS server. I want to listen on the JMS queue myqueue.

Creating the JMS consumer actor is quite straightforward:

import akka.camel.{CamelMessage, Consumer}
import akka.event.Logging

class JMSConsumer extends Consumer {
  val log = Logging(context.system, this)
  def endpointUri = "jms:queue:myqueue"

  def receive = {
    case m: CamelMessage => {
      log.info(s"JMS Received $m")
    }
    case other => {
      log.info(s"JMS Received unknown message type : $other")
    }
  }
}

But I'm struggling with the configuration of the JMS component.

In order to connect to JMS server, I need to specify a few properties as specified in FFMQ documentation.

So far I have only managed to do this by specifying parameters using some Camel internals:

import akka.actor.{Props, ActorSystem}
import akka.camel.CamelExtension
import org.apache.camel.component.jms.{JmsConfiguration, JmsComponent}
import java.util.Hashtable
import javax.naming.{InitialContext, Context}
import net.timewalker.ffmq3.FFMQConstants
import javax.jms.{Session, ConnectionFactory}

object MainApp extends App {
  val system = ActorSystem("TestSystem")

  def jmsConnectionFactory() : ConnectionFactory = {
    val env = new Hashtable[String, String]();
    env.put(Context.INITIAL_CONTEXT_FACTORY, FFMQConstants.JNDI_CONTEXT_FACTORY);
    env.put(Context.PROVIDER_URL, "tcp://localhost:10002");
    val context: Context = new InitialContext(env);

    context.lookup(FFMQConstants.JNDI_CONNECTION_FACTORY_NAME).asInstanceOf[ConnectionFactory];
  }

  val jmsConfiguration = new JmsConfiguration(jmsConnectionFactory)

  val jmsComponent = new JmsComponent(jmsConfiguration)

  val camel = CamelExtension(system)
  camel.context.addComponent("jms", jmsComponent)
  val jmsConsumer = system.actorOf(Props[JMSConsumer], name="myqueueConsumer")
}

I'm wondering if this is the way that akka-camel is intended to be used.

It seems that I'm just putting random things together, possibly going into too low-level detail when doing JNDI lookup myself?

Unfortunately, akka-camel documentation doesn't go into details here.


texts: List-flattening function in erlang feels too wordy

texts:
I wrote a tail-recursive list-flattening function, but I'm not too happy with it.

a) Is tail-recursion necessary here, or will the function be optimized without it?
b) It's ugly how many clauses there are, and that I have to call out to flatten in the expression of the first clause of flatten_acc

So, how could I do better?

(To be clear, this is a function that completely flattens the list -- e.g. flatten([foo, [[[bar]], [baz]]]) == [foo, bar, baz])

flatten(List) ->
    lists:reverse(flatten_acc(List, [])).

flatten_acc([[[H|T0]|T1]|T2], Acc) ->
    flatten_acc([flatten([[H|T0]|T1])|T2], Acc);
flatten_acc([[H|T0]|T1], Acc) ->
    flatten_acc([T0|T1], [H|Acc]);
flatten_acc([[]|T], Acc) ->
    flatten_acc(T, Acc);
flatten_acc([H|T], Acc) ->
    flatten_acc(T, [H|Acc]);
flatten_acc([], Acc) ->
    Acc.

Thanks!


texts:
I'm writing a perl script which reads logs from a file and looks for matches from another file before sending the matches off by email. The problem is, I'm dealing with files which could be changed (a log written to them by syslog) at any time. I discovered that files can be locked in perl, however I'm not sure if it is 100% secure yet. Here is the pertinent snippet:

    # Check for valid email
    unless ($mailto =~ EMAIL_REGEX) {
        die "Please supply a valid email"
    }

    # Build a rule from a key and an email
    # Write it to LOGMAN_CONF
    my $key_and_email = $keyword.":".$mailto."\n";
    open (RULES, ">>", LOGMAN_CONF)
        or die "Cannot open logman configuration file ".LOGMAN_CONF;
    flock(RULES, LOCK_EX) or die "Can't lock ".LOGMAN_CONF;
    print RULES $key_and_email;
    close RULES;

    # Check if CRONTAB_LOC needs a send entry
    open (CRON, "<", CRONTAB_LOC)
        or die "Cannot open crontab file ".CRONTAB_LOC;
    flock(CRON, LOCK_SH) or die "Can't lock ".CRONTAB_LOC;
    my @cronLines = <CRON>;
    close CRON;

    my $match = 0;
    foreach my $line (@cronLines) {
        if ($line eq CRON_ENTRY) {
            $match = 1;
        }
    }
    unless ($match == 1) {
        open (CRON, ">>", CRONTAB_LOC)
            or die "Cannot open crontab file ".CRONTAB_LOC;
        flock(CRON, LOCK_EX) or die "Can't lock ".CRONTAB_LOC;
        print CRON CRON_ENTRY;
        close CRON;
    }

Feel free to critique my style or structure, as this is my first contact with Perl.

NB: There are a couple of constants used above which I haven't shown where they are defined. I could add them if anyone needs, but they are for the most part location to files.


texts: Find total number of paths in a matrix of 0's and 1's

texts:
I am working on a program which states that:

You are given a 2-D matrix with M rows and N columns.You are initially positioned at (0,0) which is the top-left cell in the array. You are allowed to move either right or downwards. The array is filled with 1’s and 0’s. A 1 indicates that you can move through that cell, a 0 indicates that you cannot move through that cell. Return the number of paths from top-left cell to bottom-right cell.(i.e. (0,0)to(M-1,N-1)). Since answer can be large thus you have to return ans%(10^9+7).

static int count(int a[][], int i, int j) {
    int rows = a.length;
    int cols = a[0].length;
    if(a[i][j] == 0)  return 0;
    if (i == rows - 1 && j == cols - 1)
        return a[i][j];
    else if (i == rows - 1)
        return a[i][j + 1];
    else if (j == cols - 1)
        return a[i + 1][j];
    else if (a[i][j] == 1)
        return count(a, i + 1, j) + count(a, i, j + 1);
    else
        return 0;
}

How can we improve the performance of this program?


texts: Maximum contiguous subarray with recursion

texts:
I've implemented the algorithm below for the maximum contiguous subarray problem and would like a review on three specific things:

Making the code shorter
Making the code faster
Any other algorithms that can do the job with lower complexity

def crossingsubarray(A, low, mid, high):

    negetiveinfinity = -10000000000
    summ = 0
    for i in range(mid, low - 1, -1):
        summ = summ + A[i]
        if summ > negetiveinfinity:
            negetiveinfinity = summ
            leftindex = i
    left = negetiveinfinity

    negetiveinfinity = -10000000000
    summ = 0

    for j in range(mid+1, high+1):
        summ = summ + A[j]
        if summ > negetiveinfinity:
            negetiveinfinity = summ
            rightindex = j
    right = negetiveinfinity

    return(leftindex, rightindex, left + right)

def findmaxarray(alist, low, high):

    if high == low:
        return low, high, alist[low]

    else:

        mid = (low+high)/2

        leftlow, lefthigh, leftsum = findmaxarray(alist, low, mid)
        rightlow, righthigh, rightsum = findmaxarray(alist, mid + 1, high)
        crosslow, crosshigh, crosssum = crossingsubarray(alist, low, mid, high)

        if leftsum >= rightsum and leftsum >= crosssum:
            return leftlow, lefthigh, leftsum
        elif rightsum >= leftsum and rightsum >= crosssum:
            return rightlow, righthigh, rightsum
        else:
            return crosslow, crosshigh, crosssum

B = [-7, -2, 5, 4, -1, 100, 10]

L,H,maxi = findmaxarray(B, 0, 6)

print(L)
print(H)
print(maxi)

Just a quick explanation:

The first function, crossingsubarray, returns the maximum value of a subarray (along with its low and high indices with respect to A) such that the subarray crosses the provided midpoint.

The second function, findmaxarray, is a divide-and-conquer task which recursively calls the first function such that the maximum contiguous subarray sum is found.

Please let me know if I could make any improvements in the aforementioned areas.


texts: Reverse int within the 32-bit signed integer range: \$[−2^{31}, 2^{31} − 1]\$ Optimized

texts:
LeetCode Problem

  Reverse digits of a 32-bit signed integer. When the reversed integer overflows return 0.

Feedback

Optimized from beta code in the original question here. Based on this LeetCode problem.. I'm trying to come up with a good approach that just math operations to iterate a serious of digits using division, almost treating the int like a stack popping using modulus, and pushing using multiplication.

#include <cassert>
#include <climits>
#include <cmath>
#include <iostream>

class Solution
{
    public:
        int reverse(int i) {

            if(i > INT_MAX || i < INT_MIN) {
                return 0;
            }
            int sign = 1;
            if(i < 0) {
                sign = -1;
                i = i*sign;
            }

            int reversed = 0;
            int pop = 0;

            while(i > 0) {
                pop = i % 10;
                reversed = reversed*10 + pop;
                i /= 10;
            }

            std::cout << reversed << '\n';

            return reversed*sign;
        }
};

int main()
{
    Solution s;

    assert(s.reverse(1) == 1);
    assert(s.reverse(0) == 0);
    assert(s.reverse(123) == 321);
    assert(s.reverse(120) == 21);
    assert(s.reverse(-123) == -321);
    assert(s.reverse(1207) == 7021);
    assert(s.reverse(1534236469) == 0);
    assert(s.reverse(-2147483412) == -2143847412);
}


texts:
For some time now, I've been using a pattern which I think could be done more elegantly.
I have a lot of XML files that need to be represented in a Django views. My current approach is like this:

I get a XML response from an API which gives me several documents.

First I define a mock class like this:

class MockDocument:
    pass

Then I write an XPath expression that gives me a list of the document nodes:

from lxml import etree
with open("xmlapiresponse.xml", "r") as doc:
    xml_response = doc.read()
tree = etree.fromstring(xml_response)
document_nodes = tree.xpath("//documents/item")

Now I iterate over the different documents and their fields using nested for-loops:

# list for storing the objects
document_objects = []
for document in document_nodes:
    # create a MockDocument for each item returned by the API
    document_object = MockDocument()
    for field in document:
        # store the corresponding fields as object attributes
        if field.tag == "something":
            document.something = field.text
    document_objects.append(document)

Now I can pass the list of mock objects to a Django view and represent them in the template in whichever way I want. Could this be done in a simpler fashion, though?


texts:
I just built my first scraper and I'd like to get your thoughts on the structure and the way I went about it. The basic premise of the script:

Get a random movie from IMDb's Top 250
Ask the user whether they've seen it before. If yes, print another random movie. If no, tell them to enjoy the movie and the script ends.

from lxml import html
import requests

def moviePicker():
    hasSeen = False
    while hasSeen == False:
        import random
        page = requests.get('http://www.imdb.com/chart/top')
        tree = html.fromstring(page.content)
        random = random.randint(1, 250)

        title = tree.xpath('//*[@id="main"]/div/span/div/div/div[3]/table/tbody/tr[' + str(random) +']/td[2]/a/text()')
        yearReleased = tree.xpath('//*[@id="main"]/div/span/div/div/div[3]/table/tbody/tr[' + str(random) + ']/td[2]/span/text()')

        # Parse the movie's url and pull the summary from the details page
        movieUrl = str(tree.xpath('//*[@id="main"]/div/span/div/div/div[3]/table/tbody/tr[' + str(random) + ']/td[2]/a/@href'))
        removeFront = movieUrl.replace("['", "")
        cleanUrl = 'http://www.imdb.com' + removeFront.replace("']", "")
        moviepage = requests.get(cleanUrl)
        details = html.fromstring(moviepage.content)
        movieSummary = details.xpath("normalize-space(//div[@class='summary_text']/text())")

        print(title)
        print(yearReleased)
        # print(cleanUrl)
        print(movieSummary)

        while True:
            answer = str.upper((input("Have you already watched this movie? Enter Y or N. : ")))
            if answer in ['Y', 'N']:
                break
            else:
                print("Invalid input. Please enter a Y or a N. ")
                continue
        if answer == 'Y':
            hasSeen = False
        elif answer == 'N':
            print("Enjoy the movie!")
            hasSeen = True

moviePicker()


texts: Which function is faster levenshtein() or similar_text()?

texts:
Brief

I wrote two functions using levenshtein() and similar_text().
The functions will find similar words from the dictionary in the input array with the wrong words. At the same time, the found words are stored in the associative array by passing the wrong variant to the array key and the correct variant of the words to the value of the array.

First function using levenshtein()

function getLevenshtein($inputWordsArray, $dict){
    $shortest = -1;
    $result = array();
    foreach ($inputWordsArray as $input) {
        foreach ($dict as $word) {
            $lev = levenshtein($input, $word);
            if ($lev == 0) {
                $closest = $word;
                $shortest = 0;
                break;
            }
            if ($lev <= $shortest || $shortest < 0) {
                $closest  = $word;
                $shortest = $lev;
                $result[$input] = $closest;
            }
        }
    }
    if($count = count($result) > 0) return $result;
    return false;
}

Second function using similar_text()

function getSimilar($inputWordsArray, $dict){
    $result = array();
    foreach ($inputWordsArray as $input){
        $match = 0;
        foreach ($dict as $word){
            similar_text($word, $input, $percent);
            if ($percent > $match){
                $closest = $word;
                $match = $percent;
            }
        }
        $result[$input] = $closest;
    }
    if($count = count($result) > 0) return $result;
    return false;
}

Usage:

$inputWordsArray = array('desription','programing','exteds','plaer','moie','edt','laavel');
$dict = array('description','programming','extends','player','level','laravel','etc','edit','movie');

echo "Usage levenshtein:";
echo "
";
    print_r(getLevenshtein($inputWordsArray, $dict));
echo "
";

echo "Usage similar text:";
echo "
";
    print_r(getSimilar($inputWordsArray, $dict));
echo "
";

Output:

Usage levenshtein:

Array
(
    [desription] => description
    [programing] => programming
    [exteds] => extends
    [plaer] => player
    [moie] => movie
    [edt] => edit
    [laavel] => laravel
)

Usage similar text:

Array
(
    [desription] => description
    [programing] => programming
    [exteds] => extends
    [plaer] => player
    [moie] => movie
    [edt] => edit
    [laavel] => laravel
)

Is my algorithm correct? Is it possible to optimize the function? Which one should I use for a large number of vocabulary? I need the result in the form of an associative array.


texts: Ping-pong game with JavaScript and Canvas

texts:
I have created my first ping-pong game with JavaScript and Canvas. I will be glad if anybody can tell me how to optimize the code and functionality.

https://github.com/nikitalarionov/js-pong

First collision detection:

//Function to check collision between ball and one of
//the paddles
function collides(b, p) {

    if(b.x + ball.r >= p.x + p.w && b.x - ball.r <= p.x + p.w) {

        if (b.y + b.r >= p.y && b.y + b.r <= p.y + p.h && b.x - b.r <= p.x) {
            paddleHit = 1;
            if(b.x < W/ 2) {
                hit++;
            } else if (b.x > W / 2) {
                hit2++;
            }
            return true;
        }
        else if(b.y - b.r <= p.y && b.y - b.r >= p.y - p.h && b.x + b.r >= p.x) {
            paddleHit = 2;
            if(b.x < W/ 2) {
                hit++;
            } else if (b.x > W / 2) {
                hit2++;
            }
            return true;
        }
        else return false;

    }
}

I experience bad performance when the ball hits an angle of one of the paddles:

// Function that updates everything, score, positions, main game logic
function update(){
    // Move the padles
    for(var i = 0; i <= padles.length; i++) {
        var p = padles[i];
        if (i === 0 && players[0].moveUp) {
            if (p.y <= 0) {
                p.y = 0;
            }
            else {
                                    // is it how i move left paddle
                                    // it is doesn't work good like a mousemove
                                    // animations is slowly, i dont know how to fix it
                p.y -=25;
            }
        }
        if (i === 0 && players[0].moveDown) {
            if (p.y + p.h >= H) {
                p.y = H - p.h;
            }
            else {
                p.y += 25;
            }
        }
        if (mouse.y && i === 1) {
            if (p.y + p.h >= H && mouse.y > p.y) {
                p.y = H - p.h;
            }
            else {
                p.y = (mouse.y -50) - p.w / 10;
            }
        }
    }

            // ... some code

}

There I have very lazy animation and moving of the left paddle. I use keys for it outside of the animation cycle:

    // Add Global Event to handle keyboards buttons
window.addEventListener('keydown', function(e) {
    if (e.keyCode === 87) {
        players[0].moveUp = true;
    } else
    if (e.keyCode === 83) {
        players[0].moveDown = true;
    }
}, false);

window.addEventListener('keyup', function(e) {
    if (e.keyCode === 87) {
        players[0].moveUp = false;
    } else
    if (e.keyCode === 83) {
        players[0].moveDown = false;
    }
}, false);


texts: Using ADO to run sql script (with GO syntax) in inno setup

texts:
I am using this code to run my sql scripts in inno setup. However ADO gives an error if the script contains GO syntax within it. I added my own code to overcome this problem.

My code below splits the script at each GO statement and run each section separately. I think this could be done in better ways.

[code]
const
 adCmdText = $00000001;
 adExecuteNoRecords = $00000080;

procedure RunScript();
var
 tString: TStringList;
 ADOCommand: Variant;
 ADORecordset: Variant;
 ADOConnection: Variant;
 i, len: Integer;
 strToQuery, str: String;
begin
 try
 ADOConnection := CreateOleObject('ADODB.Connection');
 ADOConnection.ConnectionString :=
  'Provider=SQLOLEDB;' +               // provider
  'Data Source=(local)\SQL2000;' +   // server name
  'Initial Catalog=databasename;' +       // default database
  'User Id=userId;' +                // user name
  'Password=password;';                   // password
 ADOConnection.Open;
 try
  ADOCommand := CreateOleObject('ADODB.Command');
  ADOCommand.ActiveConnection := ADOConnection;
   tString:= TStringList.Create;
   tString.LoadFromFile('C:\sqlscript.sql');
   len:= tString.Count;
   strToQuery:='';
   for i:=0 to len-1 do begin
    str := trim(tString[i]);
    if POS('go', lowercase(str)) = 1  then begin
     //If GO is found run the script added in to strToQuery since last GO
     ADOCommand.CommandText := strToQuery;
     ADOCommand.Execute(NULL, NULL, adCmdText or adExecuteNoRecords);
     strToQuery:='';        //Clear the string to start adding till next GO
     end else strToQuery:= strToQuery +#13#10+ str;  //Add the script to strToQuery
    end;
    ADOCommand.CommandText := strToQuery;
    ADOCommand.Execute(NULL, NULL, adCmdText or adExecuteNoRecords);
 finally
  ADOConnection.Close;
  tString.Free;
 end;
 except
  MsgBox(GetExceptionMessage, mbError, MB_OK);
 end;
end;

Any suggestion to update the code will be much appreciated.


texts: Simple string-root detection in a string-family

texts:
(This problem is related to Simple string-split by root and sufix algorithm)

There are many ways to find a "common root" of a list of similar strings, that begins with the same substring... The question is what the best way (faster and elegant)?  Do you know a book or library with these algorithms?

Example: in the set {"foo2", "foo1", "foofo"} the root is "foo".

In practical use we need also ignore extrange itens, so we can expect the same "foo" root in the set {"hello", "foo2", "foo1", "foofo", "bye"}. A "root minimal length" parameter is also a practical issue.

Here is a sample and a first candidate algorithm:

  $words = array('i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', 'your', 'yours',
   'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', 'her', 'hers', 'herself',
   'it', 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which',
   'who', 'whom', 'this', 'that', 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be',
   'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an',
   'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for',
   'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',
   'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under',
   'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all',
   'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not',
   'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don',
   'should', 'now');

  /**
   * Get the common start-string of two strings.
   * @param $a string.
   * @param $b string with probable common root.
   * @return string $root or empty.
   * @see this function can feed the root for str_splitByRoot() function.
   */
  function str_getRoot($a,$b) {
        $rootLen = strspn($b ^ $a, "\0"); // length before difference.
        return substr($a,0,$rootLen);
  }

  /**
   * Get the common start-string of many strings.
   * The algorithm splits the string by its differences.
   * @param $a array of strings.
   * @param $b string with probable common root, or integer for array index.
   * @return array of strings with $root and family.
   */
  function array_getRoot($a,$b='',$minLen=1) {
    if (is_integer($b))
        $b = $a[$b];
    if (!$b) $b=$a[0];
    $family = array();
    foreach ($a as $item) {
        $r = str_getRoot($item,$b);
        if (strlen($r)>=$minLen) {
            $family[]=$item;
            if ($r!=$b) $b=$r;
        } //if
    } // for
    array_unshift($family,$b);
    return  $family;
  }

Applying in the example:

$list = array("foo2", "hello", "foo1", "foofo", "bye");
$fam = array_getRoot($list);
print "\nThe root of list is ".array_shift($fam); // foo

Using to show the roots of the $words list:

  sort($words); // not necessary
  foreach($words as $i){
       $fam4 = array_getRoot($words,$i,4);
       $root = array_shift($fam4);
       if (count($fam4)>1)
            print "\n * $i - ($root) ".join(', ',$fam4);
       else { // repeate da same procedure:
            $fam3 = array_getRoot($words,$i,3);
            $root = array_shift($fam3);
            if (count($fam3)>1)
                 print "\n * $i - ($root) ".join(', ',$fam3);
       }
  }

Some results:

* about - (abo) about, above
* again - (again) again, against
* her   - (her) her, here, hers, herself
* hers  - (hers) hers, herself
* you   - (you) you, your, yours, yourself, yourselves
* yourself - (your) your, yours, yourself, yourselves


texts: Basic Nginx server environment creation script

texts:
Here's a script I wrote for raising up a basic Nginx server environment.

The script includes an internal script named csb (create Sblock) which is used to create Sblocks in a comfortable way. As I'm new to Linux, I might have had about 2-3 mistakes, especially in that internal script.

#!/bin/bash -x
function nginx {

    apt-get update -y && apt-get upgrade -y
    apt-get install unattended-upgrades tree zip unzip -y
    dpkg-reconfigure --priority=low unattended-upgrades
    mkdir /root/backups /root/backups/db /root/backups/dirs

    ufw app list # Orient your firewall for Nginx.
    cd /usr/src && rm -fv csf.tgz
    wget https://download.configserver.com/csf.tgz && tar -xzf csf.tgz
    cd csf && sh install.sh
    sed -i 's/TESTING = "1"/TESTING = "0"/g' /etc/csf/csf.conf
    csf -r && perl /usr/local/csf/bin/csftest.pl

    cd /usr/local/src && wget http://www.rfxn.com/downloads/maldetect-current.tar.gz && tar -xzf maldetect-current.tar.gz
    cd maldetect-* && bash ./install.sh && cd ~

    # systemctl stats/stop/start/restart/reload/disable/enable # disable/enable --- at boot. # nginx -t
    apt-get install nginx mysql-server php-fpm php-mysql
    sed -i 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g' /etc/php/7.0/fpm/php.ini
    sed -i 's/server_names_hash_bucket_size ..;/server_names_hash_bucket_size ..;/g' /etc/nginx/nginx.conf
    restart php7.0-fpm
    # http://ip_address

    cat <<-'CSB' > /etc/nginx/sites-available/csb
        #!/bin/sh
        for domain; do
        > "/etc/nginx/sites-available/${domain}.conf" cat <<EOF
        server {
            listen 80;
            listen [::]:80;
            root /var/www/html/${domain};
            index index.php index.html index.htm index.nginx-debian.html;
                server_name ${domain} www.${domain};

            location / {
                try_files $uri $uri/ =404;
            }

            location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
            }

            location ~ /\.ht {
                deny all;
            }
        }
        EOF
    ln -s /etc/nginx/sites-available/${domain} /etc/nginx/sites-enabled/
        done
        systemctl restart nginx.service
    CSB
    chmod +x /etc/nginx/sites-available/csb

    cat <<-'BASHRC' > /etc/bash.bashrc
    alias csb="bash /etc/nginx/sites-available/csb"
    BASHRC

    reboot
} nginx

Note: For some reason I can't indent the code under ln, here in Code Review.


texts: Ruby function to fetch, filter, and generate data

texts:
I'm currently writing a script and I decided to run cane over it to look for some issues, and the following method was highlighted. I've done my best to cut it back, and at this point I'm inclined to leave it as-is, however cane is still giving it a pretty high rating of 23 (15 is the point it starts complaining) so I wanted to get some more input. Other than perhaps splitting fetching and generating does anyone have any ideas?

def self.generate(template, output_file, company)
  puts 'Fetching data...'
  @data = Provider::GenericProvider.create_provider(company['type'].to_sym, company).data

  valid_keys = @data.keys.sort {|a,b| -(a <=> b)}[0,10]
  @data = @data.select {|k, _| valid_keys.include? k}

  valid_keys = @data.keys.sort {|a,b| -(a <=> b)}[0,2]

  loop do
    break if :done == choose {|menu| timesheet_menu valid_keys, menu}
  end

  puts 'Generating output...'
  # Used as a result of the ERB binding
  #noinspection RubyUnusedLocalVariable
  data = @data.select {|k, _| valid_keys.include? k}
  File.write(output_file, ERB.new(File.read(template), nil, '-').result(binding))
end

EDIT:

I just split it, and ended up with the below function, which still scores 19 due to the various lambdas used to control sorting and filtering the data despite being pretty easy to follow still:

def self.fetch_data(company)
  data = Provider::GenericProvider.create_provider(company['type'].to_sym, company).data

  valid_keys = data.keys.sort {|a,b| -(a <=> b)}[0,10]
  data = data.select {|k, _| valid_keys.include? k}

  valid_keys = data.keys.sort {|a,b| -(a <=> b)}[0,2]

  loop do
    break if :done == choose {|menu| timesheet_menu data, valid_keys, menu}
  end

  data.select {|k, _| valid_keys.include? k}
end


texts: Is the LINQ version faster than the foreach one?

texts:
Since I don't know how LINQ works under the hood, I can't decide what version is best to use in term of rapidity of execution. I've done some testing with my testing data (Point Cloud) but I can't see a clear difference between the 2. The only thing I know is that the real life data will be a larger Point Cloud so my guess is that the LINQ would be faster but this is only if LINQ doesn't do a for each under the hood. If it's the case, the 2 functions would be the same. What is your advice?

By the way, cylindre is a 3D cylinder and I want to know which point are inside.

Version 1 without LINQ

for (int i = 0; i < fpc.Vertices.Length; i++)
{
    if (cylindre.IsPointInside(fpc.Vertices[i]))
        listPoint.Add(fpc.Vertices[i]);
}

Version 2, with LINQ

var insidePoint =
    from pt1 in fpc.Vertices
    where cylindre.IsPointInside(pt1)
    select pt1;

    foreach (Point3D pt2 in insidePoint)
    {
        listPoint.Add(pt2);
    }


texts: Interface for unit of work pattern and repository pattern

texts:
I'm trying to design a well defined yet simple interface for the unit of work and repository patterns. My UoW's are exposed to services and services then "get repositories" that it needs to query. I know returning IQueryable<T> for repositories is a religious war. Because repositories are only exposed to the service, all queries are performed inside the service and therefore I can test the queries. Is there anything I should change for these interfaces? All criticisms are greatly appreciated!

public interface IUnitOfWork : IDisposable
{
    bool IsActive { get; }

    bool WasCommitted { get; }

    /// <summary>
    /// Commits all changes made on the unit of work.
    /// </summary>
    void Commit();

    bool WasRolledBack { get; }

    /// <summary>
    /// Rolls back all changes made on the unit of work.
    /// </summary>
    void Rollback();

    /// <summary>
    /// Returns an instance of an entity with the specified key that is attached to the unit of work without
    /// loading the entity from a repository.
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    T Load<T>(int id)
        where T : class;

    void Attach<T>(T entity)
        where T : class, IIdentifiable;

    void Detach<T>(T entity)
        where T : class;

    IRepository<T> GetRepository<T>()
        where T : class;
}

public interface IRepository<T>
    where T : class
{

    IUnitOfWork UnitOfWork { get; }

    void Add(T entity);

    void Remove(T entity);

    /// <summary>
    /// Returns an instance of an entity with the specified key that is attached to the unit of work by loading
    /// the entity from the repository.
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    T Get(int id);

    IQueryable<T> All();
}


texts: Creating a dictionary of strings and list of strings

texts:
I have a List of objects, List<myObject> objectList, and each object contains a List of strings like so:

myObject: StringList( "A_1", "B_1", "C_1", "D_1", "E_1", "F_1" )
myObject: StringList( "A_2", "B_2", "C_1", "D_2", "E_2", "F_1" )
myObject: StringList( "A_2", "B_3", "C_1", "D_3", "E_2", "F_1" )

I'm trying to merge the lists into a dictionary of: Dictionary<string, List<string>>, where the final results will look like so:

Dictionary: { [A:1,2]  [B:1,2,3]  [C:1]  [D:1,2,3]  [E:1,2]  [F:1] }

Here is what I have done, and it does work:

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();

foreach (myObject result in objectList)
{
    foreach (var item in result.StringList)
    {
        string Key = item.Split('_')[0];
        string Value = item.Split('_')[1];

        List<string> sValue = new List<string>();
        bool exists = dict.TryGetValue(Key, out sValue);

        if (exists && !sValue.Contains(Value))
        {
            sValue.Add(Value);
            dict[Key] = sValue;
        }
        else if (!exists)
        {
            sValue = sValue ?? new List<string>();
            sValue.Add(Value);
            dict.Add(Key, sValue);
        }
    }
}

Is there a better way to do this, where I don't have to use two foreach loops? Is there a way to do it without using any foreach loops?

I have tried using lambda but this is as far as I got:

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();

foreach (myObject result in objectList)
{
    dict = result.StringList.Select(x => x.Split('_'))
                            .GroupBy(x => x[0])
                            .ToDictionary(x => x.Key, x => x.Select(g => g[1]).ToList());
}

The problem is that the expression keeps overwriting any existing entries in the dictionary each time I iterate through the loop.

Is there a way to keep the existing entries, groupby the Key and add to the existing list of values but don't duplicate any values?

I think the answer lies in this part of the expression:

x => x.Select(g => g[1]).ToList()

but I'm not 100% sure.


texts:
This is a question about Project Euler number 2, a relatively easy one. The question is:

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

My code is pretty simple; I'm interested in other ways of doing it (lamdba expressions for instance).

namespace ProjectEuler
{
    public class Fibonacci
    {
        // find even number fibonacci terms < 4 mil.
        public void FibonacciSequence(int limit)
        {
            var sw = Stopwatch.StartNew();
            int a = 0;
            int b = 1;
            int total = 0;
            int evenTerms = 0;

            while (total < limit)
            {
                total = a + b;
                a = b;
                b = total;
                if (total % 2 == 0)
                {
                    evenTerms += total;
                }
            }
            sw.Stop();
            Console.WriteLine(evenTerms);
            Console.WriteLine(sw.ElapsedMilliseconds);
        }
    }
}


texts:
I am solving the "Spread the Word" problem on CodeChef:

  Snackdown 2019 is coming! People have started to spread the word and tell other people about the contest. There are \$N\$ people numbered 1 through \$N\$. Initially, only person 1 knows about Snackdown. On each day, everyone who already knows about Snackdown tells other people about it. For each valid \$i\$, person \$i\$ can tell up to \$A_i\$ people per day. People spread the information among the people who don't know about Snackdown in the ascending order of their indices; you may assume that no two people try to tell someone about Snackdown at the same moment. Each person is only allowed to start telling other people about Snackdown since the day after he/she gets to know about it (person 1 can start telling other people already on day 1). How many days does it take for all people to know about Snackdown?

But my code exceeds the given time limit. It solves the problem in 1.01 seconds, but the time limit in there, is 1.00 seconds. I am attaching the code snippet written in C++ below:

#include<iostream>
using namespace std;
int main()
{
    int t,n;
    cin>>t;
    for(int i = 0; i<t;i++)
        {
        int c = 0,f=0,p=1;
        cin>>n;
        int a[n];
        for(int i = 0; i<n; i++) cin>>a[i];
        f = a[0];
        while(p<n)
        {

            for(int i = 0; i<f; i++)
            {
                p += a[i];
            }
            c++;
            f = p;
        }
    cout<<c;
    }
}

It would be a great help if someone modifies the above code into an efficient one!


texts:
I do always search online English dictionaries for words that I know but want to get a better understanding of and/or to know their other meanings, or for words that I do not know at all. Therefore, I have written a simple program to help me search for English words faster and easier.

Here is my code:

import webbrowser

class OnlineDictionary:
    """Represents an online dictionary.

    Attributes:
      name: str
      url: str
    """
    def __init__(self, name, url, sep):
        """Initializes an OnlineDictionary object.

        name: str
        url: str
        sep: str
        """
        self.name = name
        self.url = url
        self.sep = sep

    def search(self, query):
        """Searches the dictionary for a given query.

        url: str
        query: str
        """
        query = self.sep.join(query.split())
        webbrowser.open(self.url + query)

def print_instructions(message, instructions, names, num_of_dics):
    """Prints the available dictionaries, their corresponding
    numerals and the instructions.

    message: str
    instructions: str
    names: list
    num_of_dics: int
    """
    print(message)

    for numeral, name in zip(range(num_of_dics), names):
        print(numeral, name)

    print()
    print(instructions)

def get_user_data(num_of_dics):
    """Asks the user for which dictionary
    to use and for what to search for.

    num_of_dics: int

    Returns: tuple
    """
    while True:
        to_use = input('Specify which dictionary or dictionaries to use.\n')
        if to_use == '*':
            break

        try:
            to_use = to_use.replace(' ', '').split(',')
            numerals = []

            for num in to_use:
                num = int(num)
                if num not in range(num_of_dics):
                    raise
                numerals.append(num)

            to_use = set(numerals)  #set is used to get rid of any duplicates
            break

        except:
            continue

    query = input('Type something to search for.\n')

    return (to_use, query)

def __main__():
    names = ('Merriam-Webster Dictionary', 'Oxford Dictionary', 'Camberidge Dictionary', 'Collins Dictionary',
             'Longman Dictionary of Contemporary English','The American Heritage Dictionary of the English Language')

    urls = ('https://www.merriam-webster.com/dictionary/', 'https://en.oxforddictionaries.com/definition/',
            'https://dictionary.cambridge.org/dictionary/english/', 'https://www.collinsdictionary.com/dictionary/english/',
            'https://www.ldoceonline.com/dictionary/', 'https://ahdictionary.com/word/search.html?q=')

    seps = ('%20', '_', '-', '-', '-', '%20')  #seperators are used if there are spaces in the query

    collection = list(zip(names, urls, seps))

    num_of_dics = len(names)

    message = "These are the available dictionaries:\n"

    instructions = """To use a dictionary type its corresponding numeral.
To use more than one dictionary seperate the numerals with ",".
To use all of them type "*". Do not type the quotation marks.\n"""

    print_instructions(message, instructions, names, num_of_dics)

    while True:
        to_use, query = get_user_data(num_of_dics)
        print()
        dics_to_use = collection if to_use == '*' else [collection[num] for num in to_use]
        dics = [OnlineDictionary(name, url, sep) for name, url, sep in dics_to_use]

        for dic in dics:
            print('Searching %s for "%s"...' % (dic.name, query))
            dic.search(query)

        print('Finished searching. Check your Web browser.\n')

if __name__ == '__main__':
    __main__()

I would appreciate any suggestions and comments.


texts: PHP strpos() as a way to implement an swear word filter

texts:
I wrote a short function that should check if user input does contain any bad words that I predefined inside $bad_words array. I don't even care to replace them - I just want to ban if there are any. The code seems to work as it should - in the example below will detect the quoted string badword and the function does return true.
My question: Is this a good way to use foreach and strpos()? Perhaps there is better way to check if $input contains one of the $bad_words array elements? Or is it just fine as I wrote it?
function checkswearing($input)
{
    $input = preg_replace('/[^0-9^A-Z^a-z^-^ ]/', '', $input);//clean, temporary $input that just contains pure text and numbers

    $bad_words = array('badword', 'reallybadword', 'some other bad words');//bad words array

    foreach($bad_words as $bad_word)
    {//so here I'm using a foreach loop with strpos() to check if $input contains one of the bad words or not
        if (strpos($input, $bad_word) !== false)
            return true;//if there is one - no reason to check further bad words
    }
    return false;//$input is clean!
}

$input = 'some input text, might contain a "badword" and I\'d like to check if it does or not';

if (checkswearing($input))
    echo 'Oh dear, my ears!';
else
{
    echo 'You are so polite, so let\'s proceed with the rest of the code!';
    (...)
}


texts:
I am writing, as review, Modern C++ compliant versions of sorting algorithms I previously have seen. This post is about selection sort, and selection sort only.

Whilst selection sort is rather simple, straightforward, and not the best in terms of performance, I wanted to know if there were any ways to improve upon my implementation, especially in terms of performance:

// Orders a list of values by repeatedly putting the smallest
// or largest unplaced value into its final position.
template<typename T>
void sort_selection(std::vector<T> & arr)
{
    std::vector<T>::iterator min, beg, end = arr.end();
    for (beg = arr.begin(); beg < end; ++beg)
    {
        min = std::min_element(beg, end);
        if (*min < *beg)
            std::iter_swap(min, beg);
    }
}

I'm using local variables min, beg, end outside the loop to lower the amount of dereferencing and stack allocations and take advantage of temporal locality. Also I am using iterators and min_element, iter_swap to be modern c++ compliant.