texts: Import Excel, unpivot data, output tab-delimited for SQL Import

texts:
I have a client GL file (Excel) that needs to be regularly imported to SQL Server (as tab-delimited txt).

Sample (simplified):

PayCode  PayDesc   Dept1   Dept2   Dept3
========================================
REG      Regular   00001   00001   00002
VAC      Vacation  00011   00012   00013
HOL      Holiday   00021   00022   00022

However, the number of columns (departments) may change over time, and SQL Server doesn't support importing files with an uncertain column count. So rather than recode the SQL import each time a change occurs, I decided to "unpivot" the data prior to import, so the resulting table structure will always be static:

PayCode  PayDesc    DeptCode  GLCode
====================================
REG      Regular    Dept1     00001
REG      Regular    Dept2     00001
REG      Regular    Dept3     00002
VAC      Vacation   Dept1     00011
VAC      Vacation   Dept2     00012
VAC      Vacation   Dept3     00013
HOL      Holiday    Dept1     00021
HOL      Holiday    Dept2     00022
HOL      Holiday    Dept3     00022

I've got the script functioning, but being a PS lightweight, I thought I would solicit for enhancement ideas. I feel like I'm missing good pipeline opportunities due to inexperience.

Code updated using feedback from briantist

$srcDir = "C:"
$srcTab = "Sheet1"
$srcFile = Join-Path -Path $srcDir -ChildPath "ClientGL.xlsx"
$outFile = Join-Path -Path $srcDir -ChildPath "ClientGL.txt"
$delim = "`t"

## Export from Excel to tab-delimited .txt
Write-Host "Launch Excel"
$Excel = New-Object -comobject Excel.Application
$Excel.Visible = $False
$Excel.displayalerts = $False
Write-Host "Open $srcFile"
$Workbook = $Excel.Workbooks.Open($srcFile)
$Workbook.Worksheets.Item($srcTab).Select()
Write-Host "Export $outFile as Tab-Delimited TXT"
$Workbook.SaveAs("$outFile",-4158)
Write-Host "Quit Excel"
$Excel.Quit()
If(Get-Process -name excel){Stop-Process -name excel}

## Import data and headers
Write-Host "Import $outFile data"
$inData = Import-Csv -Path $outFile -Delimiter $delim
Write-Host "Import $outFile headers"
$inHeaders = (Get-Content -Path $outFile -TotalCount 1) -split $delim

## Build output datatable
Write-Host "Build output datatable"
$outData = New-Object System.Data.DataTable
[Void]$outData.Columns.Add("PayCode",[string])
[Void]$outData.Columns.Add("PayDesc",[string])
[Void]$outData.Columns.Add("DeptCode",[string])
[Void]$outData.Columns.Add("GLCode",[string])

## Unpivot Department columns, and add results to datatable
Write-Host "Unpivot each Dept column and add data to datatable"
for($col=2; $col -lt $inHeaders.Count; $col++)
{
    $dept = $inHeaders[$col]  #current $col header name
    foreach($row in $inData)
    {
        $dr = $outData.NewRow();
        $dr.Item("PayCode") = $row.PayCode
        $dr.Item("PayDesc") = $row.PayDesc
        $dr.Item("DeptCode") = $dept  #header name
        $dr.Item("GLCode") = $row.$dept  #row.col value
        $outData.Rows.Add($dr)
    }
}

## Output modified file
Write-Host "Output modified $outFile"
$outData | Export-Csv -Path $outFile -Delimiter $delim -notypeinformation -Force
Write-Host "Remove quotes from file"
(Get-Content -Path $outFile) | ForEach-Object {$_ -replace '"', ""} | Out-File -FilePath $outFile -Force


texts:
I have written a program in Ruby which calculates the median of a streaming set of numbers dynamically. For each number that arrives, the median is calculated for all the numbers that have arrived so far.

The issue I am facing is that the program times out on some inputs, and, most likely, the reason is that I return a variable that is passed to a routine. I need to do this because this variable changes inside the routine and I can't pass by reference in Ruby.

Is there any workaround for this inability to pass by reference? I have seen the code involving "binding" but I found it clumsy. Why does Ruby not have a simple, straightforward pass-by-reference as do C++, C# and Java? I have pasted my code below.

I maintain two heaps max and min. The value in any node in the max (min) heap is at least as large (small) as the value in any node below it. Any arriving number is inserted into the max heap or min heap with the proviso that the difference in the number of nodes in the two heaps does not exceed 1, and that the heap property be preserved for both heaps. With this proviso, the median can be calculated from the root elements in the two heaps.

Node=Struct.new(:v,:l,:r)do
end

max=0
min=0

def count(m)
        m==0 ? 0 : 1 + count(m.l) + count(m.r)
end

def delete(d,type)

      if d==0
          return 0
      end
      if type=="max"
          if d.l==0 && d.r==0
              return 0
          elsif d.l!=0 && d.r!=0
              if  d.l.v > d.r.v
                  d.v= d.l.v
                  d.l=delete(d.l,type)
              else
                  d.v= d.r.v
                  d.r= delete(d.r,type)
              end
          elsif d.l == 0
                 d.v= d.r.v
                 d.r=delete(d.r,type)
              else
                 d.v= d.l.v
                 d.l=delete(d.l,type)
              end
     else
          if d.l==0 && d.r==0
              return 0
          elsif d.l!=0 && d.r!=0
              if  d.l.v < d.r.v
                  d.v= d.l.v
                  d.l=delete(d.l,type)
              else
                  d.v= d.r.v
                  d.r= delete(d.r,type)
              end
          elsif d.l == 0
                 d.v= d.r.v
                 d.r=delete(d.r,type)
              else
                 d.v= d.l.v
                 d.l=delete(d.l,type)
              end
     end
return d
    end

def insert(v,type,t)

        if t==0
            return t=Node.new(v,0,0)
        end
            if type=="max"
                    if v>t.v
                    tmp=t.v
                    t.v=v
                                t.l=insert(tmp, type,t.l)
            else
                                t.l=insert(v,type,t.l)
            end
            else
                        if v<t.v
                    tmp=t.v
                    t.v=v
                                t.l=insert(tmp, type,t.l)
            else
                                t.l=insert(v,type,t.l)
            end
        end
                return t

end

n=gets.chomp.to_i

n.times do
    v=gets.chomp.to_i
     if (k=count(max)-count(min))==1
        if v<max.v
            tmp=max.v
            max=delete(max,"max")
            min=insert(tmp,"min",min)
            max=insert(v,"max",max)
        else
                        min=insert(v,"min",min)
        end
        p (max.v+min.v)/2.0
     elsif  k==0
        if max==0 || v<=max.v
                        max=insert(v,"max",max)
            p max.v/1.0
        else
                        min=insert(v,"min",min)
            p min.v/1.0
        end
     else
                if v>min.v
            tmp=min.v
            min=delete(min,"min")
            max=insert(tmp,"max",max)
            min=insert(v,"min",min)
        else
                        max=insert(v,"max",max)
        end
        p (max.v+min.v)/2.0
     end
end


texts: Storing, fetching, and deleting battle simulation results

texts:
my connection code:

    <?php
try {
    $pdo = new PDO("mysql:host=localhost;dbname=game;
    charset=utf8", "root");
}
catch(PDOException $e){
    echo $e->getMessage();
}
?>

my class code:

    <?php
include './database/config.php';

class DB {
    public function dataWarrior($battle,$name,$type){
        global $pdo;
        try {
            $stmt = $pdo->prepare("SELECT battle_id,warrior_name,warrior_type,health,attack,defense,speed,evade
            FROM battle WHERE battle_id = :battle AND warrior_name = :name AND warrior_type = :type LIMIT 1");

            $stmt->execute(array(":battle"=>$battle, ":name"=>$name, ":type"=>$type));

            return $stmt;
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
    }
    public function checkBattleID($battle){
        global $pdo;
        try {
            $stmt = $pdo->prepare("SELECT battle_id FROM battle WHERE battle_id=:battle LIMIT 1");

            $stmt->execute(array(":battle"=>$battle));

            if($stmt->rowCount()>0){
                return false;
            }
            else {
                return true;
            }
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
    }
    public function createBattle($warrior){
        global $pdo;
        try {
            $stmt = $pdo->prepare('INSERT INTO battle(battle_id,warrior_name,warrior_type,
            health,attack,defense,speed,evade) VALUES(:battle,:name,:type,:health,:attack,:defense,:speed,:evade)');

            $stmt->execute(array(':battle'=>$warrior['battle'], ':name'=>$warrior['name'],
            ':type'=>$warrior['type'], ':health'=>$warrior['health'], ':attack'=>$warrior['attack'],
            ':defense'=>$warrior['defense'], ':speed'=>$warrior['speed'], ':evade'=>$warrior['evade']));
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
    }
    public function deleteBattle($battle){
        global $pdo;
        try {
            $stmt = $pdo->prepare('DELETE FROM battle WHERE battle_id = :battle');
            $stmt->execute(array(':battle'=>$battle));
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
    }
}
?>


texts:
I am doing a CS practice exercise in which you are supposed to sort exactly three numbers using only if statements.  I wrote the following code in LISP and would appreciate any suggestions how to improve on my code.  Thank you!

(defun generate-three ()
  (loop for l from 1 to 3 collect (random 25)))

(defun result (a b c) (format t "The sorted result is (~d,~d,~d)~%" a b c))

(let (a b c (the-three (generate-three)))
    (format t "~a ~%" the-three)
    (setq a (first the-three) b (second the-three) c (third the-three))
    (if (< a b)
      (if (< b c) (result a b c)
        (if (< a c) (result a c b) (result c a b)))
      (if (< a c) (result b a c)
        (if (< b c) (result b c a) (result c b a)))))

Based on feedback from commenters, the revised code looks as follows:

(defun my-sort-3 (a b c)
    (if (< a b)
      (if (< b c) (list a b c)
        (if (< a c) (list a c b) (list c a b)))
      (if (< a c) (list b a c)
        (if (< b c) (list b c a) (list c b a)))))

(destructuring-bind (a b c) (loop repeat 3 collect (random 25))
  (format t "The sorted result of (~d,~d,~d) is ~a ~%" a b c (my-sort-3 a b c)))

Latest iteration - note the changes in the final "format" statement:

(defun my-sort-3 (a b c)
    (if (< a b)
      (if (< b c) (list a b c)
        (if (< a c) (list a c b) (list c a b)))
      (if (< a c) (list b a c)
        (if (< b c) (list b c a) (list c b a)))))

(destructuring-bind (a b c) (loop repeat 3 collect (random 25))
  (format t "The sorted result of (~{~d~^, ~}) is (~{~d~^, ~})~%" (list a b c) (my-sort-3 a b c)))


texts:
I must implement a simple Caesar cipher class. Initializer takes two parameters - number of positions to shift the alphabet (integer) and the alphabet used (as string, not necessarily the standard English alphabet). The class must have two instance methods encrypt and decrypt, which take a string and do the respective action based on the parameters of the initializer. These are my rspec tests:

describe "Caesar" do

  latin_encrypter = Caesar.new 4
  dna_encrypter = Caesar.new 3, 'ACTG'

  it 'encrypts correctly' do
    expect(latin_encrypter.encrypt 'hello').to eq "lipps"
  end

  it 'encrypts correctly using DNA alphabet' do
    expect(dna_encrypter.encrypt 'ACCTGA').to eq "GAACTG"
  end

  it 'decrypts correctly' do
    expect(latin_encrypter.decrypt 'lipps').to eq 'hello'
  end

  it 'decrypts correctly using DNA alphabet' do
    expect(dna_encrypter.decrypt 'GAACTG').to eq 'ACCTGA'
  end
end

and this is my implementation:

class Caesar
  def initialize(shift, alphabet = 'abcdefghijklmnopqrstuvwxyz')
    @shift = shift % alphabet.size
    @alphabet = alphabet
  end

  def encrypt(string)
    string.chars.map { |char| @alphabet[@alphabet.index(char) + @shift - @alphabet.size] }.join
  end

  def decrypt(string)
    string.chars.map { |char| @alphabet[@alphabet.index(char) - @shift] }.join
  end
end

Is this an optimal algorithm for encryption/decryption or is there a better one (perhaps using gsub)?


texts:
I create a cache manager to manage a system of cache exchangeable by another implementation.

I use the CacheManager class throughout my program. If I want to change the implementation I simply add a provider and I add it in my dependency container

Is it correct to do this like that?

ICache

namespace Caching
{
    public interface ICache
    {
        object Get(string key);

        void Set(string key, object value);
    }
}

ICacheManager

namespace Caching
{
    public static class CacheManager
    {
        private static ICache cache;
        private static readonly object syncRoot = new object();

        private static ICache Cache
        {
            get
            {
                lock (syncRoot)
                {
                    if (cache == null)
                    {
                        cache = Container.Instance.Resolve<ICache>();
                    }
                }

                return cache;
            }
        }

        public static object Get(string key)
        {
            return Cache.Get(key);
        }

        public static void Set(string key, object value)
        {
            Cache.Set(key, value);
        }
    }
}

MemoryCacheProvider

using System.Runtime.Caching;

namespace Caching.Providers
{
    public class MemoryCacheProvider : ICache
    {
        public object Get(string key)
        {
            return MemoryCache.Default.Get(key);
        }

        public void Set(string key, object value)
        {
            MemoryCache.Default.Add(key, value, DateTime.Now.AddMinutes(5));
        }
    }
}

Main

static void Main(string[] args)
{
    Container.Instance.RegisterType<ICache, MemoryCacheProvider>();
}


texts: Format python data structures in HTML no dependencies

texts:
My poorly written tests suggests that the module works as intended. I fear this is to good to be true. I don't known how to write unit tests for this. I'm new to writing tests and I think this module would be hard for a unit test master to test.

#-*-coding:utf8;-*-
#qpy:3
#qpy:console

SINGLETONS = [
    'area',
    'base',
    'br',
    'col',
    'command',
    'embed',
    'hr',
    'img',
    'input',
    'keygen',
    'link',
    'meta',
    'param',
    'source',
    'track',
    'wbr'
]

# Constants.
SP = ' '
EMPTY = ''

def is_singleton(tag):
    return tag in SINGLETONS

def not_singleton(tag):
    return is_singleton(tag) == False

def html_attributes(**kw):
    # 'attrs' is the elements attributes.
    # Iterate over the keys and values of the kw dict
    # and transform them into a string of html
    # attributes. Two html attribute keys are
    # Python keywords 'class' and 'id' to set
    # the id and class of and element use:
    # cls for class and '_id' for 'id.'
    attrs = EMPTY
    n_attrs = len(kw)
    for key, value in zip(kw.keys(), kw.values()):
        if key == 'cls':
            key = 'class'

        if key == '_id':
            key = 'id'

        if n_attrs > 1:
            attrs += '{}="{}"{}'.format(key, value, SP)
        else:
           attrs += '{}="{}"'.format(key, value)
    return attrs.rstrip(SP)

def tagify(tagname, data=EMPTY, **kw):
    if isinstance(data, str):
        data = data.replace('\n', '
')
    attrs = html_attributes(**kw)

    if not attrs:
        opentag = '<{}>'.format(tagname)
    else:
        opentag = '<{}{}{}>'.format(tagname, SP, attrs)

    if not_singleton(tagname):
        closetag = '</{}>'.format(tagname)
    else:
        closetag = None

    if not closetag:
        return '{}'.format(opentag)

    if data:
        return '{}{}{}'.format(opentag, data, closetag)
    else:
        return '{}{}'.format(opentag, closetag)

def tag(tagname, **deco_kw):
    '''
    Decorate a functions output with html by
    passing it through tagify.
    '''
    def deco(func):
        def wraps(*args, **kw):
            content = func(*args, **kw)
            return tagify(tagname, content, **deco_kw)
        return wraps
    return deco

def tests():
    '''
    This is a temporary function for
    testing the module.
    Please dont include this in any reviews.
    '''
    @tag('li', cls='link', _id='list-item')
    def link(name, **kw):
        return tagify('a', name, **kw)

    @tag('article', cls='main', _id='spam')
    def paragraph(content, **kw):
        return tagify('p', content, **kw)

    print(link(__name__, src=__file__))
    print(paragraph(list(range(10)), _id='monty'))

if __name__ == '__main__':
    tests()

test() output

__main__

[0, 1, 2, 3, 4]


texts:
Sometimes I would like use word count to describe someone's contribution, so, I wrote a query to stat the word count for a given stackexchange user, based on SEDE. click to run it online

DECLARE @total_count int, @post_id int, @post_body nvarchar(max);

SET @total_count = 0;

DECLARE vendor_cursor CURSOR FOR
SELECT id, Body
FROM posts
WHERE posts.OwnerUserId = 9872;

OPEN vendor_cursor

FETCH NEXT FROM vendor_cursor
INTO @post_id, @post_body
PRINT FORMATMESSAGE('  id   | count | total count')
WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE @count int;
    SELECT @count = (LEN(@post_body ) - LEN(replace(@post_body , ' ', '')))
    SELECT @total_count = @total_count + @count
    PRINT FORMATMESSAGE('%6d | %5d | %d', @post_id, @count, @total_count)
    FETCH NEXT FROM vendor_cursor
    INTO @post_id, @post_body
END


texts:
I'm calling these two methods on a Worker that is executed every 24 hours at midnight in the background.

The code seems to be a little bit difficult to read and I'm not sure if i'm iterating through the collections in the smartest way.

Is there a more elegant or faster way to iterate on these methods?
Would you suggest any other change?

  # Deletes UserDiscounts when the discount belongs to a segment that the user does not belong to
  def clean_user_discounts
    UserDiscount.all.each do |user_discount|
      user_segment = UserSegment.find_by(user: user_discount.user)
      discount_segment = DiscountSegment.find_by(discount: user_discount.discount)
      user_segment_id = user_segment ? user_segment.segment_id : nil
      discount_segment_id = discount_segment ? discount_segment.segment_id : nil
      user_discount.delete unless discount_segment_id == user_segment_id
    end
  end

  # Creates UserDiscounts when a user belongs to a segment and that segment has a discount
  def create_user_discounts
    UserSegment.all.each do |user_segment|
      DiscountSegment.where(segment: user_segment.segment).each do |discount_segment|
        unless UserDiscount.find_by(discount: discount_segment.discount, user: user_segment.user)
          UserDiscount.create(discount: discount_segment.discount, user: user_segment.user)
        end
      end
    end
  end


texts:
I was asked to implement bucket sort recently from my friend.

  Bucket sort is mainly useful when input is uniformly distributed over
  a range. For example, consider the following problem. Sort a large set
  of floating point numbers which are in range from 0.0 to 1.0 and are
  uniformly distributed across the range.

How do we sort the numbers efficiently? I would like to ask for feedback for my solution. I also performed some  diagram and benchmark it against quicksort.
I appreciate any feedback.

function bucketsort(arr, range_min, range_max) {
  if (arr.length <= 1) {
    return arr;
  }
  if (arr.length < 20) {
    return arr.sort();
  }

  let result = [];
  let numberOfBuckets = Math.ceil(Math.sqrt(arr.length));

  for (let i = 0; i < numberOfBuckets; i++) {
    result.push([]);
  }

  let bucketRange = (range_max - range_min) / numberOfBuckets;

  for (let i = 0; i < arr.length; i++) {

    let bucketIndex = Math.floor((arr[i] - range_min) / bucketRange);

    result[bucketIndex].push(arr[i]);
  }

  let finalResult = []
  for (let i = 0; i < result.length; i++) {
    finalResult = finalResult.concat(bucketsort(result[i], i * bucketRange + range_min, (i+1) * bucketRange + range_min));
  }

  return finalResult;
}

// console.log(bucketsort([0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434, 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434], 0.0, 1.0));

// console.log(bucketsort([1,2,3,4,5,6,7,8,9,10,11,12,13,14], 0, 15));

// bucketRange = 0.33333
//
//     0.0        0.333       0.666       1.0
//     [ [       ],  [       ],  [       ]]

// calling bucketsort on large arrays compared to quicksort

let test = [];

for (let i = 0; i < 100000; i++) {
  test.push(Math.random());
}

function quicksort(arr) {
  return arr.sort((a, b) => {
    return a - b;
  });
}

console.time("quicksort: ");
quicksort(test);
console.timeEnd("quicksort: ");

console.time("bucketsort: ");
bucketsort(test, 0.0, 1.0);
console.timeEnd("bucketsort: ");

Array.sort


texts: Form with a country list statically or dynamically generated

texts:
I want to create a form with a country drop down list so I can just google and get all the countries but the question should I just encode it statically or generate dynamically with PHP. (Note it doesn't have to be necessary country list just any static list with lots of data)

HTML Example:

<select>
  <option value="AF">Afghanistan</option>
  <option value="AX">Åland Islands</option>
  <option value="AL">Albania</option>
  ...
</select>

or use php array i.e.

$countries = array (
    'AF' => 'Afghanistan',
    'AX' => 'Åland Islands',
    'AL' => 'Albania',
    ...
    );

and generate html

<!--Method 1-->
<select>
  <?php foreach($countries as $id => $country) echo "<option value='$id'>$country</option>\n" ?>
</select>

Also which method of generating is preferred or is more readable?

<!--Method 2-->
<select>
  <?php foreach($countries as $id => $country):?>
  <option value="<?php echo $id; ?>"><?php echo $country; ?></option>
  <?php endforeach; ?>
</select>

And finally should I escape variables with htmlspecialchars even though I know the output will be valid?


texts:
I made this simple tabbed app template and one thing in particular I am not sure about is my creation of a pageMap object. The thinking behind it is that you can add a new page to the app by adding an entry in the pageMap as well as the list being mapped to produce the tabs.

The components are from material-ui and for brevity I didn't include the imports / style boilerplate.

function App() {
const classes = useStyles();
const [page, setPage] = useState('Home')

const pageMap = {
'Home':  {'component': <Home />, 'icon': <HomeIcon /> },
'Favourites': {'component': <Favourites />, 'icon': <StarIcon /> },
};

return (

  <CssBaseline />
  <AppBar position="fixed" className={classes.appBar}>
    <Toolbar>
      <Typography variant="h6" noWrap>
        Dashboard
      </Typography>
    </Toolbar>
  </AppBar>
  <Drawer
    className={classes.drawer}
    variant="permanent"
    classes={{
      paper: classes.drawerPaper,
    }}
    anchor="left"
  >

    <Divider />
    <List>
      {['Home', 'Favourites'].map((text, index) => (
        <ListItem button key={text} onClick={() => setPage(text)} selected={text==page}>
          <ListItemIcon>{pageMap[text]['icon']}</ListItemIcon>
          <ListItemText primary={text} />
        </ListItem>
      ))}
    </List>
    <Divider />
  </Drawer>

    {pageMap[page]['component']}

);
}


texts: Generate random characters from ranges 0–9 and a–Z

texts:
I’m trying to generate 5 characters from the ranges 0–9 and a–Z. Is my solution optimal or did I overthink it a little? Would hardcoding a character list be more optimal?

const numbers = [
    ...Math.random()
        .toString(36)
        .substr(2, 5),
].map(element => (Math.random() > 0.5 ? element : element.toUpperCase())).join('');


texts: Count line of code for a JavaScript project

texts:
Here is my bash script that I just wrote to count line of code for JavaScript project.

It will list number of:

Comment lines
Blank lines
All lines

Here is my script:

#!/bin/bash

fileExt="*.js"

allFiles=$(find ./ -name "$fileExt")

commentLines=$((perl -ne 'print "$1\n" while /(^\s+\/\/\s*\w+)/sg' $allFiles;\
perl -0777 -ne 'print "$1\n" while /(\*\*.*?\*\/)/sg' $allFiles) | wc -l)

blankLines=$(grep '^[[:space:]]*//' -r --include $fileExt | wc -l)

allLines=$(echo $allFiles | xargs wc -l | tail -n 1 | cut -d " " -f 2)

echo -e "\nTotal comments line is: $commentLines.\n\
Total blank lines is: $blankLines.\n\
\nTotal all lines is: $allLines."

Let me explain it a little bit:

First, we need to list all files that end with ".js" within the project:

allFiles=$(find ./ -name "$fileExt")

Second, we count all comment lines:

commentLines=$((perl -ne 'print "$1\n" while /(^\s+\/\/\s*\w+)/sg' $allFiles;\
perl -0777 -ne 'print "$1\n" while /(\*\*.*?\*\/)/sg' $allFiles) | wc -l)

There are 2 types of comment lines in JavaScript:

Line start with only space and // or only //

Example:

//this is a comment line

// this is a comment line
    // this also is a comment line

All above are comment lines, and we got 3 lines total here. But the following is not comment lines:

function foo(params 1) { // return void

}

The line contains // return void is not considered as a comment, so we do not need to count it.

And for the kind of comment line. I using the regex with perl to print all comment lines that match with regex:

/(^\s+\/\/\s*\w+)/sg

Multi-line comment (JSDOC):

Example:

/**
 * return something
 * @param {object} obj
 * return void
*/

So we need to count all number of lines that start from the line with /** and end with */, we have 5 lines here.

I use this regex to match:

perl -0777 -ne 'print "$1\n" while /(\*\*.*?\*\/)/sg' $allFiles

So the total number of comment lines is the sum of two types comment lines above.

Third

We need to count blank lines.

I use the following command to match:

grep '^[[:space:]]*//' -r --include $fileExt | wc -l

Finally

We need to count all lines:

echo $allFiles | xargs wc -l | tail -n 1 | cut -d " " -f 2

I wonder if my solution is good enough or not.


texts:
Im am solving Count total set bits:

  Find the sum of all bits from numbers 1 to N.

  Input:

  The first line of input contains an integer T denoting the number of
  test cases. The first line of each test case is N.

  Output:

  Print the sum of all bits.

  Constraints:

  1 ≤ T ≤ 100
  1 ≤ N ≤ 1000

  Example:

  Input:
  2
  4
  17

  Output:
  5
  35

  Explanation:
  An easy way to look at it is to consider the number, n =
  4:
  0 0 0 = 0
  0 0 1 = 1
  0 1 0 = 1
  0 1 1 = 2
  1 0 0 = 1
  Therefore , the total number of bits is 5.

My approach:

/*package whatever //do not write package name here */

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

class GFG {
    private static int noOfBits (int N)
        {
            int sum = 0;
            for (int i = 1; i <= N; i++)
                {
                    if ((i & i-1) == 0)
                        {
                            sum += 1;
                        }
                    else
                        {
                            sum += numBits(i);
                        }
                }
            return sum;
        }

    private static int numBits (int num)
        {
            int sum = 0;
            int rem;
            while (num != 0)
                {
                   rem = num%2;
                   num /= 2;
                   sum += rem;
                }
            return sum;
        }

    public static void main (String[] args) throws IOException {
        //code
        BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
        String line = br.readLine();
        int T = Integer.parseInt(line);
        String line2;
        int N;

        for (int i = 0; i < T; i++)
            {
                line2 = br.readLine();
                N = Integer.parseInt(line2);
                System.out.println(noOfBits(N));
            }
    }
}

I have the following questions with regards to the above code:

How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?


texts:
This is my first attempt at writing a programme: a BMI calculator written in Python. Please give me feedback on the programme overall, as well as how easy the code is to interpret and adapt.

from sys import exit

bmi = ["what is bmi?", "what is bmi", "bmi", "bmi?"]

male=["male","m"]

female=["female", "f"]

def bmi_q():
    print "Very good! Let's start with your age."
    age= float(raw_input("How old are you %s?   >   " %name))

    height= float(raw_input("How tall are you, in m?    >   "))

    weight=float(raw_input("What do you weigh in kg?    >   "))
    Gender=raw_input("Finally, are you male or female? (No offense.)    >   ")

    result = bmi_c(weight,height)

    analysis(result)

def analysis(result):
    if result < 18.5:
        print "Your BMI is %d." % round(result,2), "You are far too skinny, please eat more."
        print "A healthy BMI is between 18.5 and 25."
        exit(0)

    elif result > 25:
        print "Your BMI is %d." % round(result,2), "You are far too fat, please eat less."
        print "A healthy BMI is between 18.5 and 25."
        exit(0)

    else:
        print "Your BMI is %d." % round(result,2), "Congratulations! You're well fit."
        print "A healthy BMI is between 18.5 and 25."
        exit(0)

def bmi_c(weight,height):
    return weight / (height**2)

def consent_q():
    unsure = True

    while True:
        print "Would you like to calculate your BMI?"
        consent = raw_input("> Answer: \"Yes\", \"No\", or \"What is BMI?\" >   ")

        if consent.lower() == "no":
            print ("What did you open a script called \"BMI\" for then??? This is all I can do!")

        elif consent.lower() in bmi:
            print """Wise man at CDC say:
                \"Body Mass Index (BMI) is a person's weight in kilograms
                divided by the square of height in meters.

                A high BMI can be an indicator of high body fatness.

                BMI can be used to screen for weight categories that may
                lead to health problems but it is not diagnostic of the
                body fatness or health of an individual.\" """

        elif consent.lower() == "yes":
            unsure = False
            bmi_q()

        else:
            print "Sorry, me no hablo ingles so good. Try again."

print "Thank you for running the BMI script."
print "Before we begin, please tell me your name:"
name=raw_input(">   ")
print "Hello %s, nice to meet you." % (name)
consent_q()


texts: Calculate the weekday from a date (M-D-Y)

texts:
This Common Lisp exercise is to write a program that can calculate the weekday given a string of the format "M-D-Y."  It was more challenging than I expected.  If you have suggestions about how to simplify this code, I will be very grateful.

;;  2.7 Day of Week. A program for converting Gregorian dates in the form month-day-year to day of the
;;  week is the following. Let the Gregorian date be represented by M-D-Y where we have the following
;;  definitions:
;;    M is the month of the year. Let m be the month number derived from M by the rule m is M - 2 if M >= 3
;;    and m is M + 10 otherwise.
;;    d is the day of the month.
;;    y is the year of the century.
;;    c is the number of the previous century.
;;  The algorithm is as follows:
;;    (a) A is the integer part of (13m - 1)/5.
;;    (b) B is the integer parg of y/4.
;;    (c) C is the integer part of c/4.
;;    (d) D = A + B + C + d + y - 2c.
;;    (e) Make R equal to the remainder of D/7.
;;    (f ) Interpret R as Sunday if R = 0, Monday if R is 1, etc

(defun read-date () (format t "Enter the gregorian date in the format (M-D-Y): ~%") (read))

(defun flatten (the-list)
  (cond ((null the-list) nil)
    ((atom the-list) (list the-list))
    (t (concatenate 'list (flatten (car the-list)) (flatten (cdr the-list))))))

(defun split (split-char string-to-split)
  (let ((next-split-char (position split-char string-to-split)))
    (if next-split-char (flatten (list (safely-read-from-string (subseq string-to-split 0 next-split-char))
                  (split split-char (subseq string-to-split (+ 1 next-split-char)))))
      (list (safely-read-from-string string-to-split)))))

(defun weekday-code (bigM bigD bigY)
    (let* ((m (if (>= bigM 3) (- bigM 2) (+ bigM 10)))
          (y (mod bigY 100))
          (littleC (/ (- bigY y) 100))
          (A (floor (- (* 13 m) 1) 5))
          (B (floor y 4))
          (C (floor littleC 4))
          (D (- (+ A B C bigD y) (* 2 littleC)))
          (R (mod D 7)))
      (format t "m: ~a y: ~a c: ~a A: ~a B: ~a C: ~a D: ~a R: ~a ~%" m y littleC A B C D R)
      R))

(defun check-date-format (bigM bigD bigY)
  (cond ((or (< bigM 1) (> bigM 12)) (error "The month (~a) is not in the range 1-12." bigM))
    ((< bigY 0) (error "The year (~a) is less than 0." bigY))
    ((or (< bigD 1) (> bigD 31)) (error "The day (~a) is not in the range 1-31." bigD))))

(let ((gregorian-date (read-date)))
      (destructuring-bind (bigM bigD bigY) (split #\- gregorian-date)
    (check-date-format bigM bigD bigY)
    (format t "~a was (or will be) a ~[Sunday~;Monday~;Tuesday~;Wednesday~;Thursday~;Friday~;Saturday~]." gregorian-date (weekday-code bigM bigD bigY))))


texts:
The problem I'm solving is:

given a length of an arithmetic progression, and a limit to the
terms (see below), find all progressions that work.
All terms of the progressions must be of the form a²+b², and
0 ≤ a²+b² ≤ limit.

I have the following code:
from math import ceil
with open('ariprog.in') as fin:
    ariLen = int(fin.readline().strip())
    ariLim = int(fin.readline().strip())
def generate(bound):
    max_len=((bound**2)*2)+1
    parity = [0]*max_len
    for i in range(bound+1):
        for j in range(bound+1):
            parity[i**2+j**2] = 1
    return parity

parity = generate(ariLim)
lenpar = len(parity)
big_mama_ar = []
# print(lenpar)
for a in range(lenpar-1):
    if parity[a] == 1:
        for d in range(1, ceil((lenpar-a)/(ariLen-1))):
            for n in range(1, ariLen):
                # print('a:', a)
                # print('d:', d)
                # print('n:', n)
                if parity[a+n*d] != 1:
                    break
            else:
                big_mama_ar.append((a,d))
                pass
big_mama_ar.sort(key=lambda x: x[1])
with open('ariprog.out', 'w') as fout:
    if big_mama_ar == []:
        fout.write('NONE\n')
    else:
        for i in big_mama_ar:
            fout.write(str(i[0])+' '+str(i[1])+'\n')

This code times out on my grader when ariLen is 21 and ariLim is 200. The time limit is 5 seconds, and on my computer, it takes 22 seconds.
ariprog.in is

21
200


texts: Dictionary with ISet key as a collection of names

texts:
I'm writing a command-line utility and I need to find commands (and parameters) by name. The name can either be a full name like save or a shortcut s.

I thought I use a dictionary with an ISet key and a custom comparer. At first I had a list and searched for the name with LINQ but I'd like to have something more convenient. The performance doesn't matter - this time convenience goes first. There will be at most a few dozens of commands. I know I could use a string and map each name to the command but this isn't cool :-)

First, there is a NameSet that is the base class for concrete sets.

class NameSet : HashSet<string>
{
    protected NameSet(IEnumerable<string> keys, IEqualityComparer<string> keyComparer)
    : base(keys ?? throw new ArgumentNullException(nameof(keys)), keyComparer)
    { }
}

one with the suffix CI which stands for Case Insensitive (like the collation in Sql Server)

class NameSetCI : NameSet
{
    private NameSetCI(IEnumerable<string> keys, IEqualityComparer<string> keyComparer)
    : base(keys, keyComparer)
    {}

    public static NameSetCI Create(params string[] keys) =>
        new NameSetCI(keys, StringComparer.OrdinalIgnoreCase);
}

the other with the suffix CS which obviously stands for Case Sensitive.

class NameSetCS : NameSet
{
    private NameSetCS(IEnumerable<string> keys, IEqualityComparer<string> keyComparer)
    : base(keys, keyComparer)
    { }

    public static NameSetCS Create(params string[] keys) =>
        new NameSetCS(keys, StringComparer.Ordinal);
}

The comparer for this is very simple. It just looks if there is any overlapping set.

internal class SetComparer : IEqualityComparer<ISet<string>>
{
    public bool Equals(ISet<string> x, ISet<string> y) => x.Overlaps(y);

    public int GetHashCode(ISet<string> obj) => 0; // Force Equals.
}

With the hash code 0 it doesn't seem to be O(1) anymore but all the keys are in one place an the logic is just a single Overlaps method. LINQ wouldn't be faster anyway and it would mean a lot more work.

Example:

var dic = new Dictionary<NameSetCI, string>(new SetComparer());

dic.Add(NameSetCI.Create("foo", "bar"), "fb");
dic.Add(NameSetCI.Create("qux"), "q");
dic[NameSetCI.Create("baz")] = "b";
dic[NameSetCI.Create("bar")].Dump(); // fb
dic.Add(NameSetCI.Create("foo"), "f"); // bam!


texts:
The working hours are saved in Database like

{"1" : "11:00 - 14:30", "2" : "17:30 - 23:00"}

Now i wrote a function like, which test is the shop is opened or close at the moment. Can someone please suggest if there is a better way to do this? And how i can check if the timing are like

{"1" : "11:00 - 14:30", "2" : "17:30 - 02:00"}

Where 02:00 o clock is next day's time.
here is my funciton.

$working_hours = json_decode('{"1" : "11:00 - 14:30", "2" : "14:39 - 23:00"}');
$is_open = false;
$time = time();

foreach ($working_hours as $key=>$value)
{
   $working_hour = explode(" - ", $value);
   $from = strtotime($working_hour[0]);
   $to = strtotime($working_hour[1]);

   if ($time >= $from && $time <= $to)
   {
       $is_open = true;
       break;
   }
}

echo "\n***********************";
echo "\n". date("d.m.Y H:i", $time);

if($is_open)
   echo "\nOpend";
else
   echo "\nClosed";

echo "\n***********************";


texts: Deleting email using mailcore with imapSession

texts:
The following function works fine. However, deleting 1 mail takes about 4 seconds (from start of operation to the firing of the completion handler).

Currently, using mailcore2, copying mails on the Gmail server.

Are there any significant issues?

func deleteOnServer (indexSet: MCOIndexSet) {
     NSLog("will delete email")
     let sessionForOperation = getSessionForOperation()
     let localCopyMessageOperation = sessionForOperation.copyMessagesOperationWithFolder("INBOX", uids: indexSet, destFolder: account.trashFolderPath)
     localCopyMessageOperation!.start { (error, uidMapping) -> Void in
            if let error = error {
                NSLog("error in deleting email : \(error.userInfo!)")
            } else {
                NSLog("email deleted")
            }
        }
    }

}

My session is configured as follows:

    func createNewIMAPSessionWith(userName: String, hostname: String, oauth2Token: String) -> MCOIMAPSession {
        let retSession =  MCOIMAPSession()
        retSession.hostname = hostname
        retSession.port = 993
        retSession.username = userName
        retSession.OAuth2Token = oauth2Token
        retSession.authType = MCOAuthType.XOAuth2
        retSession.connectionType = MCOConnectionType.TLS
        retSession.maximumConnections = 2
        retSession.timeout = NSTimeInterval(60)
        retSession.allowsFolderConcurrentAccessEnabled = true

        return retSession
}


texts: Checking for existing key in multi-dimensional array

texts:
Say I have a data structure like this:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(3) "foo"
  ["message"]=>
  array(1) {
    ["action"]=>
    string(3) "PUT"
  }
}

Where 'message' and 'action' are both optional.  To check if they're present my first attempt would be to write something like this:

if (array_key_exists('message', $array) && array_key_exists('action', $array['message'])){
}

Is there a cleaner implementation?


texts:
I'm struggling with some code that should be a very simple computation of a duration. The purpose of the code is to generate a random delay, constrained by an upper and lower limit. The reason I'm looking for advise here is that what should be a simple task, has turned into a behemoth of type conversions:

package main

import (
        "math/rand"
        "time"
)

func main() {
        // parameters, hardcoded for illustration purposes only
        tMin := float32(1.2)
        tMax := float32(2.7)

        // intention is approximately this:
        // delay := tMin + rand.Float32() * (tMax - tMin)

        delay := time.Duration((tMin + rand.Float32() * (tMax - tMin)) * float32(time.Second))

        time.Sleep(delay)
}

Questions:

Apart from rounding errors (which I'm happy to ignore here), does this code have any actual bugs that I missed?
I know that elegance is in the eye of the beholder, but is there any way to write this more elegantly? In particular, I'd like to reduce the number of required casts, preferably down to zero.


texts: Converting a region code (short string up to 4 characters) to a 32-bit integer

texts:
There is a function that converts region code strings (1 to 4 characters and null terminator) to 32 bit integers codes to be used in maps as keys or values.

Blindly casting char* to int* is bad as it can be less than 4 bytes including null terminator.

Currently the code is like this

uint32_t region_code_key(const char* region_code) {
  unsigned char buf[4] = "\0";
  strncpy(buf, region_code, 4);
  return *((int*)buf);
}

I believe that buf may be not well aligned causing problems on some platforms. Is it a valid concern?
The endianity is not a concern as such numbers are used only on local machines, only as keys.

It's a very simple function but If alignment concern is valid I see two ways to rewrite it.
Here we just convert it byte by byte

uint32_t region_code_key(const char* region_code) {
    unsigned char* region_code_iter;
    unsigned char* region_code_end = region_code+4;
    uint32_t code_as_int = 0;
    for (region_code_iter = region_code; region_code_iter!=region_code_end && (*region_code_iter); ++region_code_iter) {
        code_as_int = (code_as_int<<8) | (*region_code_iter);
    }
    return code_as_int;
}

Alternatively use union to ensure better alignment:

uint32_t region_code_key(const char* region_code) {
union {
                char[sizeof(uint32_t)] as_string;
                uint32_t as_int;
} region = {0, 0, 0, 0};
strncpy(region.as_string, region_code, sizeof (region_code));
return region.as_int;
}

Is alignment a valid concern? If so which alternative seems less ugly to you?


texts:
I need to validate multiple input fields using React. I am using a simple if-else block for each input field but I would like to optimize my code and make it better. I feel there can be a better way to validate multiple input fields.

  validateForm = () => {
    const {
      firstName, lastName, mobileNo, city, empType, salary
    } = this.state;

    if (firstName !== '') {
      this.setState({
        firstNameMsg: '',
        validFirstName: false
      });
    } else {
      this.setState({
        firstNameMsg: 'Please enter a vaild first name.',
        validFirstName: true
      });
    }
    if (lastName !== '') {
      this.setState({
        lastNameMsg: '',
        validLastName: false
      });
    } else {
      this.setState({
        lastNameMsg: 'Please enter a vaild last name.',
        validLastName: true
      });
    }

    if (mobileNo.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && !(mobileNo.match(/0{5,}/))) {
      this.setState({
        mobileNoMsg: '',
        validMobileNo: false
      });
    } else {
      this.setState({
        mobileNoMsg: 'Please enter a vaild mobile number.',
        validMobileNo: true
      });
    }

    if (city !== '') {
      this.setState({
        cityMsg: '',
        validCity: false
      });
    } else {
      this.setState({
        cityMsg: 'Please enter a vaild city.',
        validCity: true
      });
    }

    if (empType !== 'Self-Employed') {
      this.setState({
        empTypeMsg: '',
        validEmpType: false
      });
    } else {
      this.setState({
        empTypeMsg: 'Some msg',
        validEmpType: true
      });
    }

    if (salary !== '') {
      this.setState({
        salaryMsg: '',
        validSalary: false
      });
    } else {
      this.setState({
        salaryMsg: 'Please enter a vaild salary.',
        validSalary: true
      });
    }
  }


texts:
I'm building a procedure which compares two JSON objects and return two JSON objects with differences between each (compared keys and values).
But I have relatively superficial SQL knowledge, so I need your review to avoid any simple mistakes and improve my code.

Compares "first" against "second" and returns the values in "first" that are not present in "second" OR has different value

DELIMITER $$

DROP PROCEDURE IF EXISTS json_diff $$

# Compares "first" against "second" and
# returns the values in "first" that are not present in "second" OR has different value
CREATE PROCEDURE json_diff(IN first JSON, IN second JSON, INOUT firstResult JSON, INOUT secondResult JSON)
BEGIN
    DECLARE oldKey VARCHAR(300);
    DECLARE oldVal, newVal INT;
    DECLARE i, secondHasKey INT DEFAULT 0;
    DECLARE oldKeys, newKeys JSON;

    SELECT JSON_KEYS(first) INTO oldKeys;
    SELECT JSON_KEYS(second) INTO newKeys;

    WHILE i < JSON_LENGTH(oldKeys) DO
        SELECT JSON_EXTRACT(oldKeys, CONCAT('$[',i,']')) INTO oldKey;
        SELECT JSON_EXTRACT(first, CONCAT('$.', oldKey)) INTO oldVal;

        SELECT JSON_CONTAINS_PATH(second, 'one', CONCAT('$.', oldKey)) INTO secondHasKey;

        IF secondHasKey = 1 THEN
            SELECT JSON_EXTRACT(second, CONCAT('$.', oldKey)) INTO newVal;
            IF oldVal != newVal THEN
                SELECT JSON_INSERT(firstResult, CONCAT('$.', oldKey), oldVal) INTO firstResult;
                SELECT JSON_INSERT(secondResult, CONCAT('$.',oldKey), newVal) INTO secondResult;
            end if;
        ELSE
            SELECT JSON_INSERT(firstResult, CONCAT('$.', oldKey), oldVal) INTO firstResult;
        end if;

        SET i = i + 1;
    end while;
END $$

Use above PROCEDURE to make bidirectional comparison.

DELIMITER $$

DROP PROCEDURE IF EXISTS json_diff_both $$

CREATE PROCEDURE json_diff_both(IN first JSON, IN second JSON, INOUT firstResult JSON, INOUT secondResult JSON)
BEGIN
    CALL json_diff(first, second, firstResult, secondResult);
    CALL json_diff(second, first, secondResult, firstResult);
END $$


texts:
I'm pretty new to programming in general.  I work with MySQL at my job but my knowledge of scripting language is rudimentary at best.  I've been learning JavaScript via Codecademy but I got bored and set out on my own.  I made this Tic Tac Toe game, which is purely text-based and predictably boring.  I was just wondering if anyone has suggestions for improving the code, especially in terms of following programming best practices.  Also any advice for turning this into a visual game would be greatly appreciated, especially with HTML5.

var board = [0, 0, 0, 0, 0, 0, 0, 0, 0];
var gameOver = true;
var check = true;
var i = Math.floor(Math.random()*2);

var transInput = function(p){
    switch(p) {
        case "A3": return 0;
        case "B3": return 1;
        case "C3": return 2;
        case "A2": return 3;
        case "B2": return 4;
        case "C2": return 5;
        case "A1": return 6;
        case "B1": return 7;
        case "C1": return 8;
        default  : console.log("Entry Unknown!");
    }
};

var transOutput = function(p){
    switch(p) {
        case  1: return "x";
        case 10: return "o";
        default: return " ";
    }
};

var drawBoard = function(){
    console.log("3 " + transOutput(board[0]) + "|" + transOutput(board[1]) + "|" + transOutput(board[2]));
    console.log(" -----");
    console.log("2 " + transOutput(board[3]) + "|" + transOutput(board[4]) + "|" + transOutput(board[5]));
    console.log(" -----");
    console.log("1 " + transOutput(board[6]) + "|" + transOutput(board[7]) + "|" + transOutput(board[8]));
    console.log(" A B C");
};

drawBoard();

if(i === 0){
    console.log("You go first!");
} else {console.log("Computer goes first!");}

while (gameOver){
    if(i === 0){
        var playerMove = transInput(prompt("Your move!"));
        var check = true;
        while(check){
            if(board[playerMove] === 0){
                board[playerMove] = 1;
                drawBoard();
                i = 1;
                check = false;
            } else {
                playerMove = transInput(prompt("Try again."));
            }
        }
    } else if(i === 1){
        console.log("Computer's turn...");
        var check = true;
        while(check){
            var compMove = Math.floor(Math.random()*9);
            if(board[compMove] === 0){
                board[compMove] = 10;
                drawBoard();
                i = 0;
                check = false;
            }
        }
    }
    var scores = [
        board[0] + board[1] + board[2],
        board[3] + board[4] + board[5],
        board[6] + board[7] + board[8],
        board[0] + board[3] + board[6],
        board[1] + board[4] + board[7],
        board[2] + board[5] + board[8],
        board[0] + board[4] + board[8],
        board[2] + board[4] + board[6]
    ];

    var scoreSum = 0;

    for(var k = 0; k < board.length; k++){
        scoreSum += board[k];
    }

    for(var j = 0; j < scores.length; j++){
        if(scores[j] === 3){
            console.log("You Win!");
            gameOver = false;
            break;
        } else if(scores[j] === 30){
            console.log("You Lose!");
            gameOver = false;
            break;
        }
    }

    if(
        gameOver === true && (
            scoreSum === 54 ||
            scoreSum === 45
        )
    ){
        console.log("Draw!");
        gameOver = false;
    }
}


texts: Displaying records from a MySQL database

texts:
I've started learning .NET with MVC 4 in C# and I built a basic application to display records from a MySQL database. It's incredibly basic, but it's the best I could come up with being a complete beginner to C# and all.

Most of the programming I do is with Ruby on Rails and I tried to carry over some of the design patterns that I use there. I don't know the .NET conventions so if you see anything that should be changed please let me know.

Also, I don't fully understand how to find records with LINQ and pass them to the view. I ended up getting lucky and finding an article that somewhat explained it, but I don't have a firm grasp on the subject.

The naming conventions for my entities and models are wrong. It's a long story, basically it took me a while to connect to my MySQL database and when I generated them I didn't care how they were named.

RouteConfig.cs

routes.MapRoute(
    name: "root",
    url: "",
    defaults: new { controller = "Authors", action = "Index" }
);

routes.MapRoute(
    name: "author_books",
    url: "authors/{author_id}/books",
    defaults: new { controller = "Authors", action = "Books" }
);

AuthorsController.cs

public class AuthorsController : Controller {

    bookisticsEntities be = new bookisticsEntities();
    //
    // GET: /Authors/

    public ActionResult Index() {
       return View(be.authors.ToList());
    }

    public ActionResult Books(int author_id = 0) {
        author aut = be.authors.Find(author_id);

        var books = from b in be.books
                    join a in be.authors
                    on b.author_id equals a.id
                    where b.author_id == author_id
                    select b;

        ViewBag.author_name = aut.name;
        return View(books.ToList());
    }
}

I've omitted the view files because I pretty much left them at default after they were generated.


texts:
I've made a simple clicking game where you spam a button in order to get coins which you can use to buy upgrades to get even more coins.

I've only 2 classes one that is responsible for the game logic - MainGame and one for the items available in the shop - Item.

MainGame

public partial class MainGame : Form
{
    private readonly Item[] purchasableItems = new Item[20];

    private long _currentMoney = 0;
    private long currentMoney
    {
        get { return _currentMoney; }
        set
        {
            _currentMoney = value;
            lbCurrentMoney.Text = $@"{currentMoney} $";
        }
    }

    private long _moneyPerClick = 1;
    private long moneyPerClick
    {
        get { return _moneyPerClick; }
        set
        {
            _moneyPerClick = value;
            bGetMoney.Text = $@"{moneyPerClick} $";
        }
    }

    private Thread countThread = null;
    private bool stop = false;

    public MainGame()
    {
        InitializeComponent();
        Initialize();
    }

    private void Initialize()
    {
        lbCurrentMoney.Text = $@"{currentMoney} $";
        bGetMoney.Text = $@"{moneyPerClick} $";
        for (int i = 0; i < purchasableItems.Length; i++)
        {
            purchasableItems[i] = new Item((long) Math.Pow(2, i + 1), (long) (Math.Pow(2, i + 2)*10), flpShop,
                OnShopItemClickableMouseDown, OnShopItemMouseUp);
        }
        UpdateItemAccessibility();
    }

    private void OnShopItemMouseUp(object s, EventArgs e, Item item)
    {
        stop = true;
        UpdateItemAccessibility();
    }

    private void OnShopItemClickableMouseDown(object s, EventArgs e, Item item)
    {
        stop = false;
        countThread = new Thread(() =>
        {
            while (!stop && currentMoney >= item.RequiredMoney)
            {
                if (lbCurrentMoney.InvokeRequired && bGetMoney.InvokeRequired)
                {
                    Invoke(new MethodInvoker(() =>
                    {
                        currentMoney -= item.RequiredMoney;
                        moneyPerClick += item.DollarsPerClick;
                    }));
                }
                Thread.Sleep(100);
            }
        });
        countThread.Start();
    }

    private void bGetMoney_Click(object sender, EventArgs e)
    {
        currentMoney += moneyPerClick;
        UpdateItemAccessibility();
    }

    private void UpdateItemAccessibility()
    {
        foreach (Item item in purchasableItems)
        {
            item.UpdateAccessibility(currentMoney);
        }
    }
}

Item

public class Item
{
    public delegate void ShopItemEvent(object sender, EventArgs e, Item item);

    public long DollarsPerClick { get; }
    public long RequiredMoney { get; }

    private Button buttonActivator;

    public Item(long dollarsPerClick, long requiredMoney, Control parent, ShopItemEvent onMouseDown, ShopItemEvent onMouseUp)
    {
        DollarsPerClick = dollarsPerClick;
        RequiredMoney = requiredMoney;
        CreateBuyButton(parent, onMouseDown, onMouseUp);
    }

    private void CreateBuyButton(Control parent, ShopItemEvent onMouseDown, ShopItemEvent onMouseUp)
    {
        buttonActivator = new Button
        {
            Text = $@"{DollarsPerClick} $ per click." + Environment.NewLine +
                   $@"Cost : {RequiredMoney}",
            Size = new Size(parent.Width - 10, 40),
            Enabled = false
        };
        buttonActivator.MouseDown += (sender, EventArgs) => onMouseDown(sender, EventArgs, this);
        buttonActivator.MouseUp += (sender, EventArgs) => onMouseUp(sender, EventArgs, this);
        parent.Controls.Add(buttonActivator);
    }

    public void UpdateAccessibility(long currentMoney)
    {
        buttonActivator.Enabled = currentMoney >= RequiredMoney;
    }
}

The code is quite short but I think that there are plenty of stuff to improve.


texts: Extracting queries from controller to model

texts:
I had a complex query in the controller like:

def outgoing_tasks
  @tasks = current_user.
           assigned_tasks.
           uncompleted.
           includes(executor: :profile).
           order("deadline DESC").
           paginate(page: params[:page], per_page: Task.pagination_per_page)
end

and since I have some other collections in that controller I refactored to this:

def outgoing_tasks
  @tasks = current_user.assigned_tasks.assigned_default(page: params[:page])
end

with these new methods in the model:

def self.ordered
  order("deadline DESC")
end

def self.paginated(page: 1)
  paginate(page: page, per_page: self.pagination_per_page)
end

def self.assigned_default(page: 1)
  uncompleted.includes(executor: :profile).ordered.paginated(page: page)
end

Should I do something differently or is this okay?


texts: Rotating lists in linear time and constant space (Java) - follow-up

texts:
(The previous and the initial iteration.)

After some critique, I found the way to keep the rotation operation also for java.util.Lists that do not provide random access iterators:

package net.coderodde.util;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

/**
 * This class contains a static method for rotating lists in linear time and
 * constant space.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Oct 6, 2017)
 */
public final class ListRotation {

    private ListRotation() {}

    /**
     * Performs the list rotation.
     *
     * @param <T> the list element type.
     * @param list the list whose content to rotate.
     * @param rotationCount the number of steps to rotate to the right. If
     * negative, rotates to the left.
     */
    public static <T> void rotate(List<T> list, int rotationCount) {
        Objects.requireNonNull(list, "The input list is null.");
        rotationCount %= list.size();

        if (rotationCount < 0) {
            rotationCount += list.size();
        }

        Collections.<T>reverse(list);
        Collections.<T>reverse(list.subList(0, rotationCount));
        Collections.<T>reverse(list.subList(rotationCount, list.size()));
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<Integer> list =
                new LinkedList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));

        System.out.println(list);

        while (true) {
            int rotationCount = scanner.nextInt();
            rotate(list, rotationCount);
            System.out.println(list);
        }
    }
}

So how does that look now?


texts:
I've prepared a script to manipulate csv files in Windows that simply adds quotes as requested.

The script creates a backup of the original files and overwrite the wrong originals in its same folder.

It works as expected but I'd be really happy to learn from gurus how to improve my code, my thinking and my Python.

#!/usr/bin/python
# coding: utf-8
#
#    ______________________________________
#   / CSV Fix                              \
#   \ LtPitt - 25/02/2015                  /
#    --------------------------------------
#           \   ^__^
#            \  (oo)\_______
#               (__)\       )\/\
#                   ||----w |
#                   ||     ||
#
# This script will fix the manually-edited csv files before import into application

import os
import csv
import shutil
import sys
import time

script_path = os.path.dirname(sys.argv[0])
backup_path = script_path + "\\backup\\"
tmp_path = script_path + "\\tmp\\"

os.chdir(script_path)

paths = [backup_path, tmp_path]

for path in paths:
  if not os.path.exists(path):
    os.makedirs(path)

def fixCsv(csv_file):
  # This function fixes the broken csv adding ; and " where needed and saves the fixed file into the script path
  rows = []
  with open(tmp_path + csv_file, 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=';', quotechar='"')
    for row in spamreader:
      if not ''.join(row).strip():
        pass
      else:
        rows.append(row)

  with open(script_path + "\\" + csv_file, 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL)
    for row in rows:
      spamwriter.writerow(row)

def prepareFiles():
  # This function saves original files in case of errors / reviews and moves originals into tmp folder for elaboration
  current_datetime = str(time.strftime('%Y%m%d%H%M%S') )
  os.makedirs(backup_path + current_datetime)
  for file in os.listdir(script_path):
    if file.endswith(".csv"):
      shutil.copyfile(script_path + "\\" + file, backup_path + current_datetime + "\\" + file)
      shutil.move(script_path + "\\" + file, tmp_path + "\\" + file)

# Let's rock
prepareFiles()
for file in os.listdir(tmp_path):
  if file.endswith(".csv"):
    fixCsv(file)
shutil.rmtree(tmp_path)


texts: Is this correct to reassign already intialized variable?

texts:
I am reading hadoop source code , Here I have a doubt "org.apache.hadoop.util.StringUtils" they reassigned a list which is already intiailized.

  public static Collection<String> getStringCollection(String str){
    List<String> values = new ArrayList<String>();
    if (str == null)
      return values;
    StringTokenizer tokenizer = new StringTokenizer (str,",");
    values = new ArrayList<String>();
    while (tokenizer.hasMoreTokens()) {
      values.add(tokenizer.nextToken());
    }
    return values;
  }

Is there any reason to reassign here?


texts: Implementing checksum add without carry in C

texts:
I need to write a function in C which performs a checksum using the rule "add without carry". As I understand it, the "add without carry" concept is equivalent to the bitxor operator and given that the bitxor operation is associative and commutative, I am relying on that to perform the calculation. Below is my function. Note that the input is in decimal format and the checksum is of the binary digits with final output being in decimal format.

UCHAR checksumAddWoCarry(int num, ...)
{
    va_list valist;  /* List of variable arguments */
    UINT arg1, arg2; /* The first two arguments from the va_list */
    int i;           /* Iterator */
    UINT result;     /* Storage for returned result */

    va_start(valist, num); /* Start the usage of the list */

    arg1 = va_arg(valist,UINT); /* Pull out the first two variable arguments */
    arg2 = va_arg(valist,UINT);
    result = arg1 ^ arg2;
    if (num > 2) {
        for (i = 2; i < num; i++) {
            result ^= va_arg(valist,UINT);
        }
    }

    va_end(valist);

    return (UCHAR)result;
}

An example call would be

result = checksumAddWoCarry(3, 4,5,6);

where I expect that result is 7.

I would like an answer to two related questions.

Is my logic for the implementation correct? Specifically in
regards to my use of the bitxor operator to perform the checksum?
I want to know, aside from the logic of the implementation, if my
method is a good one. Are there any gotchas I could run into? Is
there a better/faster way?


texts: Can phrase be made from whole words in another string?

texts:
I am working to solve this HackerRank puzzle: Hash Tables: Ransom Note
The premise is that if I am given a string like this:

give one grand today

I can find a match for each of the words in the following string, but I cannot use the same word more than once:

give me one grand today night

My code looks like this:
  var ransom = "give one grand today".split(' ');
  var magazine = "give me one grand today night".split(' ');
  var result = ransom.reduce(function(words, word) {
    var index = magazine.indexOf(word);

    if(index !== -1) {
      words.push(word);
      magazine.splice(index, 1);
    }

    return words;
  }, []);

  console.log(result.length === ransom.length ? 'Yes' : 'No' );

My code works for most of the test cases but times out for the large inputs.
How can I make my code faster?


texts: Fetching data via jquery and adding items to a list

texts:
Super-duper javascript noob here. I'm trying to fetch public repos from GitHub, and add them to a dl. I know this won't work on every website due to cross-site scripting, but GitHub offers a JSON-P API. I'm fairly certain that I'm doing this mostly the right way (it works), but the append function looks ugly, and I'm not sure if the way I'm triggering the script is considered best practice.

gh-project.js:

function get_github_public_repos(username) {
    var the_url = "https://api.github.com/users/" + username + "/repos"

    $.ajax({
      url: the_url,
      dataType: 'jsonp',
      type: 'get',
      success: function(data) {
        for(i = 0; i < data.data.length; i++){
          var repo = data.data[i];
          if (!repo.fork) {
            $('#gh-projects').append("
" + repo.name + "" + "
" +
            "
" + repo.description + "
" );
          }
        }
      }
    });
}

projects.html:

Thanks for the pointers.


texts:
After following some suggestions you can find here, I'd like to show you the result:

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

double getDeterminant(std::vector<std::vector<double>> vect, int dimension);

int main() {

    //First, the user has to enter the dimension of the matrix
    int dimension;
    std::cout << "Please enter dimension of Matrix: ";
    std::cin >> dimension;
    std::cout << std::endl;

    if(dimension < 0) {
        std::cout << "ERROR: Dimension cannot be < 0." << std::endl;
        return -1;
    }

    //Now, the user has to enter the matrix line by line, seperated by commas
    std::vector<std::vector<double>> vect(dimension, std::vector<double> (dimension));
    std::string str;
    for(int i = 1; i <= dimension; i++) {
        std::cout << "Enter line " << i << " only seperated by commas: ";
        std::cin >> str;
        std::cout << std::endl;
        str = str + ',';
        std::string number;
        int count = 0;
        for(int k = 0; k < str.length(); k++) {
            if(str[k] != ',') {
                number = number + str[k];
            }
            else if(count < dimension) {
                if(number.find_first_not_of("0123456789.-") != std::string::npos) {
                    std::cout << "ERROR: Not only numbers entered." << std::endl;
                    return -1;
                }
                vect[i - 1][count] = std::stod(number);
                number = "";
                count++;
            }
            else {
                std::cout << "ERROR: Too many numbers entered." << std::endl;
                return -1;
            }
        }
    }

    //Output
    for(int i = 0; i < dimension; i++) {
        for(int j = 0; j < dimension; j++) {
            std::cout << vect[i][j] << " ";
        }
        std::cout << std::endl;
    }

    std::cout << "Determinant of the matrix is : " << getDeterminant(vect, dimension) << std::endl;
    return 0;
}

double getDeterminant(std::vector<std::vector<double>> vect, int dimension) {

    if(dimension == 0) {
        return 0;
    }

    if(dimension == 1) {
        return vect[0][0];
    }

    //Formula for 2x2-matrix
    if(dimension == 2) {
        return vect[0][0] * vect[1][1] - vect[0][1] * vect[1][0];
    }

    double result = 0;
    int sign = 1;
    for(int i = 0; i < dimension; i++) {

        //Submatrix
        std::vector<std::vector<double>> subVect(dimension - 1, std::vector<double> (dimension - 1));
        for(int m = 1; m < dimension; m++) {
            int z = 0;
            for(int n = 0; n < dimension; n++) {
                if(n != i) {
                    subVect[m-1][z] = vect[m][n];
                    z++;
                }
            }
        }

        //recursive call
        result = result + sign * vect[0][i] * getDeterminant(subVect, dimension - 1);
        sign = -sign;
    }

    return result;
}

Do you have any more suggestions to improve the code?

You can find the follow-up question here.


texts: Handling Tasks to read HttpRequestMessage in an Azure Function App

texts:
I am writing an Azure function app to receive a file uploaded through a multipart/form-data HTML form. I think the only way to get my uploaded data is by probing the HttpRequestMessage req but I can only do this using Async extension methods such as .ReadAsMultipartAsync() (it seems)

So I have ended up with this pattern of get-task-and-run-synchronously-if-not-completed, and I am concerned that this might be really wrong:

var multipartTask = req.Content.ReadAsMultipartAsync();
if (!multipartTask.IsCompleted)
{
    multipartTask.RunSynchronously();
}
stream = multipartTask.Result;

I could await each call but that would require me to change the signature of the function to make it an async Task<HttpResponseMessage> and I don't trust that to work correctly within the Azure Functions environment.

Here is the complete code of my function. This is a prototype so I realise there is also some work to do with refactoring out repeated code into other classes.

[FunctionName("Load")]
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "Load")]HttpRequestMessage req, TraceWriter log)
{
    MultipartMemoryStreamProvider stream;
    try
    {
        var multipartTask = req.Content.ReadAsMultipartAsync();
        if (!multipartTask.IsCompleted)
        {
            multipartTask.RunSynchronously();
        }
        stream = multipartTask.Result;
    }
    catch (Exception)
    {
        return req.CreateResponse(HttpStatusCode.BadRequest, "Posted data was not multipart or read failed");
    }
    string fileContent;
    try
    {
        var httpContent = stream.Contents[0];
        var contentTask = httpContent.ReadAsStringAsync();
        if (!contentTask.IsCompleted)
        {
            contentTask.RunSynchronously();
        }
        fileContent = contentTask.Result;
    }
    catch (Exception)
    {
        return req.CreateResponse(HttpStatusCode.InternalServerError, "Unable to read file stream");
    }
    try
    {
        WriteGrammar("stegriff", fileContent);
    }
    catch (Exception)
    {
        return req.CreateResponse(HttpStatusCode.InternalServerError, "Failed to write grammar");
    }
    return req.CreateResponse(HttpStatusCode.Created, "Hello world");
}


texts: Parsing Bitcoin binary data file with Python

texts:
The script parses Bitcoin database (blkXXXXX.dat) files directly from raw binary to txt human readable view. And I think about how to encrease the speed of processing.

Can anyone suggest how to improve the performance? I know that the best way to encrease performance is to write this on C or C++, but what about Python?  Also, is this style of programming is good?

Example cut from code (full code avaible here):

import os
import hashlib

def reverse(input):
    L = len(input)
    if (L % 2) != 0:
        return None
    else:
        Res = ''
        L = L // 2
        for i in range(L):
            T = input[i*2] + input[i*2+1]
            Res = T + Res
            T = ''
        return (Res);

f = open('blk01234.dat','rb')
tmpHex = ''
fSize = os.path.getsize(t)
while f.tell() != fSize:
    for j in range(4):
        b = f.read(1)
        b = b.encode('hex').upper()
        tmpHex = b + tmpHex
    tmpHex = ''
    for j in range(4):
        b = f.read(1)
        b = b.encode('hex').upper()
        tmpHex = b + tmpHex
    resList.append('Block size = ' + tmpHex)
    tmpHex = ''
    tmpPos3 = f.tell()
    while f.tell() != tmpPos3 + 80:
        b = f.read(1)
        b = b.encode('hex').upper()
        tmpHex = tmpHex + b
    tmpHex = tmpHex.decode('hex')
    tmpHex = hashlib.new('sha256', tmpHex).digest()
    tmpHex = hashlib.new('sha256', tmpHex).digest()
    tmpHex = tmpHex.encode('hex')
    tmpHex = tmpHex.upper()
    tmpHex = reverse(tmpHex)
    resList.append('SHA256 hash of the current block hash = ' + tmpHex)
    f.seek(tmpPos3,0)
    tmpHex = ''
    for j in range(4):
        b = f.read(1)
        b = b.encode('hex').upper()
        tmpHex = b + tmpHex
    resList.append('Version number = ' + tmpHex)
    tmpHex = ''
#.....next part of code
f.close()
f = open('blk01234.txt','w')
for j in resList:
    f.write(j + '\n')
f.close()


texts:
I have a list of unique strings (approx 2500000) of different lengths and I am trying to find if there is any string which occurs as a substring of previous strings.

def index_containing_substring(the_list, substring):
    for i, s in enumerate(the_list):
        if substring in s:
            return i
    return -1

def string_match():
    test_list=['foo bar abc xml','fdff gdnfgf gdkgf','foo bar','abc','xml','xyz']
    max_len=4 # I am storing the maximum length of sentence
    # the list starts with reverse order
    # i.e sentence with highest length are at the top
    safe_to_add=[]
    for s in test_list:
        if len(s)==max_len:
            safe_to_add.append(s)
        else:
            idx=index_containing_substring(safe_to_add,s)
            if idx==-1:
                safe_to_add.append(s)
            else:
                # process the substring
                print('match found <{}> for <{}>'.format(test_list[idx],s))

This method works fine but I think it is pretty slow. Is there a better way to solve this problem using a better data structure (trie or suffix tree)?

Output

match found <foo bar abc xml> for <foo bar>
match found <foo bar abc xml> for <abc>
match found <foo bar abc xml> for <xml>


texts:
A while back, I reverse-engineered a checksum algorithm from an MMO used to check the validity of an item that's linked to chat (similar to WoW). The idea is that if the checksum is invalid then the game client would ignore the link when clicked. Otherwise clicking on the item link in in-game chat would display the stat and attrib for that item.

ushort16 CreateChecksum(const string &itemlink)
{
    stringstream parseitemlink(itemlink);
    uint32 hexform[ITEMLINKGROUPCOUNT] = {0};
    uint32 hexsum = 0;

    //Parse itemLink string into hexform array
    for (int i = 0; i < ITEMLINKGROUPCOUNT; ++i)
        parseitemlink >> hex >> hexform[i];

    //sum all the itemlink group together
    for (int i = 0; i < ITEMLINKGROUPCOUNT; ++i)
        hexsum += hexform[i];

    for (int i = 0; i < ITEMLINKGROUPCOUNT; ++i)
    {
        uint32 ebx = hexform[i], edi = ebx * i;

        //if loop iteration is odd store MSB 2-bytes.
        //Otherwise, store working hexgroup as is untouched
        if (i & 0x01)
            ebx = hexform[i] >> 16; // aka same as dividing hexform[i] by 65,536

        // (hexform[i] / 65,536) + (hexform[i] * i) + hexsum -- for odd groups
        //  hexform[i] + (hexform[i] * i) + hexsum           -- for even groups
        ebx += edi + hexsum;
        hexsum = ebx ^ hexform[i];
    }

    for (int i = 0; i < ITEMLINKGROUPCOUNT; ++i)
    {
        // the more familiar high-level form would be
        // hexform[i]^2 + hexform[i] * hexsum
        uint32 ecx = (hexform[i] + 1) * hexsum,
               eax = ecx * hexform[i];

        eax >>= 16;
        eax += ecx;
        hexsum = eax ^ hexform[i];
    }

    //return the lower 2-bytes of hexsum
    //as the final checksum
    return hexsum & 0xFFFF;
}//CreateChecksum

The format of the itemlink is comprised of a group of hexadecimal separated with a space in string format. It's passed into main() as an argument when the program is run.

Here's what an itemlink's hex string might look like:

const string EXAMPLELINK = "36c6a 0 3f000a54 d0f1 0 0 0 0 0 0 20d0";

Are there any code smells or readability issues in this code segment? Can any part(s) of it be improved?


texts: Counting inversions in C++ via mergesort and vectors

texts:
I have a text file that contains 100,000 numbers from 1 ~ 100,000 in an unsorted manner (no duplicates).

The name of the file is "IntegerArray.txt"

My task is to count the number of inversions in the text file.  An inversion is a pair of elements a, b where a comes before b, but a > b.  Thus "1 2 3 6 4 5" contains two inversion (6 > 4 and 6 > 5).

I implemented it with the merge sorting method.

The following is my code:

long long mergeAndCount(vector<int>& vec, int p, int q, int r) {
    long long count = 0;

    vector<int> L, R;
    for (int i = p; i <= q; ++i) L.push_back(vec[i]);
    for (int j = q + 1; j <= r; ++j) R.push_back(vec[j]);

    L.push_back(numeric_limits<int>::max()); //sentinel element
    R.push_back(numeric_limits<int>::max());

    int i = 0, j = 0;

    for (int k = p; k <= r; ++k) {
        if (L[i] <= R[j]) {
            vec[k] = L[i];
            ++i;
        } else {
            vec[k] = R[j];
            ++j;
            if (L[i] != L.back() && R[j] != R.back())
                count += q - p + 1 - i
        }
    }
    return count;
}

long long inversion(vector<int>& vec, int p, int r) {
    long long count = 0;

    if (p < r) {
        int q = (p + r) / 2;
        count = inversion(vec, p, q);
        count += inversion(vec, q + 1, r);
        count += mergeAndCount(vec, p, q, r);
    }

    return count;
}

int main() {
    ifstream infile("IntegerArray.txt");
    int a;
    vector<int> vec;

    while (infile >> a)
        vec.push_back(a);

    cout << inversion(vec, 0, vec.size()-1);
    return 0;
}

The result from the above code is 2407905288, which is correct.

The answer by brute force with the following code is 2407905288, which is correct. The following is a brute force version (it took me more than 10 minutes to run this code):

long long inversion(vector<int>& vec, int p, int r) {
    long long count = 0;

    for (int i = 0; i < vec.size(); ++i)
        for (int j = i + 1; j < vec.size(); ++j)
            if (vec[i] > vec[j])
                ++count;

    return count;
}

Any improvements in runtime or efficiency would be much appreciated.


texts: F# wrapper to generate SHA256 signature for a file

texts:
I've created the following module to allow me to generate a SHA256 signature for a file. (In real life this is used to verify an image file hasn't been amended).  The cut down code looks like this:

open System.IO
open System.Text
open System.Security.Cryptography;

// Get the SHA256 hash of a file
let SHA256 (file:FileInfo) =
    let FileSHA256Wrap (hashFile : FileStream) (sha256Hash : SHA256)  : byte[] =
        sha256Hash.ComputeHash(hashFile)
    let FileWrap (hashFile : FileStream) : byte[] =
        using (SHA256Managed.Create()) (FileSHA256Wrap hashFile)
    using (file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) FileWrap

// Convert the byte[] version of the hash to a printable encoded HEX string
let HexEncoded (hash:byte[]) :string =
    let sb = new StringBuilder(hash.Length * 2)
    hash |> Array.map (fun c -> sb.AppendFormat("{0:X2}",c)) |> ignore
    sb.ToString()

// Get the file hash and convert it to a HEX string
let HexEncodedSHA256 (file:FileInfo) =
    file |> SHA256 |> HexEncoded

let fi = new FileInfo("somefile.tif")
HexEncodedSHA256 fi

I've two questions here, with the double using statements I find the wrap functions help me work out what is going on - but is there a neater and more succinct way to write this without making it hard to work out what is happening?

The implementation of HexEncoded uses a string builder, is there a more functional way to do this.


texts: Coin Flip Streaks - correct streak condition

texts:
This is a practice task from Automate the Boring Stuff with Python. I imagine many others have asked for their version of the solution to be checked, so I apologise beforehand  for boring you yet again.
In brief, the task entails writing a code that carries out an experiment of checking if there is a streak of 6 'heads' or 'tails' in 100 coin tosses, then replicates it 10,000 times and gives a percentage of the success rate.
import random
numberOfStreaks = 0
listOf100 = []
streak = 0

def toss():
    flip = random.randint(0, 1)
    if flip == 0:
        return 'H'
    else:
        return 'T'

for experimentNumber in range(10000):
    # Code that creates a list of 100 'heads' or 'tails' values.
    for flipCoin in range(100):
        listOf100.append(toss())

    # Code that checks if there is a streak of 6 'heads' or 'tails' in a row.
    for listItem in range(len(listOf100) - 1):
        if listOf100[listItem] == listOf100[listItem + 1]:
            streak += 1
            if streak == 5:
                numberOfStreaks += 1
                streak = 0
                break
        else:
            streak = 0
    listOf100 = []

print('Chance of streak: %s%%' % (numberOfStreaks / 10000))

My question is, am I correct in setting the condition if streak == 5?
My reasoning is that there are 5 pairs to be checked for similarities, if the actual streak is to be 6, for example:
if listOf100[0] == listOf100[1]
if listOf100[1] == listOf100[2]
if listOf100[2] == listOf100[3]
if listOf100[3] == listOf100[4]
if listOf100[4] == listOf100[5]
So, if all 5 such pairs increase streak with 1, it means that there are 6 list items in a row that are either 'heads' or 'tails'.
Thank you!


texts: Thread Safe Bank Transaction: Deposit, Withdrawal, Check Balance and Transfer in Java

texts:
I have made a class which is a thread-safe implementation supporting Deposit, Withdrawal, Check Balance Querying and Transferring of money.
I have a class Account:

public class Account {
    private int balance;
    private String address;
    private String userId;
    final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    Lock transferLock = new ReentrantLock();
    public Account(String userId){
        this.userId = userId;
    }

    public void add(int amount){
        balance += amount;
    }
    public void sub(int amount){
        this.balance -= amount;
    }
    public int getBalance(){
        return balance;
    }
}

I use a ReentrantReadWriteLock for Depositing and Withdrawing which acquires a Write Lock.
Read lock is acquired when checking an Account's balance.
A 'transferLock' is used to lock the transferring of funds from Account A to Account B.

Here are the main functions:

 public boolean deposit(String userId, int amount){
        Account account = getUserAccount(userId);
        Lock accountWriteLock = account.lock.writeLock();
        accountWriteLock.lock();

        account.add(amount);

        accountWriteLock.unlock();
        return true;
    }

    public boolean withdraw(String userId, int amount){
        Account account = getUserAccount(userId);
        Lock accountWriteLock = account.lock.writeLock();
        accountWriteLock.lock();

        if(account.getBalance() < amount){
accountWriteLock.unlock();
            return false;
        }
        account.sub(amount);

        accountWriteLock.unlock();
        return true;
    }

    public int checkBalance(String userId){
        Account account = getUserAccount(userId);
        Lock accountReadLock = account.lock.readLock();
        accountReadLock.lock();

        int balance = account.getBalance();

        accountReadLock.unlock();
        return balance;
    }

    public boolean transfer(String fromAccountUserId, int amount, String toAccountUserId) throws Exception {
        Account fromAccount = getUserAccount(fromAccountUserId);
        Account toAccount = getUserAccount(toAccountUserId);
        Random rand = new Random();
        Lock fromAccountTransferLock = fromAccount.transferLock;
        Lock toAccountTransferLock = toAccount.transferLock;
        while (true) {
            if (fromAccountTransferLock.tryLock()) {
                fromAccount.lock.writeLock();
                if (toAccountTransferLock.tryLock()) {
                    try {
                        withdraw(fromAccountUserId, amount);
                        deposit(toAccountUserId, amount);
                        break;
                    } catch (Exception e) {
                        return false;
                    } finally {
                        toAccountTransferLock.unlock();
                    }
                }
                fromAccountTransferLock.unlock();
                Thread.sleep(rand.nextInt(1001));
            }
        }
        return true;
    }

Assume that getUserAccount(String userId) retrieves the appropriate Account object.

What I Would Like Reviewed
  1. Is my code thread-safe?
  2. Any improvements you think would be good?

Notes
  1. I prevent Deadlock in Transferring from Account A to Account B by allowing the holding thread to release its lock.
  2. I prevent LiveLock in transfer(...) by sleeping the thread for a random number of milliseconds between [0,1000] ms.

EDIT:
Here is the getUserAccount() code:

public Account getUserAccount(String userId){
        return new Account(userId);
    }


texts: Split CSV file into a text file per row, with whitespace normalization

texts:
I have a CSV file that I would like to split up by row, do some whitespace processing on the string data in each row of the document column, and then output the processed data into separate TXT files in a new directory. The whitespace processing is to standardize the documents by removing newlines, carriage returns, and replacing all empty strings with " ".

The thing is, I will be doing this on corpora of 3+ million documents, so was wondering if there is a better way to do this instead of iterating through each one.

with open(csv_file) as file:
    reader = csv.reader(file, delimiter=',')
    count = -1
    for row in reader:
        row[1] = str(row[1]).replace(r'\n', '')
        row[1] = str(row[1]).replace(r'\r', '')
        if not row[1]:
            row[1] = ' '
        with open('corpus' + str(count) + '.txt', 'w') as output:
            output.write(str(row[1]))
        count += 1

Input CSV data:

document_id,document
0,"Bacon ipsum dolor amet kevin jerky sausage filet mignon landjaeger, turducken drumstick burgdoggen kielbasa frankfurter doner tongue meatloaf."
1,"Beef ribs jerky biltong fatback."
2,"Short loin capicola pastrami meatball. Brisket meatloaf jowl salami porchetta jerky hamburger t-bone meatball turkey."
3,"Cow ham strip steak pastrami venison."
4,"Landjaeger fatback pork loin pig sausage."

Output individual TXT files with contents of processed document column:

corpus_0 "Bacon ipsum dolor amet kevin jerky sausage filet mignon landjaeger, turducken drumstick burgdoggen kielbasa frankfurter doner tongue meatloaf."
corpus_1 "Beef ribs jerky biltong fatback."
corpus_2 "Short loin capicola pastrami meatball. Brisket meatloaf jowl salami porchetta jerky hamburger t-bone meatball turkey."
corpus_3 "Cow ham strip steak pastrami venison."
corpus_4 "Landjaeger fatback pork loin pig sausage."


texts: Revised: Counting subnumbers divisible by a given prime

texts:
Assume we are given a number and a prime p. The goal is to count all subnumbers of number that are divisible by p. A subnumber of number is formed of any number of consecutive digits in the decimal representation of number.
Following answers to my first question about code to solve this problem, I improved my code as follows:
from collections import Counter

number = input()
p = int(input())

ans = 0

if p != 2 and p != 5:

    res = (int(number[i:]) % p for i in range(len(number)))
    C = Counter(res)

    for c in C:
        if c == 0:
            ans += (C[c] * (C[c] + 1)) // 2
        else:
            ans += ((C[c] - 1) * C[c]) // 2

elif p == 2:
    for i in range(len(number)):
        if number[i] in ('0', '2', '4', '6', '8'):
            ans += i + 1

else:
    for i in range(len(number)):
        if number[i] in ('0', '5'):
            ans += i + 1

print(ans)

Now, it passes more tests but yet there are several tests with time limit exceeded error.
Can this new solution be made faster?


texts: Acquiring indices for anagrams of an input string

texts:
I am working on an interview question from Amazon Software:

  Design an algorithm to take a list of strings as well as a single input string, and return the indices of the list which are anagrams of the input string, disregarding special characters.

I was able to design the algorithm fine. What I did in psuedocode was:

Create an array character count of the single input string
For each string the list, construct the an array character count
Compare the character count of each string in list to single output string
If same, add it to a list that holds all the indexes of anagrams
Return that list of indices

Here is my implementation in Java (it works; I've tested it):

 public static List<Integer> indicesOfAnag(List<String> li, String comp){
    List<Integer> allAnas = new ArrayList<Integer>();
    int[] charCounts = generateCharCounts(comp);
    int listLength = li.size();
    for(int c=0;c<listLength; c++ ){
        int[] charCountComp = generateCharCounts(li.get(c));
        if(isEqualCounts(charCounts, charCountComp))
            allAnas.add(c);
    }
    return allAnas;
}
private static boolean isEqualCounts(int[] counts1, int[] counts2){
    for(int c=0;c<counts1.length;c++) {
        if(counts1[c]!=counts2[c])
            return false;
    }
    return true;
}
private static int[] generateCharCounts(String comp) {
    int[] charCounts = new int[26];
    int length = comp.length();
    for(int c=0;c<length;c++) {
        charCounts[Character.toLowerCase(comp.charAt(c)) - 'a'] ++;
    }
    return charCounts;
}

I think that this solution runs in \$O(n)\$ where n is the number of strings in the list (I'm not sure, so can someone verify?). What I am concerned about is the space complexity.  I think the space complexity is \$O(n)\$ because I am creating \$n\$ copies of the 26 length array. Is there anything that I can do to reduce the amount of space I am using? I think this space will cumulate and add up.


texts:
In general, in prestashop there are no funcions to really have the final (the one with highest level_depth) category of a product based on id_product, so I extended the Product class and added this simple static method:

public static function get_product_category($id_product, $id_lang = null){
    $lang = (!isset($id_lang)) ? (int)Context::getContext()->language->id : $id_lang;

    $db = Db::getInstance();

    $sql = 'SELECT
                    c.id_category,
                    c.id_parent,
                    cl.name,
                    cl.link_rewrite

              FROM '._DB_PREFIX_.'category_product cp
              INNER JOIN '._DB_PREFIX_.'category c ON cp.id_category = c.id_category
              INNER JOIN '._DB_PREFIX_.'category_lang cl ON cl.id_category = c.id_category
              WHERE cp.id_product = ' . bqSQL($id_product) . ' and cl.id_lang = ' . bqSQL($lang) . '
              ORDER BY c.level_depth DESC
              LIMIT 1';

    $result = $db->ExecuteS($sql);

    return $result[0];
}


texts:
Solution:

Generate Training Set

traincol1 = linspace(0.1, 15, 40)';
eps = (0.2*rand(40,1)) - 0.1;
traincol2 = sin(traincol1)./traincol1 - eps;
train = [traincol1 traincol2];
save('snn_a.txt','train');
save('snn_a.mat','train');

Generate Test Set

testcol1 = linspace(0.1, 15, 400)';
eps = (0.2*rand(400,1)) - 0.1;
testcol2 = sin(testcol1)./testcol1 - eps;
test = [testcol1 testcol2];
save('snn_b.txt','test');
save('snn_b.mat','test');

Training the Neural Network

function net = train_net(trainingset, hidden_neurons)
% Parameters:
% train_set:
% labels - y
% hidden_neurons_count:
% Return value:
% net – object representing a neural network
% initialization
% hidden neuron activation function- tanh,
% output neuron activation - linear

net=newff(trainingset(:, 1)', trainingset(:, 2)',hidden_neurons,
{'tansig', 'purelin'},'trainlm');
rand('state',sum(100*clock));      %random numbers generator initialization
net=init(net);                     %weights initialization
net.trainParam.goal = 0.01;        %stop- mse criterion
net.trainParam.epochs = 400;       %number of epochs iterations
net=train(net,trainingset(:, 1)', trainingset(:, 2)'); %network training

Main Program

% input data area
load('snn_a.mat');
load('snn_b.mat');
hidden_neurons = 4;
% net training
net = train_net(train, hidden_neurons);
% assigning results
resulttrain = net(train(:, 1)')';
resulttest = net(test(:, 1)')';
% drawing
hold on
sn = @(x) sin(x) / x;
fplot(sn, [0, 15],'g');
plot(train(:, 1), resulttrain, 'r');
legend('Original function', ' Result')
hold off
% print mse results
mse(net, train(:, 2)', resulttrain')
mse(net, test(:, 2)', resulttest')

Is this code correctly implemented?

Are there any hidden bugs?

How can it be improved?


texts: Function for formatting a timespan with optional trailing zero

texts:
I'm looking to achieve a time format that looks like this: 2d 4h remaining; or 1h 36m remaining; or 35s remaining, etc. So that it only displays the two largest values of time (this is how Clash of Clans and some other mobile games format wait times.)

I would like to format the wait time value as simply 5h or 5h 0m depending on whether I am displaying the total wait time or currently counting down. My code is below… But is there a slightly simpler way of writing it without so many returns?

(This question was originally asked here:
Is there a simpler way to format this timespan? )

public string FormatRushTime ( System.TimeSpan span, boolean removeZeros )
{
    if ( span.Days > 0 )
    {
        if ( span.Hours > 0 || !removeZeros )
            return String.Format("{0:d}d {1:d}h", span.Days, span.Hours);
        else
            return String.Format("{0:d}d", span.Days);
    }
    if ( span.Hours > 0 )
    {
        if ( span.Minutes > 0 || !removeZeros )
            return String.Format("{0:h}h {1:m}m", span.Hours, span.Minutes);
        else
            return String.Format("{0:h}h", span.Hours);
    }
    if ( span.Minutes > 0 )
    {
        if ( span.Seconds > 0 || !removeZeros )
            return String.Format("{0:m}m {1:s}s", span.Minutes, span.Seconds);
        else
            return String.Format("{0:m}m", span.Minutes);
    }
    return String.Format("{0:d}s", span.Seconds);
}


texts: Getting ready for Nullable Reference Types

texts:
Looking forward for C# Nullable Reference Types in C# 8.0. I do not like to use the preview implementation in a production code though, so just went with these simple helper classes intending them to be upgraded to new syntax by search and replace when time comes.

Usage sample:

static void Main(string[] args)
{
    var johnk = new FullName("John", "F.", "Kennedy");
    var johnd = new FullName("John", null, "Do");
    var johnn = new FullName("John", null, null); // throws
}

Where business class is:

class FullName
{
    public FullName(Some<string> first, Option<string> middle, Some<string> last) =>
        (First, Middle, Last) = (first, middle, last);

    public string First { get; }
    public string Middle { get; }
    public string Last { get; }
}

Library code:

[DebuggerStepThrough]
struct Some<T> where T : class
{
    public static implicit operator Some<T>(T value) =>
        new Some<T>(value ?? throw new ArgumentNullException());

    public static implicit operator T(Some<T> some) =>
        some.Value ?? throw new ArgumentNullException();

    Some(T value) => Value = value;
    T Value { get; }
}

And

[DebuggerStepThrough]
struct Option<T> where T : class
{
    public static implicit operator Option<T>(T value) =>
        new Option<T>(value);

    public static implicit operator T(Option<T> some) =>
        some.Value;

    Option(T value) => Value = value;
    T Value { get; }
}

Nothing fancy, just does the job and it would be easy to upgrade syntax…


texts: Find meaningful words from the input string

texts:
Given a string find the number of meaningful words which could be formed from the string
for eg. programmerit forms:

pro+gram+merit
program+merit
programmer+it
pro+grammer+it

Looking for code review optimizations and best practices. Also hoping for suggestions for complexity better than \$O(n^2)\$, where n is the number of characters.

public final class DictionaryValidWords {

    private static final Set<String> dictionary = new TreeSet<String>();
    static {
        dictionary.add("this");
        dictionary.add("his");
        dictionary.add("is");
        dictionary.add("awe");
        dictionary.add("we");
        dictionary.add("some");
        dictionary.add("awesome");
        dictionary.add("foo");
        dictionary.add("bar");
    }

    private DictionaryValidWords() {}

    /**
     * Returns set of valid words given an input string.
     * It eliminates duplicates.
     *
     * @param str   The input string whose valid words need to be found out.
     * @return      List of valid words nested in the string.
     */
    public static Set<String> findValidStrings(String str) {
        if (str.length() ==  0) {
            throw new IllegalArgumentException("Strings of length 0 are illegal");
        }

        final Set<String> validWords = new HashSet<String>();
        for (int i = 0; i < str.length(); i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = i; j < str.length(); j++) {
                sb.append(str.charAt(j)); // O(1) complexity.
                if (dictionary.contains(sb.toString())) {
                    validWords.add(sb.toString());
                }
            }
        }
        return validWords;
    }
}

public class DictionartValidWordTest {

    @Test
    public void testValidWords() {
        Set<String> expectedSet = new HashSet<String>(Arrays.asList("awe", "is", "his", "awesome", "some", "this", "we"));
        assertEquals(expectedSet, DictionaryValidWords.findValidStrings("thisisawesome"));
    }
}