texts: Closing InputStream of a running process

texts:
Let's say you want to extract the output of a console application till you've found a certain keyword. If you have found the keyword the started console process still should be running, however the function which has found the keyword should return.

Here is a minimal application which simply creates an output of n lines (n is the first argument).

LineOutput.java

public class LineOutput {
    public static void main(String[] args) {
        int iterations = 10;
        if (args.length > 0) {
            iterations = Integer.valueOf(args[0]);
        }
        for (int i=0; i < iterations; i++) {
            System.out.println("Line " + i);
        }
    }
}

And here is the main application with the readStreamUntilFound method, which returns as soon as the keyword was found:

ReadTest.java

package org.test;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

public class ReadTest {
    public static void main(String[] args) {
        System.out.println("Result " + readStreamUntilFound(Arrays.asList("java", "-jar", "test.jar", "10000"), "Line 99"));
    }

    public static boolean readStreamUntilFound(List<String> cmd, String keyword) {
        boolean keywordFound = false;
        ProcessBuilder pb = new ProcessBuilder();
        pb.command(cmd);
        pb.redirectErrorStream(true);
        Process p;
        try {
            p = pb.start();

            try {
                BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
                BufferedReader r = new BufferedReader(
                        new InputStreamReader(bis));

                String line;
                while ((line = r.readLine()) != null) {
                    System.out.println(line);
                    if (line.equals(keyword)) {
                        keywordFound = true;
                        break;
                    }
                }
            } finally {
                p.getInputStream().close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return keywordFound;
    }
}

I know that the InputStream of a started process must be read, otherwise the process might be blocked. Therefore I am wondering if it is problematic to close the InputStream although the console application still is running (especially in the case where a Java Process object is kept as reference).


texts:
Problem Description:

  Find the maximum sum of a compact subsequence of array elements after
  performing a single swap operation.

Solution:

def maxsum(lst): # Get maximum sum of all possible slices in list
    max_ending = max_slice = lst[0]
    for i in xrange(1,len(lst)):
        max_ending = max(lst[i], max_ending + lst[i])
        max_slice = max(max_slice, max_ending)
    return max_slice

def solution(A):
    msum = A[0]
    for i in xrange(0, len(A)-1):
        for j in xrange(i+1, len(A)):
            A[i], A[j] = A[j], A[i] # swap
            msum = max(maxsum(A),msum)
            A[i], A[j] = A[j], A[i] # swap back
    return msum

I am swapping all possible pairs in the list to get the maximum sum after a particular swap and then the maximum of all those maximum sums. Given the \$O(N^3)\$ complexity, it times out for larger sequences/values. Is there a better way to implement this solution? Codility says \$O(N)\$ is possible.


texts:
I need to generate list of all allowable test combination values of of actor, action and subject

{
 'actor': ['man', 'woman', 'baby'],
 'action': ['play', 'cry'],
 'subject': ['mathematica', 'lingvo']
}

I get itertools.produce and apply restriction that actor=man can't coexist with action and actor=baby can't coexist with subject

import itertools
from pprint import pprint

data = {'actor': ['man', 'woman', 'baby'], 'action': ['play', 'cry'], 'subject': ['mathematica', 'lingvo']}

def set_keys(*x):
    return tuple(zip(data.keys(), x))

def reduce(*x):
    dict_x = dict(x)
    if dict_x['actor'] == 'man':
        del dict_x['action']
    elif dict_x['actor'] == 'baby':
        del dict_x['subject']

    return tuple(dict_x.items())

def distict(*x):
    return dict(x[0])

product = itertools.product(*data.values())
product_with_keys = itertools.starmap(set_keys, product)

print('product_with_keys')
# pprint(list(product_with_keys))

reduced_product_with_keys = itertools.starmap(reduce, product_with_keys)
print('reduced_product_with_keys')
# pprint(list(reduced_product_with_keys))

grouped = itertools.groupby(reduced_product_with_keys)
# pprint(dict(grouped))

distinct = itertools.starmap(distict, grouped)
pprint(list(distinct))

Here is a result that suits me:

[{'actor': 'man', 'subject': 'mathematica'},
{'actor': 'man', 'subject': 'lingvo'},
{'actor': 'man', 'subject': 'mathematica'},
{'actor': 'man', 'subject': 'lingvo'},
{'action': 'play', 'actor': 'woman', 'subject': 'mathematica'},
{'action': 'play', 'actor': 'woman', 'subject': 'lingvo'},
{'action': 'cry', 'actor': 'woman', 'subject': 'mathematica'},
{'action': 'cry', 'actor': 'woman', 'subject': 'lingvo'},
{'action': 'play', 'actor': 'baby'},
{'action': 'cry', 'actor': 'baby'}]

I am not very happy with how solved the removal of identical records


texts: Model structure for Player Team and Match in football application

texts:
I'm creating an application for foosball matches.

I have models like below:

class Player(models.Model):
    match_amount = models.IntegerField(default=0)
    wins = models.IntegerField(default=0)
    avatar = models.ImageField(blank=True)
    user = models.OneToOneField(
        on_delete=models.CASCADE,
        to=User,
        primary_key=True,
        related_name='player',
        verbose_name=_('user'),
    )

    def __str__(self):
        return self.user.get_full_name()

class Team(models.Model):
    players = models.ManyToManyField(Player)
    wins = models.IntegerField(default=0)

    def __str__(self):
        return "Team %s" % self.pk

class Match(models.Model):
    date = models.DateField(default=now)

    def __str__(self):
        return "Match on %s" % self.date

class TeamMatch(models.Model):
    team = models.ForeignKey(Team)
    match = models.ForeignKey(Match)

    points = models.IntegerField()

    def __str__(self):
        return "Match %s" % self.team

Is these models are well created?

Thanks much for each tip and corrections.


texts: Clone and replace attributes that are instances of a specific class

texts:
For a given object that may be an instance of a class, a built-in container or type, I would like to copy that object, but replace all instances of a given class with something else.  I can do this with two calls to deepcopy as shown below, but there may be a more straightforward approach.

Create some complex nested object:

class T(object):
    pass

class A(object):
    def __init__(self):
        self.x = 10
        self.t1 = T()

class B(object):
    def __init__(self):
        self.a = A()
        self.y = 20
        self.t2 = T()

b = B()

Get a mapping from ids to objects:

visited = {}
copy.deepcopy(b, visited)

Create a custom dict type to replace instances of T with 100:

import collections

class Replacer(collections.MutableMapping):
    def __init__(self, idmap):
        self.store = dict()
        self.idmap = idmap
    def __getitem__(self, key):
        if isinstance(self.idmap[key], T):
            return 100
        return self.store[key]
    def __setitem__(self, key, value):
        self.store[key] = value
    def __delitem__(self, key):
        del self.store[key]
    def __iter__(self):
        return iter(self.store)
    def __len__(self):
        return len(self.store)

Copy and replace all T instances:

bb = copy.deepcopy(b, Replacer(visited))

In [121]: bb.t2
Out[121]: 100

In [122]: bb.a.t1
Out[122]: 100


texts: Efficient and fast way to send data from Android to server

texts:
I have an app that will be sending images ranging from few KB to ~20MB and I need to write a code that will do that in the fastest and most efficient way. I currently have a code that does this, but I fear that it's inefficient and slow:

// Read bitmap from file
Bitmap bitmap = null;
Uri uri = Uri.fromFile(new File("camera/myfile.jpg"));
InputStream stream = null;

try {
    stream = getContentResolver().openInputStream(uri);
    BitmapFactory.Options options = new BitmapFactory.Options();
    bitmap = BitmapFactory.decodeStream(stream, null, options);
} catch (IOException e) {
    Log.e(TAG, e.getMessage(),e);
    return null;
} finally {
    try {
        if (stream != null) stream.close();
    } catch (Exception e) {}
}

// Send image data to server
ByteArrayOutputStream byteStream = null;

try {
    // Create HTTP objects
    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicHttpParams hparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(hparams,10*1000);
    httpClient.setParams(hparams);
    HttpPost httpPost = new HttpPost(my_servers_url);

    byteStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteStream);

    // Convert ByteArrayOutputStream to byte array. Close stream.
    byte[] byteArray = byteStream.toByteArray();
    byteStream.close();
    byteStream = null;

    // Send HTTP Post request
    httpPost.setEntity(new ByteArrayEntity(byteArray));
    String response = EntityUtils.toString(httpClient.execute(httpPost).getEntity(), HTTP.UTF_8);

} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (byteStream != null) byteStream.close();
    } catch (Exception e) {}
}

My concern is that the entirety of the image is loaded into a byte array on the device before being sent to the server. Although this code works, it is slower than what I'm satisfied with.

Can this code be faster and more efficient? Would it be better to use HttpURLConnection instead? If so, how would I write the code?


texts:
I've created the following program to assist me in some template stuff I'm working on.

The function get_type returns 0, 1, 2, 3 or nullopt corresponding to which group the argument T belongs to.

This is my first template style project, so I'm looking for any critique possible. (Note the functions are marked static intentionally, as this will only be used inside this particular file, and should not be visible to users.)

namespace ae
{
    namespace details
    {
        template <class T>
        [[nodiscard]]
        static inline constexpr auto is_integer() noexcept
        {
            return std::is_same_v<T, short>
                || std::is_same_v<T, int>
                || std::is_same_v<T, long>
                || std::is_same_v<T, long long>
                || std::is_same_v<T, unsigned short>
                || std::is_same_v<T, unsigned int>
                || std::is_same_v<T, unsigned long>
                || std::is_same_v<T, unsigned long long>;
        }

        template <class T>
        [[nodiscard]]
        static inline constexpr auto is_floating_point() noexcept
        {
            return std::is_same_v<T, float>
                || std::is_same_v<T, double>
                || std::is_same_v<T, long double>;
        }

        template <class T>
        [[nodiscard]]
        static inline constexpr auto is_charachter() noexcept
        {
            return std::is_same_v<T, char>
                || std::is_same_v<T, unsigned char>
                || std::is_same_v<T, wchar_t>;
        }

        template <class T>
        [[nodiscard]]
        static inline constexpr auto is_boolean() noexcept
        {
            return std::is_same_v<T, bool>;
        }

        // Returns 0 for integer, 1 for floating_point,
        // 2 for charachter, 3 for boolean, and nullopt otherwise
        template <class T>
        [[nodiscard]]
        static inline constexpr auto get_type() noexcept
        {
            if constexpr (is_integer<T>())
                return std::optional<unsigned int>(0u);
            else if constexpr (is_floating_point<T>())
                return std::optional<unsigned int>(1u);
            else if constexpr (is_charachter<T>())
                return std::optional<unsigned int>(2u);
            else if constexpr (is_boolean<T>())
                return std::optional<unsigned int>(3u);
            else return std::nullopt;
        }
    }
}

Example usage

template <typename T>
static typename std::enable_if<ae::details::is_integer<T>(), T>::type test()
{
    // Do something if T is integer
}

template <typename T>
static typename std::enable_if<ae::details::is_charachter<T>(), T>::type test()
{
    // Do something if T is charachter
}

int main()
{
    test<int>(); //..

    return 0;
}


texts:
I have a personal website that's used primarily for fun. I upload images, videos and text that I want to share. An HTML submission form accepts questions and string submissions from users, which uses a phpmyadmin database table for storage.
The below snippet is my current .htaccess file. https://gtmetrix.com/ notes that redirects are the largest culprit in slowing down my page loads, but I'm unsure of how to streamline them.
RewriteEngine On

#REDIRECT TO SECURE HTTPS CONNECTION
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www.MYDOMAIN.com [NC]
RewriteRule ^(.*)$ https://MYDOMAIN.com/$1 [L,R=301]

#URL EXTENSION REMOVAL
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

#HOTLINKING PROTECTION
    #NOTE: having |html| and |htm| included prevented access of the site through browser search, so i removed them.
RewriteCond %{HTTP_REFERER} !^https://(www\.)?MYDOMAIN\.com(/.*)*$ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(css|flv|gif|ico|jpe|jpeg|jpg|js|mp3|mp4|php|png|pdf|swf|txt)$ - [F]

#CONTENT SECURITY POLICY
<FilesMatch "\.(html|php)$">
    Header set Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: 'unsafe-inline'; media-src 'self' data: 'unsafe-inline'; connect-src 'self';"
</FilesMatch>

#REDIRECT FOR DATE PAGE
Redirect /date /storage/date-202010

#REDIRECT FOR HOME PAGE
Redirect /home /

#CUSTOM ERROR PAGES
ErrorDocument 400 /allerror.php
ErrorDocument 401 /allerror.php
ErrorDocument 403 /allerror.php
ErrorDocument 404 /allerror.php
ErrorDocument 405 /allerror.php
ErrorDocument 408 /allerror.php
ErrorDocument 500 /allerror.php
ErrorDocument 502 /allerror.php
ErrorDocument 504 /allerror.php

#PREVENT DIRECTORY BROWSING
Options All -Indexes

#FILE CACHING
    #cache html and htm files for one day
<FilesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=43200"
</FilesMatch>
    #cache css, javascript and text files for one week
<FilesMatch "\.(js|css|txt)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>
    #cache flash and images for one month
<FilesMatch "\.(flv|swf|ico|gif|jpg|jpeg|mp4|png)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>
    #disable cache for script files
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>

#BLOCKS FILE TYPES FOR USERS
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|inc|bak)$">
Order Allow,Deny
Deny from all
</FilesMatch>

UPDATE
I have created a new post integrating an HSTS and many of the changes that were recommended by Mr. White. The bounty has been awarded. Please direct any further feedback to the New Post.


texts: Calculate the cost of cement for a project

texts:
I am a newbie in a programming, and I just randomly chose a task for training from some group on Facebook. The task is to calculate the cost of cement for a construction project. The input is the number of pounds of cement required (guaranteed not to be a multiple of 120). The store sells cement in 120-pound bags, each costing $45.

Example input: 295.8
Output: 135

#include <stdio.h>
#include <stdlib.h>

#define PRICE 45
#define CAPACITY 120
#define MAXDIGITS 5

int sum(int);

int main(int argc, char *argv[])
{
    int val = 0;
    char inp[MAXDIGITS];

    if ((argc > 1) && (argv[1] > 0))
        val = strtol(argv[1], NULL, 0);
    else
    {
        do
        {
            printf("Please input the value of cement: ");
            scanf("%s", inp);
            val = strtol(inp, NULL, 0);
        }
        while (!val);
    }

    if (val)
        printf("Money you need: %d\n", sum(val));

    return 0;
}

int sum(int need)
{
    int mon = PRICE;
    int n = CAPACITY;

    while (n < need)
    {
        n += CAPACITY;
        mon += PRICE;
    }

    return mon;
}

I'm interested in code style, rational memory usage, etc.


texts: Implementation of a Fraction class in Java

texts:
I am writing a bunch of Math related classes:BigInteger,Fraction,matrix,vector,polynomial,set etc.All of these classes will use each other.The classes will either work in decimal format or in Rational format at a time(eg as FractionalMatrix and DecimalMatrix) so I thought it will be best to implement the Fraction class first.

My primary concern is that this is going to be a big project.So, code readability and management is very important.Any suggestions on making the code better are appreciated.

Here is the Fraction class:

public final class Fraction {

private int numerator;

private int denominator;

public Fraction(int numerator,int denominator,boolean wantToReduce) {
    if (denominator == 0) {
        throw new IllegalArgumentException("The denominator is zero.");
    }
    if(numerator==0){
        this.numerator = 0;
        this.denominator = 1;
    }
    else{
    this.numerator = numerator;
    this.denominator = denominator;
    }
    if(denominator<0){
        this.numerator = -1*this.numerator;
        this.denominator = -1*this.denominator;
    }
    if(wantToReduce==true)
        this.reduce();
}
public Fraction(int num) {
    this.numerator = num;
    this.denominator = 1;
}

@Override
public String toString() {
    if(denominator!=1)
    return numerator+"/"+denominator;
    else
        return numerator+"";
}

@Override
public boolean equals(Object obj) {
    if(!(obj instanceof Fraction))
        return false;
    Fraction f = ((Fraction)obj);
    int gcd= Math2.gcd(numerator,denominator);
    f.reduce();
    if(this.numerator/gcd==f.numerator && this.denominator/gcd == f.denominator)
        return true;
    else
        return false;
}

public Fraction reduce(){
    int gcd = Math2.gcd(numerator,denominator);
    numerator = numerator/gcd;
    denominator = denominator/gcd;
    return this;
}

//Cannot decide weather to make static methods or not so I randomly picked one.
public static Fraction add(Fraction f1,Fraction f2,boolean w){
    return new Fraction(f1.numerator*f2.denominator+f2.numerator*f1.denominator,f1.denominator*f2.denominator,w);
}
public static Fraction sub(Fraction f1,Fraction f2,boolean w){
    return new Fraction(f1.numerator*f2.denominator-f2.numerator*f1.denominator,f1.denominator*f2.denominator,w);
}
public static Fraction mul(Fraction f1,Fraction f2,boolean w){
    return new Fraction(f1.numerator*f2.numerator,f1.denominator*f2.denominator,w);
}
public static Fraction div(Fraction f1,Fraction f2,boolean w){
    return new Fraction(f1.numerator*f2.denominator,f1.denominator*f2.numerator,w);
}

}

Here is the Math2.gcd method, I have used The Euclidean Algorithm for finding the GCD.

 public static int gcd(int a,int b){
    if(a<0)
        a=-1*a;
    if(b<0)
        b=-1*b;
    int t;
    while(b!=0){
        t=b;
        b = a%b;
        a = t;
    }
    return a;
}


texts: Return Data and Update Row without Multiple Lookups?

texts:
I have a stored procedure that looks up an article based on the article's title. But I also need to increment a column in the same table that counts the number of times the article has been viewed.

Trying to be as efficient as possible, I wanted a way to do this without performing multiple lookups. Someone pointed out the newer OUTPUT clause, which I've used below.

I'm just wondering if I'm using it in the most efficient way, if I really made it faster, and if there are any other optimizations that could be employed.

DECLARE @Slug VARCHAR(250) -- Stored procedure argument

-- declare @UpdatedArticle table variable
DECLARE @UpdatedArticle TABLE
(
 ArtID INT,
 ArtUserID UNIQUEIDENTIFIER,
 ArtSubcategoryID INT,
 ArtTitle VARCHAR(250),
 ArtHtml VARCHAR(MAX),
 ArtDescription VARCHAR(350),
 ArtKeywords VARCHAR(250),
 ArtLicenseID VARCHAR(10),
 ArtViews BIGINT,
 ArtCreated DATETIME2(7),
 ArtUpdated DATETIME2(7)
);

UPDATE Article
 SET ArtViews = ArtViews + 1
OUTPUT
 INSERTED.ArtID,
 INSERTED.ArtUserID,
 inserted.ArtSubcategoryID,
 INSERTED.ArtTitle,
 INSERTED.ArtHtml,
 INSERTED.ArtDescription,
 INSERTED.ArtKeywords,
 INSERTED.ArtLicenseID,
 INSERTED.ArtViews,
 INSERTED.ArtUpdated,
 INSERTED.ArtCreated
INTO @UpdatedArticle
WHERE ArtSlugHash = CHECKSUM(@Slug) AND ArtSlug = @Slug AND ArtApproved = 1

SELECT a.ArtID, a.ArtUserID, a.ArtTitle, a.ArtHtml, a.ArtDescription, a.ArtKeywords, a.ArtLicenseID,
 l.licTitle, a.ArtViews, a.ArtCreated, a.ArtUpdated, s.SubID, s.SubTitle, c.CatID, c.CatTitle,
 sec.SecID, sec.SecTitle, u.UsrDisplayName AS UserName
 FROM @UpdatedArticle a
 INNER JOIN Subcategory s ON a.ArtSubcategoryID = s.SubID
 INNER JOIN Category c ON s.SubCatID = c.CatID
 INNER JOIN [Section] sec ON c.CatSectionID = sec.SecID
 INNER JOIN [User] u ON a.ArtUserID = u.UsrID
 INNER JOIN License l ON a.ArtLicenseID = l.LicID

This is used in an ASP.NET application using SQL Server 2008.


texts: Evaluating a tic-tac-toe board using a C-style for loop in Rust

texts:
I program in C, and it's my favourite language. I've recently found Rust. I like their ideas. Sometimes looks like a weird mixture of C++ and Haskell, but overall it looks nice.

The for loop in C is very flexible, and I truly miss them in Rust. Just look at my messy beginner Rust code below. Below that there is the equivalent C version, which (hopefully) doesn't look 'that' bad. I put the C version because I know my Rust code is unreadable; you need to look at C to understand why I wrote that mess. Tell me how to make my Rust code better. It doesn't have to copy all the C patterns, but there really needs to be something to compensate the lack of the flexible for loop.

If you're interested in what the whatever my code does. It determines the result of a tic-tac-toe board.

#![feature(libc)]

extern crate libc;

const SIZE: usize = 3;
const SIZE_2: usize = SIZE * SIZE;

fn determine_result(board: &[i32; SIZE_2]) -> i32 {
  'out: loop {
    let mut i = 0;
    'a: while i < SIZE_2 {
      if board[i] == 0 {
        i += SIZE;
        continue;
      }
      for j in i + 1 .. i + SIZE {
        if board[i] != board[j] {
          i += SIZE;
          continue 'a;
        }
      }
      return board[i];
    }
    'b: for i in 0 .. SIZE {
      if board[i] == 0 {
        continue;
      }
      let mut j = i + SIZE;
      while j < i + SIZE_2 {
        if board[i] != board[j] {
          continue 'b;
        }
        j += SIZE;
      }
      return board[i];
    }
    i = SIZE + 1;
    while i < SIZE_2 {
      if board[i] != board[0] {
        break 'out;
      }
      i += SIZE + 1;
    }
    return board[0];
  }
  let mut i = SIZE * 2 - 2;
  while i <= SIZE_2 - SIZE {
    if board[i] != board[SIZE - 1] {
      return 0;
    }
    i += SIZE - 1;
  }
  return board[SIZE - 1];
}

const N: usize = 50000000;

fn main() {
  unsafe {
    libc::srand(0);
  }
  let mut n = 0 as usize;
  let mut board: [i32; SIZE_2] = [0; SIZE_2];
  for i in 0 .. N {
    for i in 0 .. SIZE_2 {
      unsafe {
        board[i] = libc::rand() as i32 % 3;
      }
    }
    n += determine_result(&board) as usize;
  }
  println!("{}", n);
}

#include <stdio.h>
#include <stdlib.h>

#define SIZE 3
#define SIZE_2 (SIZE * SIZE)

static int determineResult(int board[static SIZE_2]) {
  for (int i = 0; i < SIZE_2; i += SIZE) {
    if (!board[i]) {
      continue;
    }
    for (int j = i + 1; j < i + SIZE; ++j) {
      if (board[i] != board[j]) {
        goto next;
      }
    }
    return board[i];
  next:;
  }
  for (int i = 0; i < SIZE; ++i) {
    if (!board[i]) {
      continue;
    }
    for (int j = i + SIZE; j < i + SIZE_2; j += SIZE) {
      if (board[i] != board[j]) {
        goto next2;
      }
    }
    return board[i];
  next2:;
  }
  for (int i = SIZE + 1; i < SIZE_2; i += SIZE + 1) {
    if (board[i] != *board) {
      goto next3;
    }
  }
  return *board;
next3:
  for (int i = SIZE * 2 - 2; i <= SIZE_2 - SIZE; i += SIZE - 1) {
    if (board[i] != board[SIZE - 1]) {
      return 0;
    }
  }
  return board[SIZE - 1];
}

#define N 100000000

int main(void) {
  srand(0);
  size_t n = 0;
  for (long i = 0; i < N; ++i) {
    int board[SIZE_2];
    for (int i = 0; i < SIZE_2; ++i) {
      board[i] = rand() % 3;
    }
    n += determineResult(board);
  }
  printf("%zu\n", n);
  return EXIT_SUCCESS;
}


texts:
For a WordPress login form I have written a small plugin. It adds a checkbox with a unique name to the form and if that name is not present in the login POST request it just dies.

The idea is preventing scripted attacks made for regular WordPress login forms.

The PHP code is okay (imho), but I think the JavaScript code looks rather … inelegant. Everything works as expected, it is just not beautiful. What could I improve?

<?php  # -*- coding: utf-8 -*-
/**
 * Plugin Name: T5 Unique Log-in Field
 * Description: Adds a checkbox with a unique name to the login form to prevent scripted log-in attempts.
 * Plugin URI:
 * Version:     2013.04.14
 * Author:      Thomas Scholz
 * Author URI:  http://toscho.de
 * Licence:     MIT
 * License URI: http://opensource.org/licenses/MIT
 */

add_action( 'login_init',   't5_unique_login_field' );
add_action( 'login_footer', 't5_unique_login_field' );

/**
 * Add a checkbox with a unique name to the login form.
 *
 * @wp-hook login_init
 * @wp-hook login_footer
 * @return  void
 */
function t5_unique_login_field()
{
    if ( ! empty ( $GLOBALS['interim_login'] ) )
        return;

    if ( defined( 'LOGGED_IN_SALT' ) )
        $salt = constant( 'LOGGED_IN_SALT' );
    else
        $salt = filemtime( __FILE__ );

    $unique = md5( $_SERVER[ 'HTTP_HOST' ] . $salt );

    if ( 'POST' === $_SERVER[ 'REQUEST_METHOD' ] )
    {
        if ( ! isset ( $_POST[ 'log' ] ) )
            return;

        if ( empty ( $_POST[ $unique ] )
            or 'on' !== strtolower( $_POST[ $unique ] )
        )
            exit;

        return;
    }

    ?>
<script>
var unique    = '<?php echo $unique; ?>',
    checkBox  = document.createElement( 'input' ),
    paragraph = document.createElement( 'p' ),
    label     = document.createElement( 'label' ),
    labelText = document.createTextNode( ' I am human' );

checkBox.setAttribute( 'name', unique );
checkBox.setAttribute( 'type', 'checkbox' );
checkBox.setAttribute( 'id',   unique + '_id' );

label.setAttribute( 'for', unique + '_id' );
label.appendChild( checkBox );
label.appendChild( labelText );

paragraph.appendChild( label );
paragraph.setAttribute( 'style', 'clear:both;float:none' );
// get the same font style as the last checkbox
paragraph.setAttribute( 'class', 'forgetmenot' );

document.getElementById( 'loginform' ).appendChild( paragraph );
</script>
<?php
}

Screenshots:

Before plugin activation

After plugin activation


texts:
I need to validate whether my regex is correct for below scenario. Suggestion's if the regex is correct:

Wiki Link Local_part

The local-part of the email address may use any of these ASCII characters.[4] RFC 6531 permits Unicode characters beyond the ASCII range:

Uppercase and lowercase English letters (a–z, A–Z) (ASCII: 65–90,
97–122)
Digits 0 to 9 (ASCII: 48–57)
These special characters: ! # $ % & ' * + - / = ? ^ _ { | } ~
(limited support)
Character . (dot, period, full stop) (ASCII: 46) provided that it is
not the first or last character, and provided also that it does not
appear two or more times consecutively (e.g. John..Doe@example.com
is not allowed).
Special characters are allowed with restrictions. They are:
Comments are allowed with parentheses at either end of the local
part; e.g. "john.smith(comment)@example.com" and
"(comment)john.smith@example.com" are both equivalent to
"john.smith@example.com".
International characters above U+007F are permitted by RFC 6531,
though mail systems may restrict which characters to use when
assigning local parts.

The Regex:

^[a-z0-9][-a-z0-9.!#$%&'*+-=?^_`{|}~\/]+@([-a-z0-9]+\.)+[a-z]{2,5}$

Demo Here


texts:
I wrote a basic binary tree in JS. Can anyone give me some feedback about my code?

I just want to know if this is the right approach, and how I can improve the tree. I am new to JavaScript and data structures.

function bst() {
    this.root = null;
}

bst.prototype.insert = function( obj ){

    if ( this.root == null ){
        this.root = new node(obj);
    }
    else if (this.root.value > obj){
         if (this.root.left != null ){
            this.root.left.insert( obj );
        }
        else {
            this.root.left = new node(obj);
        }
    }
    else if (this.root.value < obj){
        if (this.root.right != null ){
            this.root.right.insert( obj );
        }
        else {
            this.root.right = new node(obj);
        }
    }
}

    function node( obj ){

   this.left = null;
    this.right = null;
    this.value = obj;

    }

node.prototype.insert = function( obj ){

if (this.value > obj){

    if (this.left != null){
        this.left.insert( obj )
    }
    else{
        this.left = new node(obj);
    }
}

else if (this.value < obj){

    if (this.right != null){
        this.right.insert( obj )
    }
    else{
        this.right = new node(obj);
    }
}
//elase duplicated key value
else{
    console.log("duplicated bst key")
}

}

var bst = new bst();
bst.insert(25);
bst.insert(75);
bst.insert(12);
bst.insert(37);
bst.insert(87);
bst.insert(63);

console.log(bst.root.value);
console.log(bst.root.left.value);
console.log(bst.root.right.value);
console.log(bst.root.right.left.value);
console.log(bst.root.right.right.value);
console.log(bst.root.right.left.right.value);


texts:
Assume the following situation: you have an object that can store any object based on a key (basically, IDictionary<string, object>). You want to store objects of various types into it that are not directly related. (For example, the dictionary can be an ASP.NET Session, or it can represent a dictionary that will be serialized to disk for persistent storage.)

I don't want to create a single class that will contain all those objects, because they are not directly related, they come from different places. But if you store each object separately, it means you have to use casts when getting some value and there is no type-check when you're setting it.

To solve this, I created a generic type that encapsulates the key along with the associated type and a couple of extension methods that use it:

class TypedKey<T>
{
    public string Name { get; private set; }

    public TypedKey(string name)
    {
        Name = name;
    }
}

static class DictionaryExtensions
{
    public static T Get<T>(this IDictionary<string, object> dictionary, TypedKey<T> key)
    {
        return (T)dictionary[key.Name];
    }

    public static void Set<T>(this IDictionary<string, object> dictionary, TypedKey<T> key, T value)
    {
        dictionary[key.Name] = value;
    }
}

Usage:

private static readonly TypedKey<int> AgeKey = new TypedKey<int>("age");

…

dictionary.Get(AgeKey) > 18
dictionary.Set(AgeKey, age)

This has the type-safety (both on get and set) of using a property, while being backed by a dictionary that can store anything.

What do you think about this pattern?


texts: Using MOQ in unit-testing for a shipping calculator

texts:
I am fairly new to writing unit tests, and I was wondering if this approach I have taken is on the right track?

Given the following interfaces/classes:

public interface ILoggingService
{
    void Log(string message);
}

public interface IShoppingCart
{
    IList<IShoppingCartItem> Items { get; }
}

public interface IShoppingCartItem
{
    string Sku { get; set; }
    string Name { get; set; }
    string Description { get; set; }
    decimal Price { get; set; }
    int Quantity { get; set; }
}

public interface IShippingCalculator
{
    decimal Calculate();
}

public class ShoppingCartItem : IShoppingCartItem
{
    public string Sku { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
}

public class ShippingCalculator : IShippingCalculator
{
    private readonly ILoggingService loggingService;
    private readonly IShoppingCart shoppingCart;

    public ShippingCalculator(IShoppingCart shoppingCart, ILoggingService loggingService)
    {
        this.shoppingCart = shoppingCart;
        this.loggingService = loggingService;
    }

    public decimal Calculate()
    {
        if (shoppingCart.Items.Count == 0)
            return 0;

        var pricePerItem = 3;

        return shoppingCart.Items.Sum(x => x.Quantity * pricePerItem);
    }
}

Given the requirements of:

  The Shipping Calculator must calculate shipping at the rate of $3.00 per item.

Does this unit test look correct?

public class ShippingCalculatorTests
    {
        [Fact]
        public void Test1()
        {
            //Arrange
            var cart = new Mock<IShoppingCart>();
            cart.Setup(m => m.Items).Returns(
                new List<IShoppingCartItem>() {
                    new ShoppingCartItem() { Quantity = 5 },
                    new ShoppingCartItem() { Quantity = 3 }
                }
            );

            var logger = new Mock<ILoggingService>();

            var calc = new ShippingCalculator(cart.Object, logger.Object);

            //Act
            var result = calc.Calculate();

            //Assert
            Assert.Equal(24, result);
        }
    }


texts: Calculates the Average Score of Given Number of Scores in C

texts:
I have started with C and I made this code and as the title suggests this program can calculate the average score of a given number of scores. Now my major concern is, is it more efficient to get the number of scores as a Command Line Argument or is the current approach better incase if sometime in the future someone designs a Interactive Front-End for it?
Also I am using the cs50 library I am not sure if it is allowed here please tell me if it's not so I'll keep that in mind in the future.
#include <cs50.h>
#include <stdio.h>
float average(int length, int array[]);

int main(void)

{
    int i, j;
    printf("This Program will Help you Compute the Average Score \n");         //Welcome Message
    int Total = get_int("How Many Scores do you wish to Use: ");               //Asks User for How Many Scores
    int scores[Total];                                                         //Stores Scores in an Array
    for (i=0; i < Total; i++)                                                  //A Loop to keep Asking for Scores
    {
        scores[i]=get_int("Enter Score %d \n", i+1);                           //i+1 is used as it would be better to start asking from Score 1 so that it avoids confusion
    }
    printf("The Average score is %f", average(Total, scores));
}

float average(int length, int array[])
  {  int sum = 0;
    for (int j=0; j < length; j++)
    {
        sum += array[j];
    }
    return sum/(float)length;
  }


texts: REST call helper function returns empty response on timeout errors

texts:
Please review my code where I want to handle the timeout errors and send parsed JSON response if any. There are times when a POST request does not ALWAYS return JSON code.

def use_service(branch: str, relative_url: str, request_type: str = 'GET', data=None, retry=1):
    """
    :param – relative_url – the relative url to be submitted
    :param – request_type – the type of request being submitted (POST, GET, PUT, etc.)
    :param – data – the data to be submitted with the request if necessary.
    """
    logger.info(f'getting data from {relative_url}')
    url = envs.get(branch, '') + relative_url
    resp = {}
    status = False

    for x in range(retry):
        try:
            if request_type == 'GET':
                print(f'GET call to {url}')
                resp = requests.get(url)
            elif request_type == "POST":
                print(f'POST call to {url}')
                if branch in envs.keys():
                    resp = requests.post(
                        url,
                        json=data,
                    )
                else:
                    print(f'{branch} : Attempted to push data: {data}')
            status = resp.ok
            if resp.ok:
                resp = resp.json()
                print(f'{resp}')
            else:
                resp.raise_for_status()
        except HTTPError as err:
            logger.exception(f'HTTP Error: {err}')
        except Timeout as err:
            logger.exception(f'Connection timed out {err}')
        except ConnectionError:
            logger.exception(f'A network problem has occured (DNS failure, refused connection)')
        except RequestException as err:
            logger.exception(f'Other error occurred: {err}')
        except Exception as err:
            logger.exception(f'Unknown Exception: {err}')

    if not status:
        resp = []

    return resp


texts: Scraping names of directors from a website

texts:
I am scraping the names of the directors from a website using Python / ScraPy.  I am very new to coding (under a year and after work) - any views would be appreciated.

The reason I have a for loop with count from 0 to 100 is that not all the names on the website have a date of birth, and hence where there are blanks I need to return a value ("n/a" in this case) otherwise the lists of names / namerefs / roles / dateofbirths will get out of order.

import scrapy
import re

from CompaniesHouse.items import CompanieshouseItem

class CompaniesHouseSpider(scrapy.Spider):
    name = "companieshouse"
    allowed_domains = ["companieshouse.gov.uk"]
    start_urls = ["https://beta.companieshouse.gov.uk/company/OC361003/officers",
]

    def parse(self, response):
        for count in range(0,100):
            for sel in response.xpath('//*[@id="content-container"]'):
                companys = sel.xpath('//*[@id="company-name"]/text()').extract()
                companys = [company.strip() for company in companys]
                string1 = "officer-name-" + str(count)
                names = sel.xpath('//*[@id="%s"]/a/text()' %string1).extract()
                names = [name.strip() for name in names]
                namerefs = sel.xpath('//*[@id="%s"]/a/@href' %string1).re(r'(?<=/officers/).*?(?=/appointments)')
                namerefs = [nameref.strip() for nameref in namerefs]
                string2 = "officer-role-" + str(count)
                roles = sel.xpath('//*[@id="%s"]/text()' %string2).extract()
                roles = [role.strip() for role in roles]
                string3 = "officer-date-of-birth-" + str(count)
                if sel.xpath('//*[@id="%s"]/text()' %string3):
                    dateofbirths = sel.xpath('//*[@id="%s"]/text()' %string3).extract()
                else:
                    dateofbirths = ["n/a"]
                dateofbirths = [dateofbirth.strip() for dateofbirth in dateofbirths]
                result = zip(companys, names, namerefs, roles, dateofbirths)
                for company, name, nameref, role, dateofbirth in result:
                   item = CompanieshouseItem()
                   item['company'] = company
                   item['name'] = name
                   item['nameref'] = "'" + nameref
                   item['role'] = role
                   item['dateofbirth'] = dateofbirth
                   yield item

        next_page = response.xpath('//*[@class="pager"]/li/a[@class="page"][contains(., "Next")]/@href').extract()
        if next_page:
            next_href = next_page[0]
            next_page_url = "https://beta.companieshouse.gov.uk" + next_href
            request = scrapy.Request(url=next_page_url)
            yield request


texts:
I just answered the question on project euler about finding circular primes below 1 million using python. My solution is below. I was able to reduce the running time of the solution from 9 seconds to about 3 seconds. I would like to see what else can be done to the code to reduce its running time further. This is strictly for educational purposes and for fun.

import math
import time

def getPrimes(n):
    """returns set of all primes below n"""
    non_primes = [j for j in range(4, n, 2)] # 2 covers all even numbers
    for i in range(3, n, 2):
        non_primes.extend([j for j in range(i*2, n, i)])
    return set([i for i in range(2, n)]) - set(non_primes)

def getCircularPrimes(n):
    primes = getPrimes(n)
    is_circ = []
    for prime in primes:

        prime_str = str(prime)
        iter_count = len(prime_str) - 1

        rotated_num = []
        while iter_count > 0:
            prime_str = prime_str[1:] + prime_str[:1]
            rotated_num.append(int(prime_str))
            iter_count -= 1

        if primes >= set(rotated_num):
            is_circ.append(prime)

    return len(is_circ)


texts: Menu (headers and sub-menu) for boxes to call 2D transforms function

texts:
I am trying to learn HTML5 and I am interested in respecting good practices of the language. I have learned it is better to use tags such as
, or , to make my code more readable, than always using
 tag.

I don't care about SEO (because my project doesn't target web), so I suppose that I could use only <tag> element, but I want to make my code good and beautiful.

This code is used to show a scrolling menu with a lot of clickable buttons. Each button calls a JavaScript function for launching a 2D transform. But, it's not quoting here.

I'm interesting to know if the structure of my html code is readable and if tags are correctly used.

This is the HTML code (only inside the ):

    HTML5 / CSS3 / Javascript

    2D Translate

      Javascript

      <button id="button_translate_2d" onclick="mainStart(command.TRANSLATE_2D, 'div_translate_2d')">
        translate_2d
      </button>

      <button id="button_translate_x" onclick="mainStart(command.TRANSLATE_X, 'div_translate_2d')">
        translateX
      </button>

      Matrix 2D

      <button id="button_matrix_2d_translate" onclick="mainStart(command.TRANSLATE_MATRIX_2D, 'div_translate_2d')">
        translate
      </button>

    2D Rotation

      Javascript

      <button id="button_rotate_x_3d" onclick="mainStart(command.ROTATE_X_3D, 'div_rotate_2d')">
        rotateX_3d
      </button>

      <button id="button_rotate_x" onclick="mainStart(command.ROTATE_X, 'div_rotate_2d')">
        rotateX
      </button>

      Matrix 2D

      <button id="button_matrix_3d_rotate_x" onclick="mainStart(command.ROTATE_X_MATRIX_3D, 'div_rotate_2d')">
        rotateX
      </button>

I am particularly concerned about getting answers to the following questions:

Is the  tag used correctly?
Is it a good idea to nest
 tags too much?
I don't use the
 or the <hx> tag for text. Is this acceptable practice?


texts:
In the standard library, there are no algorithms for element updates. This makes it unsuitable as a queue for a Dijkstra's algorithm, for example. Thus I implemented generic heap update functions with the interface in line with the standard library.

Warning: the standard does not specify implementation detail of a heap. This code assumes a binary max heap. This assumption is true for libstdc++ and libc++, and probably most other implementations of standard library. Having sift_up and sift_down it is trivial to implement other heap algorithms.

template <typename RandomAccessIterator, typename Comparator =
         std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>>
void sift_up(RandomAccessIterator first, RandomAccessIterator last,
             RandomAccessIterator pos, Comparator && cmp = Comparator())
{
    (void) last; // suppress a warning about unused parameter
    using std::iter_swap;

    while (pos != first)
    {
        auto parent = first + (pos - first - 1) / 2;
        if (!cmp(*parent, *pos))
            break;
        iter_swap(parent, pos);
        pos = parent;
    }
}

template <typename RandomAccessIterator, typename Comparator =
          std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>>
void sift_down(RandomAccessIterator first, RandomAccessIterator last,
               RandomAccessIterator pos, Comparator && cmp = Comparator())
{
    using std::iter_swap;

    while (true)
    {
        auto max_child = first + 2*(pos - first) + 1;
        if (!(max_child < last))
            break;
        if (max_child + 1 < last && cmp(*max_child, *(max_child+1)))
            ++max_child;

        if (!cmp(*pos, *max_child))
            break;
        iter_swap(pos, max_child);
        pos = max_child;
    }
}

Edit: added a remark about implementation detail of a heap being unspecified in the standard.


texts: Exception based on std::exception but easy to modify and rethrow

texts:
I've looked at boost::exception and realized it is too advanced for my project, as my colleagues mostly have legacy C background. I do not need arbitrarily complex information in exception, just some error messages and trace info that can be written to process log.

Someone on Stack Overflow wrote such code as an example, but his solution can throw while trying to insert additional exception info (looks dangerous to me, correct me if I am wrong).

I tried to avoid using anything that can throw (vector of strings) inside the exception object. See: usage example.

Your feedback in term of correctness, ease of use, and required additional functionality is welcome.

const unsigned int long_enough = 512;
class my_exception : public exception {
    std::array<char, long_enough> err;
    std::array<char, long_enough>::iterator insertion_point;
public:
    template <typename Iter>
    void append(Iter first, Iter last) noexcept {
        //Remember null terminator!
        auto space_left = std::distance(insertion_point, err.end());
        if (std::distance(first, last)>=space_left){
            last = first + (space_left - 1);
        }
        insertion_point = copy(first, last, insertion_point);
    }
    void append(const char msg[]) noexcept {
        append(msg, msg+strlen(msg));
    }
    my_exception(const char msg[]) noexcept {
        insertion_point = err.begin();
        append(msg, msg+strlen(msg));
    }
    virtual const char* what() const noexcept override{
        return err.data();
    }
};


texts:
SQL:

CREATE FUNCTION dbo.fnRandomForeNames ()
RETURNS VARCHAR(50)
AS
BEGIN
RETURN  (
            SELECT TOP 1 [FirstName]
            FROM [tmp_ForeNames]
            ORDER BY (SELECT new_id from GetNewID)
        )
END
GO

Similar functions for dbo.fnRandomSurNames() etc.

UPDATE Table1
SET firstname = dbo.fnRandomForeNames(),
    lastname = dbo.fnRandomSurNames(),
    address1 = dbo.fnRandomAddress1(),
    address2 = dbo.fnRandomAddress2(),
    address3 = dbo.fnRandomAddress3(),
    birthdate = DATEADD(DAY, ABS(CHECKSUM(NEWID()) % 3650), '1990-01-01')

My C# Code:

    private void RunThis(string connString, StreamReader sr)
    {
        sr.BaseStream.Position = 0;
        string sqlQuery = sr.ReadToEnd();
        using (SqlConnection connection = new SqlConnection(connString))
        {
            Server server = new Server(new ServerConnection(connection));
            server.ConnectionContext.StatementTimeout = 4200;
            server.ConnectionContext.ExecuteNonQuery(sqlQuery);
        }
        sr.Close();
    }

........

 RunThis(e.Argument.ToString(), _updateClaim);

Where e.Argument.ToString() is the connection string.

The CREATE FUNCTION scripts are run earlier, take very little time to run.
Also, names are stored in tmp databases, these are entered in C# via arrays.
These also take very little time to run.

Table1 contains approx 140,000 rows and takes approx. 14 mins to complete.

I have also tried using parameterised SQL queries, skipping the tmp tables and SQL functions and instead creating the SQL query and executing it from the code, such as the following:

UPDATE Table1
SET lastname = '{0}',
    firstname = '{1}',
    birthdate = DATEADD(DAY, ABS(CHECKSUM(NEWID()) % 3650), '1990-01-01'),
    address1 = '{2}',
    address2 = '{3}',
    address3 = '{4}'
    WHERE u_id = '{6}'

And some C#:

 using (SqlConnection connection = new SqlConnection(connString))
        {
            connection.Open();
            for (int i = 0; i < arraySize; ++i)
            {
                string updateString = string.Format(updateString2, GetRandomSurname(), GetRandomForeName(), GetRandomAddress1(), GetRandomAddress2(), GetRandomAddress3(), "", ids[i]);
                SqlCommand cmd = new SqlCommand(updateString, connection);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
            }
        }

The latter method also taking upwards of 14 minutes.

Any ideas on how to cut down the time it takes to update the table?


texts:
I am writing a (multi) filter that is created when the user enters in the data through wordpress. There can be anywhere between 2 - 10 filters so I need this to be as dynamic as possible. My first approach was to write out a boolean for each possible filter being created and check if it is there or not. Inside the boolean is a click function that checks if the data === "yes" and then add a active class to the item. I rewrote it in a do while, but am not sure if this is the best approach or if they are both bad.

I am not looking for a complete answer or working example, but rather if my way makes sense. If so, why? If not, why not? And an explanation of how I could possible improve it or think of it in a different way.

Manually check

var mem = $(".member");

var filter1 = $(".filter-1");
var filter2 = $(".filter-2");
var filter3 = $(".filter-3");

var memCom1 = $(".member").data("com-1");
var memCom2 = $(".member").data("com-2");
var memCom3 = $(".member").data("com-3");

//  DO THIS FOR ALL POSSIBLE

if (memCom1.length > 0 || filter1.length > 0) {
    filter1.click(function() {
        var com1 = $(this).data("com-1");
        if(com1 === "yes") {
            $(this).addClass(active);
        }
    });
}

if (memCom2.length > 0 || filter2.length > 0) {
    filter2.click(function() {
        var com2 = $(this).data("com-2");
        if(com2 === "yes") {
            $(this).addClass(active);
        }
    });
}

if (memCom3.length > 0 || filter3.length > 0) {
    filter3.click(function() {
        var com3 = $(this).data("com-3");
        if(com3 === "yes") {
            $(this).addClass(active);
        }
    });
}

// would go up to 10

Do while

var mem = $(".member");
var active = "is-active"

do {
    var i = 1;
    if ( $(".member").data("com-"+i).length > 0 || $(".filter"+i).length > 0 ) {
        $(".filter-"+i).click(function() {
            if( $(this).data("com-"+i) === "yes" ) {
                $(this).addClass(active);
            }
        });
    }
  i++;
}

while (i <= mem.length);


texts: Python file modifying script with focus on OOP

texts:
I am currently coding a tool for my work that modifies a textfile by removing unneeded parts of a string at specific spots in the file.
I would like to know if there are any obvious things I am missing or doing too complicated.
I know that some of the comments are considered too long for PEP8.

class vis_file_tools:

    def __init__(self):
        pass

    # Splits the input line into list (by a space), removes the last position, joins them with spaces and returns the modified line.
    def remove_jedec_line(self, input_line):
        input_line_split = input_line.split(" ")         # splits the string that was input through the function into a list
        del input_line_split[-1]                         # deletes the last line from the list (In this case it removes the jedec)
        output_line = " ".join(input_line_split)         # joins back the list to a string. Joins the list with a space
        output_line = output_line + "\n"
        return output_line                               # returns the finished string to the caller of the function

    def remove_jedecs_file(self, path_input_file, path_output_file):
        with open(path_input_file, "r") as file:        # Opens the input file read only
            temp_data = ""
            comp_line_reached = False
            for line in file:                           # "line" in this case is already a variable. Do not us file.readline() when using the "for line" loop.
                if "COMP" in line:                      # Sets the bool "comp_line_reached" to "true" when the loop reaches the "COMP" in the .vis file which marks the start of the components
                    comp_line_reached = True
                    temp_data = temp_data + line
                elif comp_line_reached is False:        # Simply writes the lines from the file into a variable until the component part is reached.
                    temp_data = temp_data + line
                else:
                    line_no_jedec = self.remove_jedec_line(line)
                    temp_data = temp_data + line_no_jedec
        with open(path_output_file, "w") as write_file:
            write_file.write(temp_data)
            temp_data = ""                              # Empties memory


texts:
Problem Statement

  James got hold of a love letter that his friend Harry has written for
  his girlfriend. Being the prankster that James is, he decides to
  meddle with it. He changes all the words in the letter into
  palindromes.

  While modifying the letters of the word, he follows 2 rules:

  (a) He always reduces the value of a letter, e.g. he changes 'd' to
  'c', but he does not change 'c' to 'd'.  (b) If he has to repeatedly
  reduce the value of a letter, he can do it until the letter becomes
  'a'. Once a letter has been changed to 'a', it can no longer be
  changed.

  Each reduction in the value of any letter is counted as a single
  operation. Find the minimum number of operations he carries out to
  convert a given string into a palindrome.

The challange can be found here.

Input Format

The first line contains an integer \$T\$, i.e., the number of test cases.
The next \$T\$ lines will contain a string each.

Output Format

A single line containing the number of minimum operations corresponding to each test case.

Constraints

\$1 ≤ T ≤ 10\$
\$1 ≤\$ length of string \$≤ 104\$

All characters are lower cased English alphabets.

Sample Input

3
abc
abcba
abcd

Sample Output

2
0
4

Test Cases

For the first test case, abc → abb → aba.
For the second test case, abcba is a palindromic string.
For the third test case, abcd → abcc → abcb → abca = abca → abba.

Solution

T = gets.chomp.to_i
result = []
def difference x,y
  (x.ord - y.ord).abs
end
T.times do
  string = gets.chomp
  i,j = 0, -1
  n = 0
  loop do
    n = n + difference(string[i], string[j])
    i += 1
    j -= 1
    break if string.length % 2 == 0 ? i == (string.length/2) : i + j == -1 && string[i] == string[j] && i == string.length/2
  end
  result << n
end

puts result


texts:
A quick little method for validating form input with jQuery (and some built in bootstrap classes). I know the regex isn't perfect but it's close enough. Thoughts?

var validate = {

    email: function (emailAddress) {
        var re = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
        return re.test(emailAddress);
    },

    onInput: function (formSelector, responseSelector) {
        var $form = $(formSelector),
            $input = $(formSelector + ' input'),
            $feedback = $(responseSelector),
            _this = this;

        $input.on('input', function () {
            $(this).removeClass('warning');
            $feedback.removeClass('show').addClass('hidden');
        });

        $input.on('blur', function () {
            var $blur = $(this),
                type = $blur[0].type;

            if ($blur.val().length < 3) {
                $blur.addClass('warning');
            }

            if (type === 'email' && !_this.email($blur.val())) {
                $blur.addClass('warning');
            }
        });

        $form.on('submit', function (e) {
            var valid = true;

            $input.each(function () {
                $this = $(this);
                if ($this.hasClass('warning') || $this.val().length < 1) {
                    $this.addClass('warning');
                    valid = false;
                }
            });

            if (!valid) {
                e.preventDefault();
                $feedback.html('Please fill out all form fields and resubmit.').removeClass('hidden').addClass('show');
            }
        });
    }

};


texts: What are best practices for writing conditional statements?

texts:
I am doing some console test program, and I have some normal math operations. Example of part of my code:

if (flagMultiplyDivide.Equals(true))
{
    if (currentOperator.Equals('*'))
    {
        currentNumberDouble = multiplyNumbers(currentNumberString, temporaryNumberString);
        if (operatorOnHold.Equals('+'))
        {
            total += currentNumberDouble;
        }
        else if (operatorOnHold.Equals('-'))
        {
            total -= currentNumberDouble;
        }
        else
        {
            total = currentNumberDouble;
        }
        flagMultiplyDivide = false;
    }
    else if (currentOperator.Equals('/'))
    {
        currentNumberDouble = divideNumbers(temporaryNumberString, currentNumberString);
        if (operatorOnHold.Equals('+'))
        {
            total += currentNumberDouble;
        }
        else if (operatorOnHold.Equals('-'))
        {
            total -= currentNumberDouble;
        }
        else
        {
            total = currentNumberDouble;
        }
    }
}
else if (currentOperator.Equals('+'))
{
    if (!numberOnHold.Equals(""))
    {
        total += Convert.ToDouble(currentNumberString) + Convert.ToDouble(numberOnHold);
    }
    else
    {
        total += Convert.ToDouble(currentNumberString);
    }

}
else if (currentOperator.Equals('-'))
{
    if (!numberOnHold.Equals(""))
    {
        total -= Convert.ToDouble(currentNumberString) - Convert.ToDouble(numberOnHold);
    }
    else
    {
        total -= Convert.ToDouble(currentNumberString);
    }

}

return total;

Since it is logical program, I have a lot of conditional statements, and it is easy to lose in code. What is the best practice to code conditional statements in my case? How would you improve my part of code?

What am I doing wrong? I never have a problem to make a working code, but I really want to learn best practice, really. That's why I am here.


texts: Python Minimization Functions: Is the code optimal?

texts:
I am rather new to python and am porting my R functions into python. I have written the functions below and the primary function is called thetaMax. That function minimizes a likelihood function or optionally minimizes a posterior distribution, depending on the option selected by method. The function works exactly as intended and I have unit tested this against my R code.

However, because I am not familiar with pythonic ways of doing this, I am curious what parts of the code below could be improved to 1) write less/more compact code and 2) to improve speed and take advantage of vectorization when possible?

A complete reproducible example is below

import numpy as np
from scipy.stats import binom
from scipy.optimize import minimize
from scipy.stats import norm

def prob3pl(theta, a, b, c, D = 1.7):
    result = c + (1 - c) / (1 + np.exp(-D * a * (theta - b)))
    return(result)

def gpcm(theta, d, score, a, D = 1.7):
    Da = D * a
    result = np.exp(np.sum(Da * (theta - d[0:score])))/np.sum(np.exp(np.cumsum(Da * (theta - d))))
    return(result)

def thetaMax(x, indDichot, a, b, c, D, d, method = 'mle', **kwargs):
    method_options = ['mle', 'map']
    optional_args = kwargs
    if method not in method_options:
        raise ValueError("Invalid method. Expected one of: %s" % method_options)
    if method == 'map' and 'mu' not in optional_args:
        raise ValueError("You must enter a value for 'mu' for the posterior distribution. Example, mu = 0")
    if method == 'map' and 'sigma' not in optional_args:
        raise ValueError("You must enter a value for 'sigma' for the posterior distribution. Example, sigma = 1")
    x1 = x[indDichot]
    x2 = np.delete(x, indDichot)
    result = [0] * len(x2)
    def fn(theta):
        if(len(x1) > 0):
            p = prob3pl(theta, a, b, c, D = D)
            logDichPart = np.log(binom.pmf(x1,1,p)).sum()
        else:
            logPolyPart = 0
        if(len(x2) > 0):
            for i in range(0,len(x2)):
                result[i] = gpcm(theta, d = d[i], score = x2[i], a = 1, D = D)
            logPolyPart = np.log(result).sum()
        else:
            logPolyPart = 0
        if(method == 'mle'):
            LL = -(logDichPart + logPolyPart)
        elif(method == 'map'):
            normal = np.log(norm.pdf(theta, loc = optional_args['mu'], scale = optional_args['sigma']))
            LL = -(logDichPart + logPolyPart + normal)
        return(LL)
    out = minimize(fn, x0=0)
    return(out)

### In order to run
d = np.array([[0, -1, .5, 1],[0,-.5,.2,1]])
a = np.array([1,1,1,1,1])
b = np.array([-1,.5,-.5,0,2])
c = np.array([0,0,0,0,0])
#x = np.array([1,1,0,1,0])
x = np.array([1,1,0,1,0,1,1])
indDichot = range(0,5,1)

object = py.thetaMax(x,indDichot,a,b,c,D=1,d = d)


texts:
Whilst learning Rust I am solving different algorithm problems. Below is a solution to largest rectangle in histogram.
Algorithm is well described here:

Although code below does the job it is very verbose (much more than my C++ solution).

pub fn largest_rectangle(v: &mut Vec<i32>) -> i32 {
    let mut stack: Vec<usize> = Vec::new();
    // populate stack with 0 - (index of first element in 'v') to avoid checking for empty stack
    stack.push(0);
    // insert -1 from both sides so that we don't have to test for corner cases
    v.insert(0, -1);
    v.push(-1);
    let mut answer = 0;
    for (i, h) in v.iter().enumerate() {
        let idx = i as i32;
        if h > &v[stack.last().unwrap().clone()] {
            stack.push(i);
        } else {
            while h < &v[stack.last().unwrap().clone()] {
                let last_bar = v[stack.pop().unwrap().clone()];
                let area = last_bar * (idx - 1 - stack.last().unwrap().clone() as i32);
                answer = std::cmp::max(area, answer);
            }
            stack.push(i);
        }
    }
    answer
}

My questions:

Is it possible to get rid of those 'unwrap().clone()' constructs?
Why does compiler make me use references in if statements (h > &v[] and h < &v[])?


texts:
Consider the following method that I have for checking write permissions on a directory path:

/// <summary>
/// Check existence and write permissions of supplied directory.
/// </summary>
/// <param name="directory">The directory to check.</param>
protected static void CheckPermissions(string directory)
{
    if (!Directory.Exists(directory))
    {
        throw new DirectoryNotFoundException(String.Format(JobItemsStrings.Job_DirectoryNotFound, directory));
    }

    // Check permissions exist to write to the directory.
    // Will throw a System.Security.SecurityException if the demand fails.
    FileIOPermission ioPermission = new FileIOPermission(FileIOPermissionAccess.Write, directory);
    ioPermission.Demand();
}

When running FxCop, this code throws up a "CA2103 - Review imperative security" warning, albeit with a certainty of 25%, with this info:

  "Use of imperative demands can lead to
  unforeseen security problems. The
  values used to construct a permission
  should not change within the scope of
  the demand call. For some components
  the scope spans from the demand call
  to end of the method; for others it
  spans from the demand call until the
  component is finalized. If the values
  used to construct the permission are
  fields or properties, they can be
  changed within the scope of the demand
  call. This can lead to race
  conditions, mutable read-only arrays,
  and problems with boxed  value types."

Bascially, is FxCop being over-cautious, or am I doing it wrong?


texts: C++14-ish code for creating q-grams of a string

texts:
I want to return an iterable collection of all q-grams of a provided string. This means all sub-words of length Q. Let Q be 3 for example:

normalized as an already whitespace-stripped and upcased word or string. PREFIX3 and SUFFIX3 are constant strings ^^ and$$ that are put surrounding the string before splitting. That is a common trick to get more q-words.

For the word INDEX the resulting q-grams are therefore:

^^I  ^IN  IND  NDE  DEX  EX$  X$$

My version uses several C++14 constructs. This is intended, because the code is part of a lesson for teaching about C++14.

Is there anything I could do better, especially with respect to C++14-ish code?

vector<string> qwordify(const string& normalized) const
{
    auto word = PREFIX3 + normalized + SUFFIX3;
    vector<string> result {};
    auto left = word.cbegin();
    auto right = word.cbegin() + Q; // valid, because |"^^"|+|"$$"| => 3.
    for( ; right <= word.end(); ++left, ++right) {
        result.emplace_back(left, right);
    }
    return result;
}

Here are the things I considered especially:

Despite of returning a value, result is not copied, because of RVO.
Lots of auto, which I like.
Use of cbegin() and  cend(), because I declared auto word and not const auto word. I could have done, but for this demonstration I liked to show the c-variants.
Use of emplace_back, which really saves a copy here, correct?

I feel like some places could be improved, maybe. The iterators maybe? Getting rid of the loop in favor of an algorithm? Maybe even not returning a full vector at all, but only an iterable proxy-object, but that would too long a shot for this small example, I think.


texts: Python 3.6+ Conventions for fetching paginated data

texts:
I find myself often encountering a use case where I need to fetch paginated data, where I need all of the data. Currently I use something similar to below to handle these cases:

def fetch_paginated_data(api_base, query, good_citizen_rate):
    encoded = urllib.parse.quote(query.encode('utf-8'))
    initial = f'{api_base}?q={encoded}'
    payload = {
        'has_more': True,
        'next_page': initial
    }

    storage = []

    while payload['has_more']:
        response = requests.get(payload['next_page'])
        if response.status_code != 200:
            raise ValueError('Status not 200')
            payload['has_more'] = False
            return

        data = response.json()
        if (data and data['data']):
            storage.extend(data['data'])

        payload['has_more'] = data['has_more']
        if 'next_page' in data:
            payload['next_page'] = data['next_page']
        time.sleep(good_citizen_rate)
    return storage

My question is how could I better make this convention more reusable? Should I use async / await? yield pages? Add a callback to transform the data prior to adding it to the collection variable?


texts:
Please look at the above code

#include<stdio.h>
#include<stdlib.h>
void mergesort(int *,int ,int);
void merge1(int *,int ,int ,int);

int main()
{
int low=0,high,n,i,a[100];

  printf("Enter the lenght of array\n");
  scanf("%d",&n);
  high =n-1;
  printf("Enter the array that you want to sort\n");

  for(i=low;i<=high;i++)
  {
    scanf("%d",&a[i]);
  }

  mergesort(a,low,high);
  printf("The sorted array is \n");

  for(i=low;i<=high;i++)
  {
    printf("%d-",a[i]);
  }
  printf("MERGE sorted");
  return 0;
}

void mergesort(int a[],int low,int high)

{

  int mid;
  if(low<high)
 {
    mid=(low+high)/2;
    mergesort(a,low,mid);
    mergesort(a,mid+1,high);
    merge1(a,low,mid,high);
 }

}

 void merge1(int a[],int low,int mid,int high)
{
    int i=low,j=mid+1,new_array[100],k=low,m;

      while(i<=mid && j<=high)
   {
     if(a[i]<a[j])
     {
       new_array[k]=a[i];
       i++;
       k++;
     }
    else
    {
       new_array[k]=a[j];
       j++;
       k++;

    }
   }

        while(i<=mid)
       {
       new_array[k]=a[i];
       i++;k++;
       }

       while(j<=high)
      {
       new_array[k]=a[j];
       j++;
       k++;
      }

      for(m=low;m<=high;m++)
     {
         a[m]=new_array[m];
     }

}

Actually, I implemented merge sort and it is working fine but I want much better code than this . Can anyone  make this code much better?


texts: Delete orphaned SIDS + change to full control

texts:
I need to delete all the orphaned SIDs in the ACLs of about 20 shares (between 100GB/6TB) and change full control of users groups to other permissions (modify or read/execute). I have done this script but I'm pretty sure it's easy to improve. Any advice?

$root = "\\192.168.1.1\folder"
$log = "C:\log.txt"

#log creation
"----------SIDS----------" | Out-File $log

#folders list
Get-ChildItem $root -Recurse -Directory | ForEach-Object -Begin {
    $folders = @((Get-Item $root).FullName)
} -Process {
    $folders += $_.FullName
}

##############################DELETE ORPHANED SIDS########################

foreach ($folder in $folders) {
    try {
        $acl = Get-Acl -Path $folder
        foreach ($acc in $acl.access ) {
            $acc_ir = $acc.IdentityReference.Value
            if ($acc_ir -match "S-1-5*") {
                $ACL.RemoveAccessRule($acc) | Out-Null
                Set-Acl -Path $folder -AclObject $acl -ErrorAction Stop
                $hour = Get-Date
                Write-Host -ForegroundColor Green "$hour - $acc_ir deleted in $folder"
                Write-Output "$hour - $acc_ir deleted in $folder" | Out-File -Append $log
            }
        }
    } catch {
        $hour_e = Get-Date
        Write-Host -ForegroundColor Red "$hour_e - error with $acc_ir in $folder"
        Write-Output "$hour_e - error with $acc_ir in $folder" | Out-File -Append $log
    }
}

##############################CHANGE FULLCONTROL########################

"----------FULLCONTROL----------" | Out-File -Append $log

foreach ($folder in $folders) {
    try {
        $acl = Get-Acl -Path $folder
        foreach ($acc in $acl.access ) {
            $acc_ir = $acc.IdentityReference
            $acc_fsr = $acc.FileSystemRights
            if ($acc_ir -match "GROUP" -and $acc_fsr -match "FullControl") {
                $newacc = New-Object System.Security.AccessControl.FileSystemAccessRule($acc_ir, 'Modify', $acc.InheritanceFlags, $acc.PropagationFlags, $acc.AccessControlType)
                $ACL.RemoveAccessRule($acc) | Out-Null
                $ACL.AddAccessRule($newacc) | Out-Null
                Set-Acl -Path $folder -AclObject $acl -ErrorAction Stop
                $new_perm = $newacc.FileSystemRights
                $hour = Get-Date
                Write-Host -ForegroundColor Green "$hour - $folder : the object $acc_ir now have $new_perm"
                Write-Output "$hour - $folder : the object $acc_ir now have $new_perm" | Out-File -Append $log
            }
        }
    } catch {
        $hour_e = Get-Date
        Write-Host -ForegroundColor Red "$hour_e - error with the object $acc_ir in $folder"
        Write-Output "$hour_e - error with the object $acc_ir in $folder" | Out-File -Append $log
    }
}


texts: Simulating data generating process correctly

texts:
My aim is to simulate the following model by means of a Monte Carlo simulation. I wonder if my R code is correct for generating the data.

Could somebody check?

The model:

$$Y = \sum_{j=1}^{100} (1+(-1)^{j}A_j X_j + B_j \sin(6X_j)) \sum_{j=1}^{50} (1+X_j/50) + \epsilon$$

where

\$A_1, \dots, A_{100}\$ are i.i.d. \$∼ \text{Unif}([0.6,1])\$
\$B_1, \dots, B_{100}\$ are i.i.d. \$∼ \text{Unif}([0.8,1.2])\$ and independent of \$A_j\$
\$X \sim \text{Unif}([0,1])\$ where all components are i.i.d. \$∼ \text{Unif}([0, 1])\$
\$\epsilon \sim N(0,2)\$ and \$X_j\$ represents the \$j\$th column of the design matrix

You can find the model here, p. 14

This is my code attempt

n_sim <- 10
n_sample <- 200
n_reg <- 100
sd_eps <- sqrt(2)

X <- replicate(n_reg, runif(n_sample, 0,1))
A <- replicate(n_reg, runif(1, 0.6,1))
B <- replicate(n_reg, runif(1, 0.8,1.2))

f_1 <- vector(mode = 'integer', length = n_sample)
f_2 <- vector(mode = 'integer', length = n_sample)

for (d in seq(100)){
  part1 <- 1 + (-1)^d*A[d]*X[,d]+B[d]*sin(6*X[,d])
  f_1 <- f_1 + part1
}

for (d in seq(50)){
  part2 <- 1 + X[,d]/50
  f_2 <- f_2 + part2
}

# True DGP Train ----
f_true <- f_1*f_2
y <- replicate(n_sim, f_true) + replicate(n_sim, rnorm(n_sample, 0,sd_eps))


texts: Extending Object.prototype in JavaScript

texts:
I find the default Javascript extremely poor on useful functions. There are some nice libraries, but somehow I always need something I can't find. Currently, I'd need a method removing all matching properties from an object. And I really mean removing, not creating a filtered copy. I've found similar methods in both jquery and underscore, but no exact match.

That's a long introduction, why I want to give it a try. As both $ and _ are taken, I'm extending the Object.prototype which should be fine. So this is the code:

function removeMatching(predicate) {
    for (var key in this) {
        if (!Object.prototype.hasOwnProperty.call(this, key)) continue;
        if (predicate(key, this[key])) delete this[key];
    };
};

Object.defineProperty(Object.prototype, 'removeMatching', {
    value: removeMatching,
    writable: false,
    configurable: false,
    enumerable: false
});

It's all gets enclosed in a closure to prevent namespace pollution. I don't care much about speed as this can be improved later (but tell me). I don't care about style (it's fixed) not about compatibility with old crap. I do care about all problems possible in modern browsers.

It's to be used like

var o = {a: 1, b: 2, c: 3};
o.removeMatching(function(k, v) {return k === "a" || v === 2});
// now o is {c: 3}


texts: LeetCode: Network Delay Time Bellman Ford C#

texts:
https://leetcode.com/problems/network-delay-time/

  There are N network nodes, labelled 1 to N.

  Given times, a list of travel times as directed edges times[i] = (u,
  v, w), where u is the source node, v is the target node, and w is the
  time it takes for a signal to travel from source to target.

  Now, we send a signal from a certain node K. How long will it take for
  all nodes to receive the signal? If it is impossible, return -1.

Note:

  N will be in the range [1, 100].
  K will be in the range [1, N]. The
  length of times will be in the range [1, 6000].
  All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 0 <= w <= 100.

Please review for performance

   [TestClass]
    public class NetworkDelayTimeTest
    {
        [TestMethod]
        public void ExampleTestBellmanFord()
        {
            int N = 4;
            int K = 2;
            int[][] times = { new[] { 2, 1, 1 }, new[] { 2, 3, 1 }, new[] { 3, 4, 1 } };
            NetworkDelayTimeBellmanFord bellmanFord = new NetworkDelayTimeBellmanFord();
            Assert.AreEqual(2, bellmanFord.NetworkDelayTime(times, N, K));
        }
    }

  public class NetworkDelayTimeBellmanFord
    {
        public int NetworkDelayTime(int[][] times, int N, int K)
        {
            var dist = Enumerable.Repeat(int.MaxValue, N + 1).ToList();
            dist[K] = 0;
            for (int i = 0; i < N; i++)
            {
                foreach (var e in times)
                {
                    int u = e[0];
                    int v = e[1];
                    int w = e[2];
                    if (dist[u] != int.MaxValue && dist[v] > dist[u] + w)
                    {
                        dist[v] = dist[u] + w;
                    }
                }
            }

            int maxWait = 0;
            for (int i = 1; i <= N; i++)
            {
                maxWait = Math.Max(maxWait, dist[i]);
            }

            if (maxWait == int.MaxValue)
            {
                return -1;
            }

            return maxWait;
        }
    }


texts:
I'm new to React hooks and trying to learn to write custom hooks. Today I wrote a hook that I believe works as an effective debouncer of a setter function, to prevent excessive updates when data changes rapidly. I'm trying to keep this as simple as possible so as to be reusable throughout the app and by other developers on my team if they need it.

I have tested this, and it appears to work as expected. It's currently being used to prevent excessive updates from a textfield. I'm unsure of any hidden performance drains doing this might cause, and I also don't know if I've gone about doing this in a way that makes sense (or if there might be less complicated ways of accomplishing what I want.

// Returns a callback function that wraps the passed setter in a debouncer mechanism
// While the timer is off, the setter will be called immediately and trigger a new timer.
// While the timer is on, the value to be set is captured and used at the end of the timer period.
// Subsequent calls during the timer period will replace the captured value to be set, there is no queue.
export function useDebouncedSetter(setter: (value: any) => void, timeout = 1000) {
    const timerActive = useRef(false);
    const valueCapture = useRef(null);
    const setterCapture = useRef(setter);  // Capture the setter value to detect if a new one is passed

    return useCallback(async (value: any) => {
        if (timerActive.current === true) {
            valueCapture.current = value;
        } else {
            setter(value);
            valueCapture.current = value;
            timerActive.current = true;
            setterCapture.current = setter;
            setTimeout(() => {
                timerActive.current = false;
                // If the last captured value is the same as the value when the timeout was started, do nothing
                // If the last captured setter is different from the current setter, do nothing
                // This later case means a new setter was passed invalidating the old one.
                if (valueCapture.current !== value && setterCapture.current === setter) {
                    setter(valueCapture.current);
                }
            }, timeout);
        }
        return () => {
            // Cleanup, set the flag to false, get rid of the last value.
            timerActive.current = false;
            valueCapture.current = null;
        }
    }, [setter, timeout]);
}

How best can I improve this? How can I tested its effectiveness compared to other methods, if any are feasible?


texts:
In a simple webapp I have been using as a playground, I am playing with using rxjava to perform a number of operations in a reactive manner.  I have been using reactivemongo to connect to my Mongo database, but I find that for anything more than a trivial CRUD operation I often end up trying to reduce a Future[List[Future[T]]] into a Future[List[T]].  This can happen multiple times in the execution chain, before I finally hand it back to the Play framework.

I am playing with rxjava to try to convert these reactive operations into Observables, so that I can combine them using rxjava's utility methods, but I was wondering if anyone had already solved this problem.

Here is an example from my most complex action:

def import = Action {
   //scan the base folder for app IDs (Future[List[UUID]])
   val summaries = ftpWrapper.scanUserIdsAsync

   //import all the files in each of those folders (Future[List[LogImportResult]])
   val processResults = summaries.flatMap(lst => {

     //List[Future[List[LogImportResult]]]
     val imports = lst.map(user => logProcessor.importLogFolderAsync(user))

     //fold together the several lists of insertion results into one list
     Future.fold(imports)( List[LogImportResult]() )( _ ++ _ )
   })

   Async {
     //display the insertion results, or throw.
     processResults.transform(r => Ok(views.html.logImportResult(r)), ex => throw ex)
   }
}

The above code calls into my services to do the following:

Locate all folders on an FTP server whose names are UUIDs
Import all files inside each folder into the Mongo database:

check if the file already exists in mongo
if no, then insert the data from the file as a BSONDocument

combine the results of importing each folder into one giant list
display the results in the view

Most of these actions are non-blocking asynchronous, and as such return a future.  I have code all over the place in this app to combine these futures together, so I am interested in seeing if rxjava can simplify that.  I have already been working on some ideas here: https://gist.github.com/gburgett/6106724

So, has anyone encountered something like this?  If so, do you have a better way to go about it than simply combining futures like this?


texts:
This Python code looks messy to me. Am I doing any wrong style, or is this how Python looks like?

def is_prime(number):
    """check whether the @param number is a prime number"""
    is_prime = True
    for i in range(2, (number - 1)):
        is_prime = ((number % i) != 0)
        if not is_prime:
            return is_prime
    return is_prime

This Java code looks more clean, maybe due to a lot of empty lines generated due to the { } brackets:

private boolean isPrime(int toCheck)
{
    boolean isPrime = true;

    for (int i = 2; i < toCheck; i++)
    {
        isPrime = ((toCheck % i) != 0);
        if (!isPrime)
        {
            return isPrime;
        }
    }

    return isPrime;
}

Python version 2.6.


texts:
I have a database-intensive app, almost every activity requires access to the database, both reading and writing.
I had a lot of problems with separate threads and activities on the stack closing connections to the database when the current activity was using it, even if I opened and closed the database immediately before and after use.

So I opted to use a single instance of the database. Now I have no problems, but, is this right?

Application class

public class ApplicationClass extends Application
{
    private DatabaseAdapter PrDatabaseAdapter;

    public DatabaseAdapter getDatabaseAdapter()
    {
        return PrDatabaseAdapter;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();

        PrDatabaseAdapter = new DatabaseAdapter(this);
        PrDatabaseAdapter.open();
    }
}

Adapter Class
The database adapter just sits on top of the DatabaseManager (my SQLiteOpenHelper)

private Context context;
private SQLiteDatabase db;
private DatabaseManager dbManager;

/**
 * The DatabaseAdapter contains all interaction logic for the database
 * @param context
 */
public DatabaseAdapter(Context context)
{
    this.context = context;
}

/**
 * Opens writable database
 * @return DatabaseAdapter;
 * @throws SQLiteException
 */
public DatabaseAdapter open() throws SQLiteException
{
    dbManager = new DatabaseManager(context);
    db = dbManager.getWritableDatabase();
    return this;
}

/**
 * Closes database connection
 */
public void close()
{
    dbManager.close();
}

I'm still learning a lot about Java and Android and I would appreciate some insight to the pros and cons of this approach.


texts:
Consider such a code (javascript):

var jsonTmp = '{ "groups": [ { "name": "G1", "status": "inactive" }, { "name": "G2", "status": "active"}, { "name": "G3", "status": "inactive" }] }'
var dataTmp = JSON.parse(jsonTmp)

function g(key) {
    this.key = key;
    this.name;
    this.status;

    this.setStatus = function (status) {
        this.status = status;
    }

    this.setName = function (name) {
        this.name = name;
    }

}

function main() {
    this.groups = []

    this.createGroups = function () {
        $.each(dataTmp.groups, function (key, group) {
             myGame.groups[key] = new g(key)
             myGame.groups[key].setStatus(group.status)
             myGame.groups[key].setName(group.name)
        })
    }

    this.getGroupsWithStatus = function (status) {
        var groups = [];
        $.each(myGroups, function (key, group) {
            if ( group.status == status ) { groups.push( key )}
        })
        return groups
    }

}

var myGame = new main();
var myGroups = myGame.groups
myGame.createGroups();
myGame.getGroupsWithStatus("inactive")

I am attempting to make good and effective, also readable OOP logic, and since it is my first fully oop project please make some advices:

I create game (myGame), that takes dynamically (from jsonTmp) data to create multiple objects, called groups. Because amount of groups may be different they do not have a name like

var group1 = new g("abc")
var group2 = new g("cde")

They are stored without a instialized name in array of objects (here myGame.groups or myGroups).

Question 1: is that a good idea of storing objects to access them via key of object in array? I will be also searching for particular value of property of objects - like status here with getGroupsWithStatus. Do you have any better ideas to solve such a logic?

Question 2: can i set a name of instance in different way then

var instanceName = new g("abc")

and do i really need it if my objects are stored in array?

Question 3:
In createGroups method I would rather use some kind of pointer instead of myGame.groups[key]:

  this.createGroups = function () {
        $.each(dataTmp.groups, function (key, group) {
        var currentGroup;
        currentGroup = new g(key)
        currentGroup.setStatus(group.status)
        currentGroup.setName(group.name)
        myGame.groups[key] = currentGroup;
        })
    }

I guess that solution is more readable. Am i right?

Sorry for maybe dumb questions, but i always used structural languages and oop logic is quite hard for me to use, and most of tutorials say about how to make class or inherit props of objects. Maybe you can also provide some good oop in practice tutorials?
Thansk in advance.
Kalreg.


texts: Write Once Use Everywhere: Multidimensional array traversal

texts:
I have a structure that is organized much like a Sudoku board, where individual cells reside in an n x n region, and those regions reside in an n x n area. I need to be able to address both the regions and the individual cells within the regions separately.

When operating on every individual cell (in a particular order), I (previously) had a number of huge, unwieldy, 4-deep 'for' loops like so (traversing in a doubly row-major fashion):

for (int i_row = 0; i_row < BOUND; ++i_row) {
    for (int j_row = 0; j_row < BOUND; ++j_row) {
        for (int i_col = 0; i_col < BOUND; ++i_col) {
            for (int j_col = 0; j_col < BOUND; ++j_col) {
                // operate on cell at (i_row, i_col, j_row, j_col)
            }
        }
    }
}

To eliminate these, I created a utility class so I could write it once and use it everywhere:

public class TraversalUtil {
    // private to prevent instantiation
    private TraversalUtil() {}

    public static void traverseDoubleRowMajor(TraversalFunc func) {
        int bound = Context.getInstance().getBound();
        for (int i_row = 0; i_row < bound; ++i_row) {
            for (int j_row = 0; j_row < bound; ++j_row) {
                for (int i_col = 0; i_col < bound; ++i_col) {
                    for (int j_col = 0; j_col < bound; ++j_col) {
                        func.exec(i_row, i_col, j_row, j_col);
                    }
                }
            }
        }
    }

    @FunctionalInterface
    public interface TraversalFunc {
        public void exec(int i_row, int i_col, int j_row, int j_col);
    }
}

So usage becomes:

TraversalUtil.traverseDoubleRowMajor( (i, j, k, m) -> {
    System.out.println(getCellAt(i, j, k, m)); // or whatever
});

I'm wondering if this is bad practice or if anyone has any suggestions/changes/improvements. I'm reluctant to change the '2d array of 2d arrays' structure itself because it is a dream to work with in other contexts and circumstances, so fundamental design changes to that model is a much lower priority for me.

I have run into an issue where I've needed external variables (mainly primitives) to be available to the content inside the lambda. To work around that I've been using wrapped primitives marked as final, which seems to work pretty well for me.

Any thoughts are greatly appreciated!


texts:
I asked a similar question (C++ linked list) but I'd like to have this similar code reviewed. It's not the same code, just slightly different and with bugs fixed.

The code takes the head pointer of a singly linked list and an int element to find and remove from the list:

void removeFromList(node* &head, int toBeRemoved){
    if (head != nullptr){
        node* temp = head;
        if (head->data == toBeRemoved){
            head = head->next;
            delete temp;
        }
        else{
            while (temp->next != nullptr && temp->next->data !=toBeRemoved)
                temp = temp->next;

            if (temp->next == nullptr)
                //some code to be executed when element not found
                else{
                if (temp->next->data == toBeRemoved){
                    node* removeThis = temp->next;
                    temp->next = temp->next->next;
                    delete removeThis;
                }
            }
        }
    }
    else
        //some code to be executed when list is empty
}

I've tested it by outputting messages to the console in case the element is not found or the list is empty, and it seems to be working in every case.

Still, I'd like to know if the code can be improved (not trying to use the C++ list implementation, just to rewrite this in the best way).


texts: Assign a value to combobox depend upon other combobox value

texts:
I have a windows form in C# project that keeps some information. I created a bunch of textbox and combobox dynamically, depend upon user input.

Consider, I have a list of 10 combobox whose values will be selected by user.

The combobox values are:

Finding
No Finding
Incomplete
Skipped.

Now I have a single final combobox  which contains the following values.

Finding
No Finding
Incomplete
Skipped Reviewed
Skipped Not reviewed

The final combobox  should be populated depend upon the following logic

If all values are "Finding",  then the the final combobox should be "Finding"
If all values are "No_Finding", then the the final combobox should be "No_Finding"
If all values are "InComplete", then the the final combobox should be "InComplete"
If all values are "Skipped", then the the final combobox should be "Skipped Not Reviewed".
If any value is "Finding", then the final combobox should be "Finding".
If any value is "Incomplete", then the final combobox should be "Incomplete".
If any value is "Skipped", then the final combobox should be "Skipped Reviewed".

With respect to the above logic conditions I have written the following that works fine.

After writing the code I feel it's not cleaner and not an easily understandable solution.

What I need now whether there is any way to refactor the following lines of code.

 public void selectfinalComboxValue()
        {
            List<string> list_of_combobox = new List<string>();
//txtBoxValLines is an user input
            for (int i = 0; i < int.Parse(txtboxvalLines.Text); i++)
            {
                string cmbboxValue = ((ComboBox)panel1.Controls["Add_combobox" + (i).ToString()]).Text;
                list_of_combobox.Add(cmbboxValue);

            }
            List<string> distinct = list_of_combobox.Distinct().ToList();

            if (distinct.Any(str => str.Contains("InComplete")))
            {
                cmbFinalStatus.SelectedIndex = 2;
                cmbFinalStatus.Enabled = false;
            }
            else if (distinct.Any(str => str.Equals("Finding")))
            {
                cmbFinalStatus.SelectedIndex = 0;
                cmbFinalStatus.Enabled = false;
            }
            else
            {
                cmbFinalStatus.SelectedIndex = -1;
                cmbFinalStatus.Enabled = true;
            }

            if (distinct.Count().ToString() == "1")
            {

                if (distinct.Any(str => str.Equals("Skipped")))
                {
                    cmbFinalStatus.SelectedIndex = 4;
                    cmbFinalStatus.Enabled = false;
                }
                else if (distinct.Any(str => str.Equals("No Finding")))
                {
                    cmbFinalStatus.SelectedIndex = 1;
                    cmbFinalStatus.Enabled = false;
                }
            }
            else {
                if (distinct.Any(str => str.Contains("Skipped")))
                {
                    cmbFinalStatus.SelectedIndex = 3;
                    cmbFinalStatus.Enabled = false;
                }

            }
        }


texts:
Check for Expiry

Expiry can go from 1 to 299
Expiry can be 1 digit, 2 digits or 3 digits

This will be the Input I check my regExp against.
Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2] i0 exp276
Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2] i0 exp82
Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2] i0 exp2

exp will decrease every second by one
My RegExp
let regExp = \exp[0-2]{0,1}[0-9]{1,2}\

The regeExp matches everything up from 0 up to 299.
Try it here
What do you think about this regExp.
I'm looking forward to any advice about Regular Expressions


texts: Flatten dictionary in Python (functional style)

texts:
I'm trying to learn how to write functional code with Python and have found some tutorials online. Please note that I know Python is not a promoter for functional programming. I just want to try it out. One tutorial in particular gives this as an exercise:

  Write a function flatten_dict to flatten a nested dictionary by
  joining the keys with . character.

So I decided to give it a try. Here is what I have and it works fine:

def flatten_dict(d, result={}, prv_keys=[]):

    for k, v in d.iteritems():
        if isinstance(v, dict):
            flatten_dict(v, result, prv_keys + [k])
        else:
            result['.'.join(prv_keys + [k])] = v

return result

I'd like to know whether this is the best way to solve the problem in python. In particular, I really don't like to pass a list of previous keys to the recursive call.


texts:
I am a rookie and I need help optimizing this SelectionSort() algorithm which I have tried using Python.
def selectionSort(arr,an):
    for lastUnsortedInteger in range(an-1,0,-1):
        largest = arr.index(max(arr[0:lastUnsortedInteger+1]))
        swap(arr,largest,lastUnsortedInteger)
    return arr

def swap(arr,ai,aj):
    arr[ai],arr[aj] = arr[aj],arr[ai]

if __name__ == '__main__':
    an = int(input())
    arr = list(map(int,input().strip().split()))
    selectionSort(arr,an)
    print("Sorted using SelectionSort():\n")
    for ai in arr:
        print(arr)


texts:
I'm learning Ember, and I've come across a situation where I haven't been able to find a pattern online.

My application's main route includes a list of "stories" (think scrum).  However, this list also has a StoryController associated with it.  I don't want to assign the stories in the IndexRoute file; it doesn't feel like it belongs there.  I ended up adding a property to the StoriesController and calling the App.Story.fetch() method to the Controller's init() method.  I can't help but feel there is a better, more "Ember" way to do this.

App.IndexRoute

App.IndexRoute = Ember.Route.extend({

    renderTemplate: function(){
        this.render();

        this.render('stories');
    }
});

App.StoriesController

App.StoriesController = Ember.ArrayController.extend({
    init : function(){
        this.stories = App.Story.find();
    }
});