texts: Google Apps Script shifting columns containing specified substring - using array functions

texts:
The link is to the example sheet of what I have done

This code solves the problem of shifting large amounts of specific data in a google spreadsheet. The data is shifted to the right by one column, but only the data containing the specified substring (in this case, "PO"). It is intended to shift the leftmost row over by one column.

https://docs.google.com/spreadsheets/d/12w4rGArGi1I1wlpm5yJJtT5AAlMM4LcZC31_DpP6jZQ/edit?usp=sharing

I shifted the rows that contain "PO" in my data selection. (see shift function)

It was suggested to me that I use array functions to made the code better, but I am honestly not sure how to refactor it. I am still very much a beginner.

I'm guessing I can more easily do this instead of trying to reassign array index values.

Here is my current script:

function shift() {
  try{
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var as = ss.getActiveSheet();
    var ar = as.getActiveRange();
    var vals = ar.getValues();
    var r; //variable for rows

    // in this first section, I've already stored the active range (my selection) into a two dimensional array.

    for (r = 0; r < vals.length; r++){                                           // for each row, up to the last row (iterate over all rows from top to bottom)
      if((vals[r][0].indexOf("PO") != -1)||(vals[r][0].indexOf("P0") != -1)){    // if first column in each row contains "PO"
        var c; // variable for columns
        var cols = []; // array to store all data temporarily (will be uses to set new values later)
        for (c = 0; c < vals[r].length; c++){                                   // then iterate over each column(cell) in the row
          if(c == 0){                                                           // if it is the first row,
            cols[c+1] = vals[r][c];                                             // assign second index of the array with the PO value (to simulate a shift)
            cols[c] = "";                                                       // assign the first index of the array a blank string
          }
          else{                                                                 // if it is not the first row
            cols[c+1] = vals[r][c];                                             // assign each additional column value to the next index (+1) of the array
          }
        }
        for (c = 0; c < vals[r].length; c++){                                   // once the array is finished, loop through the columns again foreach row
          vals[r][c] = cols[c];                                                 // this time, assigning the new values to the corresponding array indices
        }
      }
    }
    ar.setValues(vals);                                                         // now, set the values that you reassinged to the array
  }
  catch(err){
    SpreadsheetApp.getUi().alert(err);
  }
}


texts:
Is there anything I can do better here? I tried looking for ways to simplify this with comprehension but could not figure out how and was told it is better to explicitly use for loops.

import re

print("This is a email/phone number parser.")
print("Type in the name of the file you want to parse:\n")
filename = input("> ")

emailregex = re.compile(r'''
([a-z0-9\.]+)
(@)
([a-z0-9\.]+)
(\.)
([a-z]{2,4})
''', re.VERBOSE | re.IGNORECASE)

phoneregex = re.compile(r'''
(\+\d)?
(-)?
(\d{3}|\(\d{3}\))?
(\.|-|\s)?
(\d{3})
(\.|-|\s)
(\d{4})
''', re.VERBOSE)

with open(filename, 'r') as filename:
    filedata = filename.read()
    emailmo = emailregex.findall(filedata)
    phonemo = phoneregex.findall(filedata)

print("Emails: \n")
for email in emailmo:
    for group in email:
        print(group, end='')
    print()

print()

print("Phone numbers: \n")
for pn in phonemo:
    for group in pn:
        print(group, end='')
    print()


texts:
There are both a simple byte endian (little and big) order swapper and its testbench. A data stream inputs to the module and is converted to the other endianness by computational logic.
byte_order_swap.v
`timescale 1ns / 1ps

module byte_order_swap #
(
    parameter integer DATA_WIDTH = 32
)
(
    input wire [DATA_WIDTH - 1 : 0] data_i,
    input wire [DATA_WIDTH - 1 : 0] data_o
);
    localparam integer DATA_BYTE_NUMBER = DATA_WIDTH / 8;
    localparam integer DEC_DATA_WIDTH   = DATA_WIDTH - 1;

    generate
        genvar i;
        if (0 == (DATA_WIDTH % 4)) begin
            for(i = 0; i < DATA_BYTE_NUMBER; i = i + 1) begin
                assign data_o[(i * 8) +: 8] = data_i[(DEC_DATA_WIDTH - i * 8)  -: 8];
            end
        end
        else begin
            assign data_o = {DATA_WIDTH{1'h0}};
        end
    endgenerate

endmodule

byte_order_swap_tb.v
`timescale 1ns / 1ps

module byte_order_swap_tb;

    localparam integer              DATA_WIDTH          = 32;
    localparam integer              CLOCK_PERIOD        = 100;
    localparam integer              ITERATION_NUMBER    = 1000;
    localparam [DATA_WIDTH - 1 : 0] COUNTER_START_VALUE = 32'hAABB1122;

    wire [DATA_WIDTH - 1 : 0] counter_swap_value;

    reg                      clk;
    reg [DATA_WIDTH - 1 : 0] counter_dir_value;

    byte_order_swap #
    (
        .DATA_WIDTH (DATA_WIDTH)
    )
    byte_order_swap_dut
    (
        .data_i (counter_dir_value),
        .data_o (counter_swap_value)
    );

    initial begin
        clk = 1'h0;

        forever begin
            #( CLOCK_PERIOD / 2 ) clk = !clk;
        end
    end

    initial begin
        counter_dir_value <= COUNTER_START_VALUE;

        repeat(ITERATION_NUMBER) begin
            @(posedge clk);
            counter_dir_value <= counter_dir_value + 1'h1;
        end
    end

    task check_swap;
    begin
        repeat(ITERATION_NUMBER) begin
            @(posedge clk);
            $display("A direction value:  %h -> the swap value: %h",counter_dir_value, counter_swap_value, $time);
        end
    end
    endtask

    initial begin

        check_swap;

        $stop();
    end

endmodule


texts: MySQL data fetching without page refresh

texts:
I've recently finished a prototype for a little Raspberry Pi website. The main page of the site displays current users found in the room (through bluetooth). I wanted this list updated regularly from data in a MySQL table, so no refresh is needed. When someone walks into or out of the room, the webpage shows almost instantly.

This is the solution I created:

index.html

Present:

Absent:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

var timer = setInterval(listLoad, 1000);

function listLoad(){
    $(function(){
       $("#list1").load("herelist.php");
       $("#list2").load("notherelist.php");
    });
}
</script>

herelist.php

<!DOCTYPE html>

<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "xxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT firstname, lastname FROM room_Data WHERE attendance = 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
     echo("
")
     while($row = $result->fetch_assoc()) {
         echo ("

". $row["firstname"]. " " . $row["lastname"] . "

");
 }
     echo("
");
} else {
     echo ("");
}

$conn->close();
?>

notherelist.php

Same as herelist.php, just the where clause is = 0 instead of = 1

This project isn't for some major production scale, which is why I don't really mind hitting my MySQL server every second requesting a read. I actually like this solution a lot since it was my first time ever injecting PHP through jQuery and I thought it was a neat idea.

Is this a good solution for a personal project/school project? Or, is there something I should look into to improve this?


texts:
Today i had discussion with my colleague about casting.

Our case:
We have root class

abstract class RootFoo<R extends RooFoo> {
   ...
   abstract R getThis();
}

and we implement method getThis in subclasses.

To save (in my opinion) unnecessary implementation getThis method in every subclass i showed my solution:

abstract class RootFoo<R extends RooFoo> {
   ...
   R getThis() {
       return (R) this;
   }
}

Could you help me understand why my idea is wrong?


texts: Using QSqlQuery::bindValue() for variable number of placeholders

texts:
I am familiar with the simple use of QSqlQuery::prepare() and QSqlQuery::bindValue() as in:

QSqlQuery query;
query.prepare("SELECT name, address FROM members WHERE id = :id");
query.bindValue(":id", member_id);
query.exec();

In this scenario I show a list of people (members) to the user, all with a check-box in front. The user can simply check which members to delete.
So now, the number of :id are variable.

Currently, I solve this issue in quite a untidy fashion. All the id's checked people will be put in an array of integers called checked_items_ids and then I simply for-loop that array:

QString prepare_query = QString("DELETE FROM members WHERE id = ").append(checked_items_ids[0]);

for(int i = 1; i < checked_items_ids.count(); i++)
    prepare_query.append(QString(" OR id = %1").arg(checked_items_ids[i]));

QSqlQuery query(prepare_query);
query.exec();

Is there a 'tidier' way to do this? Using bindValue() or anything that I might be overlooking?


texts:
Background

In C++ unlike other OOP languages, we do not have a Base Class from where All Classes are derived. I understand in MFC and pre STL, some Compilers did had a similar model, so lets leave it out of the discussion and focus on what the standard provides.

In C++11, auto was introduced to derive the type from rvalue just another way of type deduction of templates. This was a huge relief when one has to write long list of types with all template parameters.

Using Naked Pointers were prone to errors so Smart Pointers were introduced as a remedy for the unavoidable evil.

Use Case

I have a function which should return something that would indicate Null Object when no data was found or if it found needs to return the data. I would like to know, if C++11 has an elegant way of writing the below code, considering, the template types are painful to read.

Code

std::unique_ptr<std::tuple<tstring, int, tstring> > CCOMErrorHandler::PopError()
    {
    unique_ptr<std::tuple<tstring, int, tstring> > error = nullptr;
    if (!m_lstErrors.empty())
        {
        error = std::unique_ptr<std::tuple<tstring, int, tstring> >(new std::tuple<tstring, int, tstring>(m_lstErrors.front()));
        if (error)
            {
            m_lstErrors.pop_front();
            }
        }
    return(error);
    }

One option is to use a typedef or macro replacement, but generally am not a big FAN as that keeps polluting namespace though you may have to use to few times in your code often only once.


texts:
Q1. Can this code be simplified/ made more efficient?

Q2. Why does the following code have to be indented in the way that it is?
used.append(guess) and so_far = new

Q3. Out of interest, is there a way to print the hangman figure once and just replace the previous figure, to avoid mass text/ reloading in the Python Shell?

The Following code has been slightly adapted from Python Programming for the absolute beginner - Hangman Game

#Python 3.4.3, MAC OSX (Latest)
#Hangman Game

import random
from time import sleep

HANGMAN = (
"""
 ------
 |    |
 |
 |
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |   -+-
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |    |
 |   |
 |   |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |    |
 |   | |
 |   | |
 |
----------
""")

WORDS = ("APPLE", "ORACLE", "MIMO", "TESLA")
word = random.choice(WORDS)
POSITIVE_SAYINGS = ("Well done!", "Awesome!", "You Legend!")
MAX_WRONG = len(word) - 1
so_far = ("-") * len(word)
used = []
wrong = 0

print("\t \t Welcome to Hangman!")
print()
input("Press Enter to START: ")

while wrong < MAX_WRONG and so_far != word:
    print()
    print(HANGMAN[wrong])
    print("Word so far: ", so_far)
    print("Letters used: ", used)

    guess = input("Guess a letter: ").upper()
    sleep(1) # Time delay - allows userfriendly reading
    print()

    while guess in used:
        print("Try again... You've already used this letter")
        guess = input("Guess a letter: ").upper()
        sleep(1)
        print()
    used.append(guess)

    if guess in word:
        print(random.choice(POSITIVE_SAYINGS),"...Updating word so far...")

        new = ""
        for i in range(len(word)):
            if guess == word[i]:
                new += guess

            else:
                new += so_far[i]
        so_far = new

    else:
        print("INCORRECT! Try again!")
        wrong += 1

print("Calculating result...")
sleep(1)
if wrong == MAX_WRONG:
    print("UNLUCKY! Better luck next time!")

else:
    print("WINNER! Congratulations!")

print()
print()
input("Press Enter to Leave: ")


texts: Convert all CSV files in a given directory to JSON using Python

texts:
I am attempting to convert all files with the csv extension in a given directory to json with this python script.

I am wondering if there is a better and more efficient way to do this?

Here is my code:

import csv
import json
import glob
import os

for filename in glob.glob('//path/to/file/*.csv'):
    csvfile = os.path.splitext(filename)[0]
    jsonfile = csvfile + '.json'

    with open(csvfile+'.csv') as f:
        reader = csv.DictReader(f)
        rows = list(reader)

    with open(jsonfile, 'w') as f:
        json.dump(rows, f)

EDIT:

Here is the sample input:

Here is the sample output:

[{
"username": "lanky",
"user_id": "4",
"firstname": "Joan",
"middlename": "Agetha",
"lastname": "Lanke",
"age": "36",
"usertype": "admin",
"email": "lanke.joan.wind@gmail.com"
}, {
"username": "masp",
"user_id": "56",
"firstname": "Mark",
"middlename": "Patrick",
"lastname": "Aspir",
"age": "25",
"usertype": "member",
"email": "aspirman@gmail.com"
}]


texts: Optimizing a c# program that creates 2 dictionaries and searches both for a matching value

texts:
I have 2 Dictionaries. I am trying to optimize this code to run as fast as possible.

This is for solving Shanks Baby Step Giant Step Algorithm
Algorithm:

Given b = a^x (mod p)
First choose n, such that n^2 >= p-1
Then create 2 lists:
    1. a^j (mod p) for 0 <= j < n
    2. b*(a(inverse)^n)^k for 0 <= k < n
Finally look for a match between the 2 lists.

public static BigInteger modInverse(BigInteger a, BigInteger n)
{
    BigInteger i = n, v = 0, d = 1;
    while (a > 0)
    {
        BigInteger t = i / a, x = a;
        a = i % x;
        i = x;
        x = d;
        d = v - t * x;
        v = x;
    }
    v %= n;
    if (v < 0) v = (v + n) % n;
    return v;
}

static int Main()
{
    BigInteger r = 92327518017225,
               rg,
               temp,
               two=2,
               tm,
               n = ((BigInteger)Math.Sqrt(247457076132467-1))+1,
               mod = 247457076132467;
    Dictionary<int, BigInteger> b = new Dictionary<int, BigInteger>();
    Dictionary<int, BigInteger> g = new Dictionary<int, BigInteger>();
    temp = modInverse(two, mod);
    temp = BigInteger.ModPow(temp, n, mod);
    for (int j = 0; (BigInteger)j < n; j++)
    {
        rg = r * BigInteger.ModPow(temp, j, mod);
        g.Add(j, rg);
    }
    for (int i = 0; (BigInteger)i < n ; i++)
    {
        tm = BigInteger.ModPow(2, i, mod);
        foreach (KeyValuePair<int, BigInteger> d in g)
        {
            if (d.Value.Equals(tm))
            {
                Console.WriteLine("j={0}   B*t^j(mod m) = {1}",d.Key,d.Value);
                Console.WriteLine("a^"+i+" = "+tm);
            }
        }
        b.Add(i,tm);
    }
    Console.ReadKey();
    return 0;
}


texts: Checking the status of a website by hitting a PHP script

texts:
I currently have a system which loops through a bunch of my website domains and checks their status and sends me a notification letting me know if they are up or down. The stripped down version of the relay code is below, I've removed the email/DB update code etc.

It pings a transponder (a file on the client website server) which returns 'SUCCESS' or whatever the error it has encountered and returns that as a string.

function checkStatus($domain){
  $statusArray = array();

  $url = $domain . '/transponder.php';

  $statusArray['transponder_response'] = file_get_contents($url);

  if($statusArray['transponder_response'] == 'SUCCESS'){
    //all is well
  }else{
    //all is not well
    $statusArray['transponder_code'] = get_headers($url, 1);
    //send code and response via email to admin
  }

  return $statusArray;
}

The transponder code is such:

$dbInfo['host'] = '';
$dbInfo['dbname'] = '';
$dbInfo['user'] = '';
$dbInfo['pass'] = '';

$link = mysqli_connect($dbInfo['host'], $dbInfo['user'], $dbInfo['pass'], $dbInfo['dbname']);

if(mysqli_connect_errno()){
  printf('Connect failed: %s\n', mysqli_connect_error());
  exit();
}

if($result = mysqli_query($link, 'SELECT 1')){
  if(mysqli_num_rows($result)) echo 'SUCCESS';
  mysqli_free_result($result);
}

mysqli_close($link);

A 'SUCCESS' response means that the site domain is resolving, PHP is working and DB is working.

Can anyone point me in a direction to make this more accurate and effective for site monitoring?


texts:
This piece of code works fine. But I'm wondering if it can be done in a more efficient way. More specifically, this part (*(s1 + i)) if it possible to force it to sequence through entire array character by character via pointer, for example, *s1++.

My task to do this function compareStrings without index array []:

int  compareStrings(const char  *s1, const char  *s2)
{
    int i = 0, answer;
    //  i - to sequence through array of characters
    // pointer to character string1 and character string2
    while (*(s1 + i) == *(s2 + i) && *(s1 + i) != '\0'&& *(s2 + i) != '\0')
    {
        i++;
    }

    if ( *(s1 + i) < *(s2 + i) )
        answer = -1;               /* s1 < s2  */
    else if ( *(s1 + i) == *(s2 + i) )
            answer = 0;                 /* s1 == s2 */
        else
            answer = 1;                 /* s1 > s2  */

        return answer;

But I want to change it to s1++ and s2++ instead of *(s1 + i) and *(s2 + i). I've tried to implement this idea with pining an extra pointer to the beginning but I've failed.

int  compareStrings(const char  *s1, const char  *s2)
{
  int answer;
  char **i = s1, **j = s2;
  // i to sequence through array of characters
  while (*(i++) == *(j++) && *(i++) != '\0'&& *(j++) != '\0');

  if (*i < *j)
      answer = -1;               /* s1 < s2  */
  else if (*i == *j)
      answer = 0;                 /* s1 == s2 */
  else
      answer = 1;                 /* s1 > s2  */

  return answer;
}


texts: Counting primes in a range whose digits are all prime

texts:
Codewars Kata: Given integers a and b, count all primes p where a ≤ p < b and the digits of p are all prime. b may be as large as 107.

To start with, I hardcoded all valid 1903 primes in \$[1, 10^7]\$ that can be formed from digits \$\{2, 3, 5, 7\}\$ and stored it in a list. Then I use binary search to locate the indexes corresponding to the given bounds, then return the difference of these indexes + 1, and my code times out. That is frankly baffling to me. Like I can't even coherently theorise why the program would be slow. All the heavy duty computation is handled by the binary search which is logarithmic time, and is called only a few times and on a 1903 element list (Also, the binary search function completes 1000 searches of 200,000 element lists in 228.67s in another kata, so I don't think I implemented it poorly).

My Code

def xbinsearch(pred, lst, *extras, type = "min", default = None):
    low, hi, best = 0, len(lst)-1, default
    while low <= hi:
        mid = (low+hi)//2
        p = pred(mid, lst, *extras)
        if p[0]:    #The current element satisfies the given predicate.
            if type == "min":
                if best == default or lst[mid] < lst[best]: best = mid
                hi = mid-1
            elif type == "max":
                if best == default or lst[mid] > lst[best]: best = mid
                low = mid+1
        elif p[1] == 1:     #For all `x` > `lst[mid]` not `P(x)`.
            hi = mid - 1
        elif p[1] == -1:    #For all `x` < `lst[mid]` not `P(x)`.
            low = mid + 1
    return best

def pred_a(idx, lst, *extras):
    tpl, val = [None, None], lst[idx],
    if extras:  a, b = extras[0], extras[1]
    tpl[0] = a <= val < b
    if val > b: tpl[1] = 1
    elif val < a:   tpl[1] = -1
    return tuple(tpl)

def get_total_primes(a, b):
    low, hi = xbinsearch(pred_a, primes, a, b), xbinsearch(pred_a, primes, a, b, type="max")
    return hi + 1 - low


texts: Rewriting nested for loops to give better formatted output

texts:
The following is code from a university practical I am doing. It reads in a txt file of twenty clients, whose information is stored in the txt file like this:

Sophia Candappa     F 23 00011

As per my lecturer's instructions, I have stored this information in a class called Client (although I know an ArrayList would be better I can't use it).
The code below is a method that is used to compare all the clients to one another and determine if they are a match. They are a match if they are all of the following:

Opposite sex
Age within five years of one another
They have three interests in common

The latter is determined by the string "00011" in the example above. If the clients share the number "1" at the same place in the string on three or more occasions, then the third condition is satisfied.

My code works perfectly and outputs the desired result. However, I want to ask two questions.

Is it as efficient as it could be (without ArrayLists)? I had considered separating out all the if/else statements into separate methods, but decided against it as I thought it wouldn't reduce any of the actual loops.
How can I change the output slightly. Currently, if a client is matched it displays "[Client Name] is compatible with" then it takes a new line and outputs all the clients who are matched. I would like to change it so that if the client has just one match, it says "Client Name is compatible with"..., but if the client has two or more clients it says "Client Name is compatible with the following [two/three/four] clients...

I have tried doing the latter, but I always mess up the formatting. Thanks in advance for any help that can be offered.

public static void matchClients(Client[] clientDetails)
{
    boolean anyMatch;
    int count;
    for (int b = 0; b < numberOfClients; b++)
    {
        anyMatch = false;
        count = 0;
        for (int c = 0; c < numberOfClients; c++)
        {
            if (clientDetails[b].getClientGender()!=clientDetails[c].getClientGender())
            {
                if (Math.abs(clientDetails[b].getClientAge() - clientDetails[c].getClientAge()) <= 5)
                {
                    int interests = 0;

                    String clientOneInterests = clientDetails[b].getClientInterests();
                    String clientTwoInterests = clientDetails[c].getClientInterests();

                    int interestNumber = 0;
                    while (interestNumber < clientOneInterests.length())
                    {
                        if ((clientOneInterests.charAt(interestNumber) == clientTwoInterests.charAt(interestNumber))
                                && (clientOneInterests.charAt(interestNumber) == '1' ))
                            interests++;
                        interestNumber++;
                    }

                    if (interests >= 3)
                    {
                        anyMatch = true;
                        if (count == 0)
                        {
                            System.out.println(clientDetails[b].getClientName() + "is compatible with the following client(s)");
                            System.out.println("\t" + clientDetails[c].getClientName());
                        }
                        else
                        {
                            System.out.println("\t" + clientDetails[c].getClientName());
                        }
                        count++;
                    }
                    interests = 0;
                }
            }
        }
        if (anyMatch == false)
            System.out.println(clientDetails[b].getClientName() + "is not compatible with any client.");
        System.out.println("");
    }
}


texts: Better way to write this code in functional manner using map and reduce?

texts:
I have an array of items on which I have to perform 2 tasks:

Applying  a function on the array item
Checking if the value is true or false.

The functional approach to solving this would be

var result = arr.map(function(item){return some_action(item);}).filter(function(item){return other_action(item) == true;});

But here the array arr is traversed twice in comparison to

var result = [];
arr.forEach(function(item){
    var x = other_action(some_action(item));
    if (x)
        result.push(x);
});

Isn't the functional approach bad in this case or am I not using map and filter the right way?


texts: Detect that a class is marked by a custom annotation in Spring

texts:
I would like to enable application behaviour based on the presence of a custom annotation that marks the configuration class (normally named something like ApplicationConfig.class) in a Spring 4 application.

This feature functions in the same way as do @EnableCache, @EnableRepositories etc, in the sense that adding these annotations adds behaviour to the application.

The following code shows the way I have decided to implement the feature. It detects and analyses the classes that are loaded by Spring at application startup and fires an event if it determines that one of those classes is annotated with the specified custom annotation. This code works as designed however the use of reflection feels clumsy and I would like to seek the advice of other developers who may have solved a similar problem in a more elegant/different manner.

The custom annotation class.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceRegistration {
    boolean enabled() default true;
}

The configuration class.

@ServiceRegistration(enabled = true)
@Configuration
@ComponentScan(basePackageClasses = Application.class, excludeFilters = @Filter({Controller.class, Configuration.class}))
@EnableJpaRepositories("com.package.repository")
class ApplicationConfig {

    @Bean
    public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setLocation(new ClassPathResource("/persistence.properties"));
        return ppc;
    }

}

The class that detects the presence of the annotation.

@Component
public class ServiceRegistrationEventListener {

    private static final String ANNOTATED_CLASSES = "annotatedClasses";

    @Autowired
    ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    ApplicationContext applicationContext;

    @EventListener
    void contextRefreshedEvent(ContextRefreshedEvent event) throws NoSuchFieldException, IllegalAccessException {

        ApplicationContext applicationContext = event.getApplicationContext();
        AnnotationConfigWebApplicationContext annotationContext = ((AnnotationConfigWebApplicationContext) applicationContext);
        for (Field field : annotationContext.getClass().getDeclaredFields()) {
            if (ANNOTATED_CLASSES.equals(field.getName())) {
                field.setAccessible(true);
                Object aContext = field.get(annotationContext);
                if (aContext instanceof Set) {
                    Set<Class<?>> classes = (Set<Class<?>>) aContext;
                    for (Class clazz : classes) {
                        for (Annotation annotation : clazz.getDeclaredAnnotations()) {
                            if (annotation.annotationType().isAssignableFrom(ServiceRegistration.class)) {
                                applicationEventPublisher.publishEvent(new RegistrationEvent(((ServiceRegistration) annotation).enabled()));
                            }
                        }
                    }
                }
            }
        }
    }

    class RegistrationEvent {

        private boolean enabled;

        public RegistrationEvent(boolean enabled) {
            this.enabled = enabled;
        }

        public boolean enabled() {
            return enabled;
        }

    }

}

Values set in the annotation e.g. @ServiceRegistration(enabled = true) are recovered and passed into the published event.

Any ideas on how to improve this code and especially ideas on completely different ways to achieve the same are welcome.


texts: Add "1" and overwrite the previous value

texts:
I have a cookie where a number is stored.
When I want to add "1" to the stored number and then overwrite it, I use this php code:

$temp = $_COOKIE['mycookie']++;
$_COOKIE['mycookie']=$temp;

Is it the best way to do that?


texts:
I've just tried my hand at Quicksort, and I seem to have gotten it working (thanks to Stack Overflow). However, is it "true" Quicksort? And is it decently written?

public static void sort(List<Integer> arr, int left, int right) {
        int i = left - 1;
        int j = right + 1;
        if (right - i == 0 || right - i == 1) return;
        int v = arr.get(right);

        for(;;) {
            while(arr.get(++i) < v);
            while(v < arr.get(--j) && j != 0)
                if(j == 1)break;
            if(i >= j)break;

            Collections.swap(arr, i, j);
        }
        Collections.swap(arr, i, right);

        sort(arr, left, i - 1);
        sort(arr, i, right);
}

I know I should use a regular array (int[]) for speed, but we can ignore that for now.


texts:
I did an application that returns you quarters, dimes, nickels and pennies after you give the cost of the product and the money you gave. Can this be done any better? This seems like kind of messed up, and it got some repeated code parts.

Console.Write("Cost of the product -> ");
decimal costProduct = decimal.Parse(Console.ReadLine());

Console.Write("Money given -> ");
decimal moneyGiven = decimal.Parse(Console.ReadLine());

decimal change = moneyGiven - costProduct;

decimal quarters = 0, dimes = 0, nickels = 0, pennies = 0;

while(change >= 0.25m)
{
    quarters = Math.Truncate((change / 0.25m));
    change = change % 0.25m;
}

while(change >= 0.10m)
{
    dimes = Math.Truncate((change / 0.10m));
    change = change % 0.10m;
}

while (change >= 0.05m)
{
    nickels = Math.Truncate((change / 0.05m));
    change = change % 0.05m;
}

while (change >= 0.01m)
{
    pennies = Math.Truncate((change / 0.01m));
    change = change % 0.01m;
}

Console.WriteLine("{0} quarters, {1} dimes, {2} nickels, {3} pennies", quarters,
    dimes, nickels, pennies);


texts: InternedString as alternative to regular String

texts:
I need to use large strings as a dictionary keys, and I want to optimize the repetitive GetHashCode() and Equals() calls in it.

The number of keys will be quite small (<1000), but each string length will be very big (it's generated SQL queries cache), and I expect a lot of hot lookups.

My idea is to make sure that each wrapped string is interned, so that we can rely on the string references of the same strings to be always the same:

public sealed class InternedString : IEquatable<InternedString>
{
    public InternedString(string s) => String = string.Intern(s);

    public string String { get; }

    public override bool Equals(object obj) => String.Equals(obj);

    public bool Equals(InternedString other) => String.Equals(other?.String);

    public override int GetHashCode() => RuntimeHelpers.GetHashCode(String);

    public static bool operator ==(InternedString l, InternedString r) =>
        l?.String == r?.String;

    public static bool operator !=(InternedString l, InternedString r) => !(l == r);
}

Can you review this class, with special attention to safety?

UPDATE

You can check the final code and benchmarks here: https://github.com/astef/InternedString

Usage:

// O(n) operation happens only here, so we want to re-use this object
var iString = new InternedString("typically_a_very_long_string_key");

// now any call to `GetHashCode()` and `Equals(...)` will run in a constant time
mySet.Add(iString);


texts: Retrieving a user's password for verification

texts:
I am working on a log in form. Basically, my code searches for a user name, then retrieves the hashed password that is related to that account. It then converts that string hashed password then converts it to its real value. But my issue here is that it is messy.

 private void userVerification() {

            //Instantiate Db
            DataClasses1DataContext myDbContext = new DataClasses1DataContext(dbPath);

            //Search for uservar search

            var hasher = new Hasher();
            //by default salt size is 4
            hasher.SaltSize = 16;

            var encryptedPassword = hasher.Encrypt(txtPassword.Text);

            var searchUser = from user in myDbContext.Accounts
                             where user.accnt_User == txtUser.Text
                             select user.accnt_Pass;

            //Retrieves the first result.
            var password = searchUser.FirstOrDefault();

            //Check if there's a result or match
            if (searchUser.Count() != 0)
            {
                bool areEqual = hasher.CompareStringToHash(txtPassword.Text, password);

                if (areEqual = true)
                {
                    MessageBox.Show("CORRECT!");
                }
                else {
                    MessageBox.Show("Wrong password!");
                }
            }
            else {
                MessageBox.Show("No Such User in the database");
            }
        }


texts: React Hooks - Did I write this correctly?

texts:
I am brand new to writing hooks and I am having a little trouble getting my head wrapped around it.  Initially, I wanted to write this with one event listener that passed the event and a separate param to distinguish itself from the other incoming arguments.

With hooks, I was confused as to how I should pass a separate param and even more confused on how I would go about putting the logic into deciphering what each argument was.

So... Basically, I am calling two arrow functions in render and using separate arguments to dictate what iconType the onMouseOver is effecting.

I guess my question is, is this an acceptable way to write react hooks?  This is my first component with any kind of state in my project (a simple navbar).  I wan to make sure I am on the right path.

import React, { useState, useEffect } from 'react';
import '../styles/HomeNavBar.css';
import logo from '../styles/images/pulse_logo.png' // relative path to image

export default function HomeNavBar() {

 const [isTrue, handleMouseOver] = useState(false)
 const [iconType, setArg] = useState('')

 return (

 handleMouseOver(true), () => setArg('services')} onMouseLeave = {() => handleMouseOver(false), () => setArg('')} className="link-holder">
            {isTrue === false && iconType !== 'services' ?
Services
 :
Services
}

 handleMouseOver(true), () => setArg('careers')} onMouseLeave = {() => handleMouseOver(false), () => setArg('')} className="link-holder">
          {isTrue === false && iconType !== 'careers'  ?
Careers
 :
Careers
}

 handleMouseOver(true), () => setArg('blog')} onMouseLeave = {() => handleMouseOver(false), () => setArg('')} className="link-holder">
            {isTrue === false && iconType !== 'blog'  ?
Blog
 :
Blog
}

About

  );
}
````


texts: Spreading out model across multiple classes a good idea?

texts:
Background

My project performs software application management; it covers in-app purchasing, product provisioning, account management, etc. I've recently been tasked to add a cost reporting component.

Code

On the code level, I've spread out my model into a few classes that represent categories or interest areas, each requiring specific dependencies. Here's a rough outline:

models/base.class.php

namespace Models;

class Base
{
    protected $db; // PDO

    public function __construct(PDO $db)
    {
    }

    // helper functions such as data mappers for one or multiple rows
}

models/ordermodel.class.php

namespace Models;

class OrderModel extends Base
{
    protected $gateway; // payment gateway to handle purchases

    public function __construct(PDO $db, Gateway $gateway)
    {
        parent::__construct($db);
        $this->gateway = $gateway;
    }

    // methods for purchase, refund, subscription cancellation, etc.
    public function updateInstallDetails(...);

    public function refundPayment(...);
}

models/provisionmodel.class.php

namespace Models;

class ProvisionModel extends Base
{
    protected $account; // user account to "anchor" queries against

    public function __construct(PDO $db, Entities\Account $account)
    {
        parent::__construct($db);
        $this->account = $account;
    }

    // this method gets called when a software update took place
    // it's called (indirectly) from a controller class
    private function updateInstallDetails(...);
}

The individual classes are accessed via a factory:

class Model
{
    private static $repository = array();

    /**
     * Generic instance loader
     *
     * @param $name string
     * @param $fn callback generates the object instance
     */
    private static function getModelInstance($name, $fn)
    {
        if (!isset(self::$repository[$name])) {
            self::$repository[$name] = $fn();
        }
        return self::$repository[$name];
    }

    public static function getOrderModel($gateway = null)
    {
        // TODO pass payment gateway object
        return self::getModelInstance(__FUNCTION__, function() use ($gateway) {
            if ($gateway) {
                $gateway = GatewayFactory::load($gateway);
            }
            return new Models\OrderModel(SiteConfig::getDefaultDatabase(), $gateway);
        });
    }
}

Problem

The cost reporting component cross-cuts two main areas of the model, i.e. purchases, refunds and provisioning (shown above). Purchases and refunds of any product are recorded for royalty payments and provisioning keeps track of software updates (between versions there may be added or removed royalties).

My possible solutions

So I have a few options:

Make both my classes aware of the reporting unit; this means extending the constructor and what not.
Apply Decorator pattern to "intercept" method calls.
Apply ObserverMediator pattern; each class will emit "interesting" events and the reporting unit will listen for them and make the appropriate changes to the database tables.

Questions

Does it make sense to spread out my model into separate classes in the first place? Would it make more sense to make one big class that encompasses all my application logic?

ObserverMediator pattern has its pros and cons; the advantage is that you can easily decouple units from each other, but the downside is that it's indeed decoupled. Are there other cons?

Is there another pattern I could apply to crack this? Is there some other major issue with my code?


texts: Is there a better way to implement this Huffman Algorithm in Python?

texts:
I have written this implementation of Huffman coding. Please suggest ways to make this code better, i.e. more Pythonic.

from collections import Counter

#####################################################################

class Node(object):
  def __init__(self, pairs, frequency):
    self.pairs = pairs
    self.frequency = frequency

  def __repr__(self):
    return repr(self.pairs) + ", " + repr(self.frequency)

  def merge(self, other):
    total_frequency = self.frequency + other.frequency
    for p in self.pairs:
      p[1] = "1" + p[1]
    for p in other.pairs:
      p[1] = "0" + p[1]
    new_pairs = self.pairs + other.pairs
    return Node(new_pairs, total_frequency)

#####################################################################

def huffman_codes(s):
  frequency_table = Counter(s)
  initial_table = []
  for k, v in frequency_table.items():
    initial_table.append([k, v])
  initial_table = sorted(initial_table, key = lambda p : p[1])
  # print(initial_table)
  table = []
  for entry in initial_table:
    ch = entry[0]
    freq = entry[1]
    table.append(Node([[ch, ""]], freq))
  # print(table)
  while len(table) > 1:
    first_node = table.pop(0)
    second_node = table.pop(0)
    new_node = first_node.merge(second_node)
    table.append(new_node)
    table = sorted(table, key = lambda n : n.frequency)
    # print(table)
  return dict(map(lambda p: (p[0], p[1]), table[0].pairs))

#####################################################################

print(huffman_codes('yashaswita'))

Thanks


texts: Writing a recursive factorial function in x86-64

texts:
The following assembly program works to print the factorial of a number:
SYS_EXIT = 60
.globl _start
_start:
    # run 4! --> 4*3*2*1 = 24
    mov $4,  %edi
    call factorial
    mov %eax, %edi
    mov $SYS_EXIT, %eax
    syscall

.type factorial @function
factorial:

    # if it is the base case, return 1 and exit
    cmp $1, %edi
    jne _factorial
    mov $1, %eax
    ret

_factorial:
    # if not the base case, set up the stack frame
    push %rbp
    mov %rsp, %rbp

    push %rdi    # move the current value or n to the stack,
    dec %rdi     # so we can pop it later and multiple by the factorial(n-1) function
    call factorial
    pop %rbx
    mul %rbx    # multiples eax (return of factorial) by previoud rdi (n)

    # clean up the stack frame
    mov %rbp, %rsp
    pop %rbp
    ret

Here is an example output:

$ as factorial.s -o factorial.o && ld factorial.o -o factorial && ./factorial; echo $?
24

How does the program look? Any feedback would be greatly appreciated!


texts:
I'm a fanboy of the Boost library and I've used Boost's components extensively in my C++03 project. The team decided to merge several pieces of code including my project. I will get the C++14 environment, but I have to drop the Boost library, so I'd like to replace BOOST_SCOPE_EXIT with a modern C++ technique.

Here is SCOPE_EXIT's implementation, with a short example:

#include <cstdio>
#include <cstdlib>
#include <memory>

template <typename Lambda>
class ScopeGuard
{
public:
    ScopeGuard(const Lambda& func)
        : committed_(false), valid_(true), rollbackFunc_(func) {}

    ~ScopeGuard() noexcept
    {
        if (valid_ && !committed_)
            rollbackFunc_();
    }

    ScopeGuard(const ScopeGuard&) = delete;
    ScopeGuard& operator=(const ScopeGuard&) = delete;

    ScopeGuard(ScopeGuard&& other)
        : committed_(other.committed_), valid_(other.valid_), rollbackFunc_(other.rollbackFunc_)
    {
        other.valid_ = false;
    }

    ScopeGuard& operator=(ScopeGuard&& other)
    {
        committed_ = other.committed_;
        valid_ = other.valid_;
        rollbackFunc_ = other.rollbackFunc_;
        other.valid_ = false;
        return *this;
    }

    void commit() const { committed_ = true; }

private:
    mutable bool committed_;
    bool valid_;
    Lambda rollbackFunc_;
};

template <typename Lambda>
ScopeGuard<Lambda> makeScopeGuard(Lambda&& func)
{
    return ScopeGuard<Lambda>(func);
}

#define MY_CONCATENATE_NX(A, B) A ## B
#define MY_CONCATENATE(A, B) MY_CONCATENATE_NX(A, B)

#define SCOPE_EXIT(f) auto MY_CONCATENATE(EXIT, __LINE__) = makeScopeGuard(f);

int foo(const char*) noexcept;
bool bar(int) noexcept;
void baz(int) noexcept;

int main() {
    int f = foo("/dev/random");
    if (!f)
    {
        return EXIT_FAILURE;
    }
    SCOPE_EXIT([f](){ baz(f); })
    int b = 1;
    bar(b);
    // baz(f)

    return EXIT_SUCCESS;
}

Godbolt gcc 7.2 -std=c++14 -O2

VS2017 -W4 /EHsc /O2

gcc's assembly is pretty short, however MSVC's assembly is so long (about 70 lines) and I can't understand what's going on. (I am not familiar with the Windows environment.)

Did I miss something, or is it a bad optimization of MSVC?


texts: Let's read a random Goodreads book in an optimal way

texts:
I have made the following program to gather data on random books from Goodreads, via their random books feature.

import requests
import re

URL = "https://www.goodreads.com/book/random"

while True:
    html_text = requests.get(URL).text

    #   Rating Count
    bg_rating_count     = html_text.find("", bg_rating_count)
    rating_count        = int(html_text[bg_rating_count : end_rating_count].replace(',', ''))

    if rating_count >= 30:
        if "" in html_text:

            #   Title
            bg_title    = html_text.find("<meta property=\"og:title\" content=\"") + 35
            end_title   = html_text.find("\"/>", bg_title)
            title = html_text[bg_title : end_title].replace("&amp;", '&')
            title = re.sub(r'\((.*)\)','', title)

            #   Pages
            bg_pages    = html_text.find("") + 31
            end_pages   = html_text.find(" page", bg_pages)
            pages       = int(html_text[bg_pages : end_pages])

            #   Rating
            bg_rating   = html_text.find("") + 45
            end_rating  = html_text.find("</", bg_rating)
            rating      = float(html_text[bg_rating : end_rating])

            if pages != 0:
                print(title, pages, rating, sep='\t')

This is my first time working with anything of this sort, and I am still learning Python as I go. Here's a breakdown of what the code does (or, is intended to do):

This program gets the HTML code from a random book via the URL.
Finds the book's rating count by searching for a specific HTML tag. Removes any commas in the rating number before making sure it's an integer.
If the rating count is >= 30, it accepts it and continues to gather data. Otherwise it moves on and tries another random book.
If it passes the rating count test, it checks whether it has a listed number of pages. If it does, it continues to gather data. Otherwise it moves on and tries another random book.
If it passes the page count test, it then gathers the title. If the title has an ampersand HTML code &amp; it replaces it with the actual ampersand character &. As well, if the title contains text identifying a series, it removes the series text. Here's an example of what I'm talking about, where it says (The Hunger Games #1). I am new to regex, let me know if I am doing anything horrible.
It then actually gathers the page count along with making sure it's an integer, and the book's rating with making sure it's a float.
If the page count is not 0 (which is sometimes the case for ill-detailed books), it then prints out the relevant data in a tab-separated format that I can copy-paste for later.

I understand that this program goes on forever, and I intended it like that. This program is meant to be manually used, and I halt it when I am done.

Is multi-threading a good idea? How can I improve this code, both in terms of performance, readability, or code logic?


texts:
Well, I'm not going to use it everywhere, as jQuery exists, but still was interested in experience of creating own library. Here are first steps:

;(function() {
  window["_o"] = function(selector) {
    if (!selector) {
      throw new Error("Cannot create Object from " + selector);
    }

    var elems;

    if (selector instanceof HTMLElement) {
      elems = {
        "0": selector,
        length: 1
      };
    } else {
      elems = document.querySelectorAll(selector);
    }

    return elems.length ? new _o.fn(elems) : null;
  }

  _o.fn = function(elems) {
    var len = this.length = elems.length;
    for (var i = 0; i < len; i++) {
      this[i] = elems[i];
    }

    /***/
    /* general */

    this.eq = function(num) {
      var tmp = num;
      num = parseInt(num);
      if (isNaN(num))
        throw new Error(tmp + " is not a number!");

      return 0 <= num && num < elems.length ? _o(elems[num]) : null;
    };

    this.first = function(selector) {
      if (typeof selector === "string") {
        var elem = elems[0].querySelector(selector);
        return elem ? _o(elem) : null;
      }

      return _o(elems[0]);
    };

    /***/
    /* className features */

    this.addClass = function(className, f_condition) {
      f_condition = f_condition || function() {
        return true;
      };

      for (var i = 0; i < elems.length; i++) {
        if (f_condition(elems[i], i, elems)) {
          elems[i].classList.add(className);
        }
      }

      return this;
    };

    this.removeClass = function(className, f_condition) {
      f_condition = f_condition || function() {
        return true;
      };

      for (var i = 0; i < elems.length; i++) {
        if (f_condition(elems[i], i, elems)) {
          elems[i].classList.remove(className);
        }
      }

      return this;
    };

    this.toggleClass = function(className, f_condition) {
      f_condition = f_condition || function() {
        return true;
      };

      for (var i = 0; i < elems.length; i++) {
        if (f_condition(elems[i], i, elems)) {
          elems[i].classList.toggle(className);
        }
      }

      return this;
    };

    /***/
    /* show - hide */

    this.display = function(value, f_condition) {
      if (typeof value === "function") {
        f_condition = value;
        value = "block";
      } else {
        value = value || "block";
        f_condition = f_condition || function() {
          return true;
        };
      }

      for (var i = 0; i < elems.length; i++) {
        if (f_condition(elems[i], i, elems)) {
          elems[i].style.display = value;
        }
      }

      return this;
    };
  }
})();
.demo {
  width: 50px;
  height: 50px;
  margin: 5px;
  background: orange;
}

.blue {
  background: #045acf;
}

Any suggestions / hints?) Also, is it a good or bad practice to write a separate mini-library before the main code?


texts:
Edit: A second iteration of this problem here.

I need to provide a service (either a Windows Service or an Azure Worker Role) which will handle the parallel execution of jobs.  These jobs could be anything from importing data to compiling of reports, or to sending out mass notifications, etc.  They are generally long-running and are not suitable to run on the web server.

Important factors

The solution needs to be a very extensible and maintainable solution, as new job implementations will be created by developers all the time.
The execution of these jobs is to be abstracted away from the client code.  All developers need to do is to create the new job and add it to the job data source (database, MSMQ, Azure Queue, etc).

Solution

Deriving from AbstractJob and overriding the abstract Execute() method to provide implementation for the new job:

public abstract class AbstractJob
{
    public JobState State { get; protected set; }

    public AbstractJob()
    {
        State = JobState.New;
    }

    protected abstract bool Execute();

    public sealed void ExecuteJob()
    {
        State = JobState.Executing;

        try
        {
            if (Execute())
            {
                State = JobState.Successful;
            }
            else
            {
                State = JobState.Failed;
            }
        }
        catch (Exception)
        {
            State = JobState.FailedOnException;
        }
    }
}

public class TestJob : AbstractJob
{
    protected override bool Execute()
    {
        Debug.WriteLine("Test job!");
        return true;
    }
}

The following JobConsumer would reside on a Windows Service or Azure Worker Role.  IJobSource provides the consumer with jobs.  These could be from the database, a MSMQ, an Azure Queue, etc (I have left this implementation out).

Every 5 seconds (this can obviously be configurable), the JobConsumer executes new jobs when there are available cores.

public class JobConsumer
{
    public List<AbstractJob> Jobs { get; set; }

    public IJobSource JobSource { get; private set; }

    public int ParallelExecutionCount { get; set; }

    protected List<Task> Tasks { get; set; }

    public JobConsumer(IJobSource jobSource, int parallelExecutionCount)
    {
        JobSource = jobSource;
        ParallelExecutionCount = parallelExecutionCount;
    }

    public void StartConsumer()
    {
        Task.Factory.StartNew(() =>
        {
            TaskScheduler currentScheduler = TaskScheduler.Current;

            while (true)
            {
                int availableCores = ParallelExecutionCount - Tasks.Count();

                IEnumerable<AbstractJob> newJobs =
                    JobSource.ReadNewJobs().Take(availableCores);

                foreach (var job in newJobs)
                {
                    System.Threading.Tasks.Task task = null;

                    task = Task.Factory.StartNew(() =>
                    {
                        Tasks.Add(task);
                    }, CancellationToken.None,
                       TaskCreationOptions.None,
                       currentScheduler)
                    .ContinueWith(t =>
                    {
                        // Execute job on a new thread
                        job.ExecuteJob();
                    })
                    .ContinueWith(t =>
                    {
                        Tasks.Remove(task);
                    }, currentScheduler);
                }

                Thread.Sleep(5000);
            }
        });
    }
}

public interface IJobSource
{
    public IEnumerable<AbstractJob> ReadNewJobs();
}

Input, critique and suggestions very welcome!

EDIT:  I am using .NET 4.5


texts: Trim() every string in a JavaScript object?

texts:
We have a database with fixed width columns. The API is really simple and returns everything the database does with little to no actual processing. This results in some unnecessarily long strings in the model. The model has child objects who have grandchildren and can get quite large at times.

I've written this function to clean up a model right after it's received from the API and right before the rest of the client does anything with it:

function DeepTrim(obj) {
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (typeof obj[prop] == 'string') {
                obj[prop] = obj[prop].trim();
            } else if (typeof obj[prop] == 'object') {
                DeepTrim(obj[prop]);
            }
        }
    }
}

I know browsers don't really pay attention to consecutive spaces, but this is causing problems when we determine if a field has any valuable content. We can't simply check for a falsey from the string because being filled with spaces makes it just as true as it being filled with an address, phone numbers, or other meaningful data.

This seems to function properly for the few cases I've tried, but it's slow for large objects, especially in IE9 (the oldest browser we're supporting).

Performance is all I care about. It won't be running a thousand times a second, but it might get large, deep objects.  Is there any way to speed this up?


texts:
I want to count the occurrences of a multi line ASCII pattern within a file.

The pattern looks like this:

a1
b2
c3

The file I want to search looks like this:
(The _ represent whitespaces but I thought it's easier to understand with this notation)

_ _ _ a1
_ _ _ b2
_ _ _ c3  _ _ _ _ a1
a1_ _ _ _ _ _ _ _ b2  _ _ _ _ a1
_ _ _ _ _ _ _ _ _ c3  _ _ _ _ b2
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ c3

The desired output should be 3 in this case. I solved this with a bunch of loops and counting symbols till finding the first part of the pattern. Then checking if the second part hast the same count of numbers before to ensure the second part is underneath the first one and so on.

_ _ _ _ a1 _ _ _ a1
_ _ _ _ b2 _ _ b2 _
_ _ _ _ c3 _ _ _ c3

In this example there is only one valid pattern found since the parts of the second aren't exactly under each other.

The regarding code is as following:

import sys

def load_data(path):
    data = []
    try:
        fp = open(path, 'r')
        for f_line in fp:
            data.append(f_line.rstrip())

    finally:
            fp.close()
    return data

bug_path = 'data/bug.txt'
landscape_path = 'data/landscape.txt'

bug = load_data(bug_path)
landscape = load_data(landscape_path)

findings = [[] for x in landscape]

min_len_bug = min([len(x) for x in bug])

for cnt, l_line in enumerate(landscape):
    if len(l_line) < min_len_bug:
        continue
    for bCnt, bLine in enumerate(bug):
        findings[cnt] = [(bCnt, ind) for ind in range(len(l_line)) if l_line.startswith(bLine, ind)] + findings[cnt]

def bugInLine(line, bug_part, whitespace):
    for entry in line:
        if entry[0] == bug_part and entry[1] == whitespace:
            return True

complete_bugs_cnt = 0

for cnt, l_line in enumerate(findings):
    for found in l_line:
        if found[0] == 0 and len(findings) > (cnt + len(bug) - 1):
            check = 1
            for i in range(1, len(bug)):
                if bugInLine(findings[cnt + i], i, found[1]):
                    check = check + 1

            if check == len(bug):
                complete_bugs_cnt = complete_bugs_cnt + 1

print complete_bugs_cnt

Since this isn't the most elegant solution I'm wondering if there is a possibility to solve this problem by using some regex code and combine this with the re.findall()-method.

I'd highly appreciate any help.


texts:
//Program To Input Values Into An Array And Sort Them In Ascending Order
#include<stdio.h>
//Function To Print The Array Values
void print(int tab[],int n)
{
    int i;
    printf("The Values Are : \n");
    for(i=0;i<n;i++)
    {
        printf("%d ",tab[i]);
    }
        printf("\n");//Line Jumping For Better Output
}
//Function To Swap The Values In The Array
void swap(int* x,int* y)
{
    int temp=*x;
    *x=*y;
    *y=temp;
}
//Function To Sort The Values In The Array By Using Previous Function
void sort(int tab[],int n)
{
    int i,j;
    for(i=0;i<n-1;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(tab[i]>tab[j])
            {
                swap(&tab[i],&tab[j]);//Swaps The Value Of Index i With The Value Of Index j In The Array
            }
        }
    }
}
//Main Code
int main()
{
    int i,n,tab[100];
    printf("Give The Number Of Elements In The Array:");
    scanf("%d",&n);
    while(n<=0)
    {
    printf("The Number Of Elements MUST Be Superior To 0!\n");
    printf("Give The Number Of Elements In The Array:");
    scanf("%d",&n);
    }
    printf("Insert %d Values :\n",n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&tab[i]);
    }
    print(tab,n);//Prints The Values In The Array
    sort(tab,n);//Sorts The Values In The Array
    printf("SORTING....\n");
    print(tab,n);//Prints The Values In The Array
    return 0;
}


texts:
The following script is supposed to got through each server in the server list and check if there are users logged in. If there aren't, it supposed to disable logon using PSExec (essentially place it in maintenance mode). If there are users logged in, it will go through each of there sessions and log out those that have an idle time of greater than an hour.

Please let me know if this code can be considered production ready. I've excluded the primary functions for log off and only included the script I was not sure about.

$content = "H:\demo\computernames.txt"  #please input where the list of servers is found (in a txt doc please)
$input = "H:\demo\session\run11.csv"  #please input where you want the csv to be exported (this includes all the active and disconnected servers)
$export ='H:\demo\session\openservers.txt' #please input where you want to 'open servers' (no users) to be exported.
#and that does it. cheers!

if (Test-Path $input) {
    Clear-Content $input
}

$Servers = Get-Content "$content"
$openservers = @()
#THE LOOP THAT FILTERS THE SERVERS MENTIONED IN THE LIST ABOVE
foreach ($Server in $Servers) {
    #tests the connection to the server (general test for the entire server)
    if (-not (Test-Connection $Server -Count 1 -Quiet)) { continue }
    #if their are no users logged in (hence the count of zero), push that server name onto a txt doc
    if (-not (Convert-QueryToObjects $Server -ErrorAction SilentlyContinue)) {
        $openservers += $server
        $openservers | Out-File $export #**TXT EXPORT**#
      }
      #if there are users logged onto the server, make sure they are either in disc or active state and push all the session details onto a seperate csv
        else {
                Convert-QueryToObjects -Name $Server | Where-Object {
                    @('Disconnected','Active') -contains $_.SessionState
                       }|Export-Csv $input -NoTypeInformation -Append
                       # does the append so each time the content is kept (however, the issue of duplicate content arose (hence the fix above).
          }
    } #concludes the first foreach loop
#<--- the folllowing function works with PsExec(external program)
    $openservers = Get-Content "$export" #**TXT IMPORT**#
    #for each server in the server list, it will check to make sure its online (Again).
    foreach($openserver in $openservers){
        if(  Test-Connection -Cn $openserver -Quiet) {
        H:\PsTools\PsExec.exe \\$openserver change logon /enable # calls an external tool and passes it the
        }
    else {
       Write-Host("the server>> $openserver is NOT online") -ForegroundColor DarkYellow
    }
}

#THIS IMPORTS FROM THE EXPORTED FILE PATH#
        Import-Csv $input | Where-Object {
                ($_.SessionState -eq 'Disconnected') -or #if its disconnected or
                (($_.IdleTime -like "*:*") -and ($_.IdleTime -gt "00:59")) #idle time is over an hour, kindly do this:
                    } | ForEach-Object { #disconnect the session by using the server name and session ID
                             Disconnect-LoggedOnUser -ComputerName $_.ComputerName -Id $_.ID -Verbose
                }


texts: Convert "String" sqrt(#) into numerical value

texts:
I had to come up with a way to convert sqrt(#) into its actual numeric value because before I would have an array containing elements such as:

[sqrt(3), -sqrt(3), 1]

If I tried to multiply, I would get the error:

  Argument "-sqrt(3)" isn't numeric in multiplication (*)

Here is my work-around, but I think there's a better way. Any suggestions?

#!/usr/bin/perl
#perl Solver.pl

use strict;
use warnings;

my $roots = "Sqrt[3] ||-Sqrt[3] ||1";
my @rootList = split(/ \|\|/, $roots); # fill array with string's values separated by " ||"

# Convert any Sqrt numbers to numerical value
# (ex.) Sqrt[3] -> sqrt(3)
for $_ ( @rootList ){
    $_ =~ s/Sqrt\[/sqrt(/g; # Sqrt[ -> sqrt(
    $_ =~ s/\]/)/g; # ] -> )

    if( $_ =~ /-sqrt/ ){ # replace string of negative sqrt()
        my $temp = substr( $_, 6 ); # take "#)"
        $temp =~ s/\)//g; # remove ")"
        $_ = -1*sqrt( $temp );
    }
    elsif( $_ =~ /sqrt/ ){ # replace positive sqrt()
        my $temp = substr( $_, 5 );
        $temp =~ s/\)//g;
        $_ = sqrt( $temp );
    }
}

print "[@rootList]\n";


texts: Workaround for have 2 column with pseudo AUTO INCREMENT

texts:
This is the situation :
the table order has a column with ID AUTO INCREMENT but (there is always a but)
i can't use it because i don't want number order 1234567 after 5 years but i want 1/2014 , 1/2015 etc etc.
For doing this i have created this columns into the table :

ID AUTO INCREMENT <--- unique ID used for manage the order after the insert
numberorder INT <--- fake number of order showed at the user NOT unique
IDyear YEAR <--- the year for the order e.g. 2014 or 2015

For doing this i write this code before the query for insert a new order
and processed at the submit form :

$query_Recordset4 = "SELECT MAX(IDyear) AS maxyear FROM order";
$Recordset4 = $mysqli->query($query_Recordset4);
$row_Recordset4 = $Recordset4->fetch_assoc();
$maxyear = $row_Recordset4['maxyear'] ;
$thisyear = date("Y") ;

if ($maxyear === $thisyear) {
    $query_Recordset5 = "SELECT MAX(numberorder) FROM order WHERE IDyear=$thisyear ;";
    $Recordset5 = $mysqli->query($query_Recordset5);
    $row_Recordset5 = $Recordset5->fetch_assoc();
    $numberorder = $row_Recordset5['MAX(numberorder)'] + 1 ;
}
else {
    $numberorder = 1 ;
}

And then i use $numberorder for insert them into the table order in his column.

QUESTION REVIEW

Maybe my question was not clear written and now i try to add some elements.

Thit is what i have now into the table order :

|----------|-------------|--------|
|    ID    | numberorder | yearId |
|----------|-------------|--------|
!    1     |     1       |  2014  |
|----------|-------------|--------|
|    "     |     "       |    "   |  <---- more orders
|----------|-------------|--------|
|   500    |    500      |  2014  |  <---- last order year 2014
|----------|-------------|--------|

When the year change what i need is this :

|----------|-------------|--------|
|   501    |     1       |  2015  |  <---- first order year 2015 (2016,2017 etc etc)
|----------|-------------|--------|

Like a suggestion, my code has a concurrency problem.

Have a second table yearid with another AUTO_INCREMENT field
for take to them a unique ID for numberorder field is perfect solution but when the year finish i can't restarting the AUTO_INCREMENT at 1 because for security reason the TRUNCATE and DROP commands are not available for the user created for the connection.

The only way i see is create a new table each year e.g. yearid2015 for have ID = 1.


texts: Python script to convert hierarchical JSON to LaTeX itemize

texts:
I have the following JSON:

{
  "items": [
    {
      "item": "abc",
      "status": "ready"
    },
    {
      "item": "def",
      "status": "ready"
    },
    {
      "item": "ghi",
      "status": "done",
      "items": [
        {
          "item": "ABC",
          "status": "ready"
        },
        {
          "item": "DEF",
          "status": "ready"
        },
        {
          "item": "GHI",
          "status": "done"
        }
      ]
    }
  ]
}

which I would like to convert to:

\begin{itemize}
    \item abc\hfill{}ready
    \item def\hfill{}ready
    \item ghi\hfill{}done
      \begin{itemize}
      \item ABC\hfill{}ready
      \item DEF\hfill{}ready
      \item GHI\hfill{}done
      \end{itemize}
\end{itemize}

The items can be nested arbitrarily deep. I have the following Python code:

import json
import os

TAB = '  '
BEGIN = '\\begin{itemize}'
ITEM = '\\item {0}\\hfill{{}}{1}'
END = '\\end{itemize}'

def main(path):
    with open(os.path.join(path, 'test.json')) as data_file:
        data = json.load(data_file)
    print('\n'.join(convert(data)))

def convert(data):
    stack = [data['items'].__iter__()]
    yield (TAB * (len(stack) - 1)) + BEGIN
    while len(stack) > 0:
        iterator = stack[len(stack) - 1]
        try:
            current = iterator.next()
            yield (TAB * (len(stack) - 1)) + ITEM.format(current['item'], current['status'])
            try:
                stack.append(current['items'].__iter__())
                yield (TAB * (len(stack) - 1)) + BEGIN
            except KeyError:
                pass
        except StopIteration:
            yield (TAB * (len(stack) - 1)) + END
            stack.pop()

I am new to Python and am looking for suggestions for the code to be more idiomatic Python.


texts: HackerRank Binary search tree validation

texts:
From here:

def checkBST(root):
    prev_val = -1
    for node in in_order_sort(root):
        if node.data <= prev_val:
            return False
        prev_val = node.data
    return True

def in_order_sort(node):
    if node.left:
        yield from in_order_sort(node.left)
    yield node
    if node.right:
        yield from in_order_sort(node.right)

Looking for any suggestions on improving this. It's pretty concise.

The input data is constrained between \$0\$ and \$10^4\$ so I can "get away" with setting the initial value to -1. The input func name checkBST is also predefined.

It seems that short of knowing you can validate a binary tree via an in-order traversal this would get complicated, but knowing that makes it straightforward?


texts:
I made Tic Tac Toe in Python. Standard code review, please tell me ways to improve. I am very new to Python, so please do not criticize very roundabout ways. Thanks.
board = []
for x in range(3):
    board.append([' '] * 3)
def print_board(board):
    x = 1
    print('    A   B   C')
    print()
    dashes = 0
    for row in board:
        print(x, ' ', ' | '.join(row))
        if dashes <= 1:
            print(' ', ' -'*6)
            dashes += 1
        x += 1
def split(word):
    return [char for char in word]
print('This is Tic Tac Toe.')
print('Player 1 will be X and Player 2 will be O.')
win = False
while win != True:
    print()
    print_board(board)
    print()
    while True:
        p1 = input('Player 1, where would you like to place a X? ').lower()
        try:
            p1_col_let = split(p1)[0]
            p1_row = int(split(p1)[1])
            p1_col = int(ord(p1_col_let) - 96)
        except ValueError:
            print('Invalid format.')
        if board[p1_row - 1][p1_col - 1] != ' ':
            print('That spot is already taken.')
        else:
            break
    while True:
        p2 = input('Player 2, where would you like to place an O? ').lower()
        try:
            p2_col_let = split(p2)[0]
            p2_row = int(split(p2)[1])
            p2_col = int(ord(p2_col_let) - 96)
        except ValueError:
            print('Invalid format.')
        if board[p2_row - 1][p2_col - 1] != ' ' or p2_row == p1_row and p2_col == p1_col:
            print('That spot is already taken.')
        else:
            break
    board[p1_row - 1][p1_col - 1] = 'X'
    board[p2_row - 1][p2_col - 1] = 'O'
    a1 = board[0][0]
    a2 = board[1][0]
    a3 = board[2][0]
    b1 = board[0][1]
    b2 = board[1][1]
    b3 = board[2][1]
    c1 = board[0][2]
    c2 = board[1][2]
    c3 = board[2][2]
    if a1 == 'X' and a2 == 'X' and a3 == 'X' or b1 == 'X' and b2 == 'X' and b3 == 'X' or c1 == 'X' and c2 == 'X' and c3 == 'X' or a1 == 'X' and b1 == 'X' and c1 == 'X' or a2 == 'X' and b2 == 'X' and c2 == 'X' or a3 == 'X' or b3 == 'X' or c3 == 'X' or a1 == 'X' and b2 == 'X' and c3 == 'X' or c1 == 'X' and b2 == 'X' and a3 == 'X':
        print()
        print_board(board)
        print()
        print('Player 1 wins!')
        win = True
    if a1 == 'O' and  a2 == 'O' and a3 == 'O' or b1 == 'O' and b2 == 'O' and b3 == 'O' or c1 == 'O' and c2 == 'O' and c3 == 'O' or a1 == 'O' and b1 == 'O' and c1 == 'O' or a2 == 'O' and b2 == 'O' and c2 == 'O' or a3 == 'O' or b3 == 'O' or c3 == 'O' or a1 == 'O' and b2 == 'O' and c3 == 'O' or c1 == 'O' and b2 == 'O' and a3 == 'O':
        print()
        print_board(board)
        print()
        print('Player 2 wins!')
        win = True
    if a1 != ' ' and a2 != ' ' and a3 != ' ' and b1 != ' ' and b2 != ' ' and b3 != ' ' and c1 != ' ' and c2 != ' ' and c3 != ' ':
        print('It\'s a tie!')
        break


texts: Go functions to create a directory if it doesn't exist

texts:
Which of the 2 solutions is written better? Personally I prefer the one line method but it does make it slightly more difficult to debug.  Is perhaps doing it the long way first then refactoring to the second method once we know all is tested to be working.

Please note Environment var "FT_SOURCE" is set to "c:\filemover\"

Original solution...

func ensureDirold(dirName string) (string, error) {

        err := os.Mkdir(dirName, os.ModeDir)

        if err == nil || os.IsExist(err) {
            return dirName, nil
        } else {
            return dirName, err
        }
    }

Usage...

func OldWay()  {
    dir := os.Getenv("FT_SOURCE") //is set to c:\filemover
    fmt.Print(ensureDirold(dir))
    _, err := os.Create(dir + "myfile-old.txt")
    check(err)

}

Alternate Solution...

type strerr struct {
    str string
    err error
}

func ensureDirnew(dirName string) strerr {

    err := os.Mkdir(dirName, os.ModeDir)

    if err == nil || os.IsExist(err) {
        return strerr{
            str: dirName,
            err: nil,
        }
    } else {
        return strerr{
            str: dirName,
            err: err,
        }
    }
}

Usage...

func NewWay() {
    _, err := os.Create(ensureDirnew(os.Getenv("FT_SOURCE")).str + "myfile.txt")
    check(err)
}


texts: CharacterEscaper - further optimizable? Bugs?

texts:
I have been working on a character escaper for a production server that receives quite a few requests per second (sometimes in the range of 400).

We forward some "query" requests to apache Lucent/SOLR, and I need to escape characters.

Containing also feedback from programmers-stackexchange , the code below is the result.

Can anyone see any bugs or additional ways to optimize?

String query = "http://This+*is||a&&test(whatever!!!!!!)";
char[] queryCharArray = new char[query.length()*2];
char c;
int length = query.length();
int currentIndex = 0;
for (int i = 0; i < length; i++)
{
    c = query.charAt(i);
    if(mustBeEscaped[c]){
      if('&'==c || '|'==c){
        if(i+1 < length && query.charAt(i+1) == c){
            queryCharArray[currentIndex++] = '\\';
            queryCharArray[currentIndex++] = c;
            queryCharArray[currentIndex++] = c;
            i++;
        }
      }
      else{
        queryCharArray[currentIndex++] = '\\';
        queryCharArray[currentIndex++] = c;
      }
    }
    else{
        queryCharArray[currentIndex++] = c;
    }
}

query = new String(queryCharArray,0,currentIndex);

System.out.println("TEST="+query);

private static final boolean[] mustBeEscaped = new boolean[65536];
static{
mustBeEscaped[':']=  //
  for(char c: "\\?+-!(){}[]^\"~*&|".toCharArray()){
     mustBeEscaped[c]=true;
  }
}


texts:
I have a list of plans and a list of contacts, and I have to check whether contact.ProviderId matches plan.ProviderId. If they match I need to store in a contactUI the plan.Name.

Provider to plan is a 0..1-to-many relationship, and that's why I couldn't use the Dictionary I tried at first instance.

For retrieving the list of object I need to call the DB. So I want to avoid calling it more than needed.

I came up with this

var offeredPlans = new List<Tuple<int, string>>();
foreach (var plan in plans)
{
    // ....Some code...
    offeredPlans .Add(new Tuple<int, string>(providerId, plan.Name));
}

var compareTo = offeringPlans.ToLookup(pair => pair.Item1, pair => pair.Item2);

foreach(var contact in contacts)
{
    var plansAttachedTo = Check(providerId.Value, compareTo);

    foreach (var plan in plansAttachedTo)
    {
        // New contactUI with plan.Name as one of its properties
    }
}

Being

private static IEnumerable<string> Check(int providerId, ILookup<int, string> plans)
{
    return offeringPlans.Where(p => p.Key == providerId).SelectMany(p => p);
}

Is this terrible or does it make sense?

I've never used before these classes (Tuple, Lookup...)
I would like my code to be the clearest I can even it it's not the cleverest of the solution I can think of which is not this case for sure, actually I realize now I could have done some kind of SQL joins, right? (but I would like to know if someone can point any obvious error in the current code).

Edit

The code inside the loop is this one (in this case I don't even omit code as I'm not sure if it's possible what you suggest p.s.w.g). I am using reflection as only some of the classes that inherit from plan have the ProviderId property.

foreach (var plan in plans)
{
    var offeringDetail = new OfferingDetail();

    if (plan.GetType() == typeof (OwnedProductSummary))
    {
        var productSummary = plan as OwnedProductSummary;

        offeringDetail = _offeringBLL.GetById(productSummary.OfferingID);
    }

    if (plan.GetType() == typeof (OwnedServiceSummary))
    {
        var serviceSummary = plan as OwnedServiceSummary;

        offeringDetail = _offeringBLL.GetById(serviceSummary.OfferingID);
    }

    // For the other types of summary will be 0
    var providerId = offeringDetail.ProviderID;

    offeredPlans .Add(new Tuple<int, string>(providerId, plan.Name));
}


texts:
I finally managed to work with socket.io namespace stuff which I'm using for building a chat module. Here, employees of multiple organizations can join and vhat with other employees of the respective organization. What I'm doing at here is creating separate namespaces for each organization. So, it'll be easier for me to manage all employees of different organizations.

Here is my server side code:

var express = require('express'),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);

var nsp_1005 = io.of('/nsp_bucket_1005');
nsp_1005.on('connection', function(socket){
    console.log('someone connected to namespace bucket 1005');

    socket.on('addEmp', function(login_org_id, login_emp_id, login_emp_name){
        console.log('addEmp - Org_Id : '+login_org_id);
        console.log('addEmp - Emp_Id : '+login_emp_id);
        console.log('addEmp - Emp_Name : '+login_emp_name);
    });

    socket.on('disconnect', function(){
        console.log('Someone disconnected from namespace bucket 1005.');
    });
});

var nsp_1010 = io.of('/nsp_bucket_1010');
nsp_1010.on('connection', function(socket){
    console.log('someone connected to namespace bucket 1010');

    socket.on('addEmp', function(login_org_id, login_emp_id, login_emp_name){
        console.log('addEmp - Org_Id : '+login_org_id);
        console.log('addEmp - Emp_Id : '+login_emp_id);
        console.log('addEmp - Emp_Name : '+login_emp_name);
    });

    socket.on('disconnect', function(){
        console.log('Someone disconnected from namespace bucket 1010.');
    });
});

Those 1005, 1010 codes are Organization IDs. Sorry for the wired naming scheme. But, one thing right now I'm feeling the way I've made this code is not so good. Because I'm duplicating the code at the time of creating namespace for each organization. Can anyone suggest a better way to arrange this code?


texts:
Goal: extract methods/functions defined in module. This excludes:

Imports
Lambda methods
Magic methods
Builtin methods
Class methods
Classes
Non-original definitions (i.e. function assignments, alt_name = orig_fn)

My approach + test below. Any room for improvement, or false positives/negatives? (In particular I wonder if we can get away without typechecks, e.g. isinstance(method, types.LambdaType))

Code: live demo

import utils

def get_module_methods(module):
    def is_module_function(obj):
        return ('<function' in str(obj) and
                module.__name__ in getattr(obj, '__module__', ''))

    def not_lambda(obj):
        return not ('<lambda>' in getattr(obj, '__qualname__', ''))

    def not_magic(obj):
        s = getattr(obj, '__name__', '').split('__')
        return (len(s) < 2) or not (s[0] == s[-1] == '')

    def not_duplicate(name, obj):
        return name == getattr(obj, '__name__', '')

    def cond(name, obj):
        return (is_module_function(obj) and not_lambda(obj) and
                not_magic(obj) and not_duplicate(name, obj))

    objects = {name: getattr(module, name) for name in dir(module)}
    m_methods = {}

    for name, obj in objects.items():
        if cond(name, obj):
            m_methods[name] = obj
    return m_methods

mm = get_module_methods(utils)
_ = [print(k, '--', v) for k, v in mm.items()]

Test:

# utils.py
import random
import numpy as np
from inspect import getsource

def fn1(a, b=5):
  print("wrong animal", a, b)

class Dog():
  meow = fn1
  def __init__(self):
    pass

  def bark(self):
    print("WOOF")

d = Dog()
barker = d.bark
mewoer = d.meow
A = 5
arr = np.random.randn(100, 100)

def __getattr__(name):
  return getattr(random, name, None)

magic = __getattr__
duplicate = fn1
_builtin = str
lambd = lambda: 1

# main.py
import utils

# def get_module_methods(): ...

mm = get_module_methods(utils)
_ = [print(k, '--', v) for k, v in mm.items()]

fn1 -- <function fn1 at 0x7f00a7eb2820>

Edit: additional test case for a lambda surrogate:

import functools

def not_lambda():
    return 1
functools.wraps(lambda i: i)(not_lambda).__name__

Code in question and answer catch not_lambda as a lambda - false positive.


texts: Express.js handler to update user fields

texts:
I have an express handler which i thought was pretty simple, but CodeClimate flagged this method as having a Cognitive complexity of 6 (5 is the max by default without flagging something)

Curious how I could simplify this method to reduce Cognitive complexity.

function updateUser (req, res) {
  // Update any fields that were passed in.
  // Explicitly checking for undefined b/c passing null values should set them to null in the db
  if (req.body.firstName !== undefined) {
    req.user.firstName = req.body.firstName
  }

  if (req.body.lastName !== undefined) {
    req.user.lastName = req.body.lastName
  }

  if (req.body.email !== undefined) {
    req.user.email = req.body.email
  }

  if (req.body.phone !== undefined) {
    req.user.phone = req.body.phone
  }

  if (req.body.fax !== undefined) {
    req.user.fax = req.body.fax
  }

  if (req.body.notes !== undefined) {
    req.user.notes = req.body.notes
  }

  req.user.save()
    .then(user => {
      return res.status(HttpStatus.OK).send(user)
    })
    .catch(err => {
      req.log.error(err)
      return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message)
    })
}


texts: Improve query: find users who are neither friends nor fans of a user

texts:
Please take a look at this query and try to give me any other ideas that will give the exact same results more efficiently.

SELECT username
FROM users
WHERE username NOT IN (
    SELECT DISTINCT username
    FROM users, friends
    WHERE 'user1' IN (you,friend,username)
      AND you     IN ('user1',username)
      AND friend  IN ('user1',username))
  AND username <> 'user1'

Here's a live demo.


texts: Script for recording a country in which a company belongs

texts:
I have an Apps Script that is supposed to run through the spreadsheet, and if a company belongs to a certain country (there's a country column), set the value of the region row to something (e.g. Africa).

The spreadsheet has more than 8500 rows and this is the dirty code I have.  It's working, but if there's a better way to write it, I'd appreciate any pointers:

function setRegions() {
      var mySheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var myCompany = mySheet.getDataRange().getValues();
      var start = 2;
      for(i = 1; i < myCompany.length; i++){
        var univ = myCompany[i];
        var country_code = univ[4];
        if (country_code == "ke" ||
            country_code == "ng" ||
            country_code == "ug" ||
            country_code == "za" ||
            country_code == "sn" ||
            country_code == "gh") {
          rgMyRange = mySheet.getRange("M" + start);
          rgMyRange.setValue("AFRICA");
        }else if (country_code == "eg" ||
                 country_code == "sa" ||
                 country_code == "ma"){
          rgMyRange = mySheet.getRange("M" + start);
          rgMyRange.setValue("MENA");
        }else if (country_code == "br" ||
                 country_code == "ar" ||
                 country_code == "mx" ||
                 country_code == "pe" ||
                 country_code == "co"){
          rgMyRange = mySheet.getRange("M" + start);
          rgMyRange.setValue("LATAM");
        }else if (country_code == "my" ||
                 country_code == "th" ||
                 country_code == "id" ||
                 country_code == "ph"){
          rgMyRange = mySheet.getRange("M" + start);
          rgMyRange.setValue("APAC");
        }else if (country_code == "in") {
          rgMyRange = mySheet.getRange("M" + start);
          rgMyRange.setValue("IN");
        }
        start++;
      }
    }


texts:
I would like comments on my implementation of a stack:

template <class T>
class Stack {
 public:
        void pop(T& element);
        void push(const T& element);
 Stack();

 private:
         int elementCount_;
         int stackTop_;
  static const int  MAX_ELEMS = 10;
  T elementArray_[MAX_ELEMS];
};

template <class T>
Stack<T>::Stack() :
elementCount_(0),stackTop_(-1)
{
}

template <class T>
void Stack<T>::push(const T& element)
{
 if (stackTop_ == MAX_ELEMS-1){
            std::cout << "Stack is full" << "\n" ;
            return;
 }
        elementArray_[++stackTop_] = element;
 elementCount_++;
}

template <class T>
void Stack<T>::pop(T& element)
{
    if (stackTop_ == -1){
     std::cout << "Stack is empty" << "\n";
     return;
    }
    elementCount_--;
    element =  elementArray_[stackTop_--];
}


texts: Getter and setter for a k-d nested list-of-lists

texts:
I'm trying to build accessors for a kd nested list-of-lists such as this 4D example (of shape \$ 2 \times 2 \times 2 \times 2 \$):

kd_lol = [
  [
    [
      [0,1],
      [2,3]
    ],
    [
      [4,5],
      [6,7]
    ]
  ],
  [
    [
      [8,9],
      [10,11]
    ],
    [
      [12,13],
      [14,15]
    ]
  ]
]

I use a list of values to access and modify elements in this nested list-of-lists.

In the above example, you can access something using [i,j,k,l] where \$ 0 \le i,j,k,l < 2 \$.

I'd like to build a fast, efficient getter in idiomatic Python of the form:

def get(grid, list_of_indices)
def put(grid, list_of_indices, value)

My current implementation is as follows:

def get(grid, list_of_indices):
  cur_grid = grid
  for index in list_of_indices:
          cur_grid = cur_grid[index]
  assert(type(cur_grid) != type([])) # not a list
  return cur_grid

and

def put(grid, list_of_indices, value):
  cur_grid = grid
  for index in list_of_indices[:-1]:
    cur_grid = cur_grid[index]
  assert(type(cur_grid) == type([]))    # must be a 1D list
  assert(type(cur_grid[0]) != type([])) # must be a 1D list
  cur_grid[list_of_indices[-1]] = value

Any critique/suggestions to tidy up or reduce the amount of code above is welcome.

Here's a repl that you can play with.


texts:
Below is the method that I have written for reading from a text file.  While reading, I need to match a line string to a given regex, and if it matches, I need to add the line string to a collection.

private static void GetOrigionalRGBColours(string txtFile)
{
    string tempLineValue;
    Regex regex = new Regex(@"^\d+.?\d* \d+.?\d* \d+.?\d* SRGB$");

    using (StreamReader inputReader = new StreamReader(txtFile))
    {
        while (null != (tempLineValue = inputReader.ReadLine()))
        {
            if (regex.Match(tempLineValue).Success
                && tempLineValue != "1 1 1 SRGB"
                && tempLineValue != "0 0 0 SRGB")
            {
                string[] rgbArray = tempLineValue.Split(' ');
                RGBColour rgbColour = new RGBColour() { Red = Convert.ToDecimal(rgbArray[0]), Green = Convert.ToDecimal(rgbArray[1]), Blue = Convert.ToDecimal(rgbArray[2]) };
                originalColourList.Add(rgbColour);
            }
        }
    }
}

When this method is run for a text file of 4MB having 28653 lines, it takes around 3 minutes just to finish the above method. Also, as a result of the above run, originalColourList is populated with 582 items.

How can I improve the performance of this method?  I had truncated the original text file for testing purpose.  The actually text file size may go up to 60MB.


texts:
I was trying out some variation in implementation of a leetcode example and was surprised by the runtimes. I was expecting it would be better to use map() than classic grandpa style for-loop

In short the problem is to find if a value in the list is smaller or larger than a threshold value

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/submissions/

Here are the three implementations:

72 ms 13.8 MB

Map over the input list and generate the list of bool

class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:

        m=max(candies)-extraCandies
        return list(map( lambda x: x>=m, candies))

40 ms 14 MB

For-loop and append() to list

class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:

        m=max(candies)-extraCandies
        ans=[]
        for x in candies:
            ans.append(x>=m)
        return ans

28 ms 13.6 MB

Use + to append to list

class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:

        m=max(candies)-extraCandies
        ans=[]
        for x in candies:
            ans+=[(x>=m)]
        return ans

Why is append() slower than + and is there some oversight in the map() solution which slows it down?


texts: Convert an integer(seconds) into the format of an hour: minute: seconds in c

texts:
input:140153(seconds)
output:38:55:53

I have solved this problem in this way:
#include <stdio.h>
int main(){
    int N;
    double hour;
    double minute;
    double seconds;
    scanf("%d",&N);

    hour=N / 3600.0;

    double floating = hour;
    double fractional, integer;

    //split the floating value(hour) into the integer and decimal
    fractional = modf(floating, &integer);
    minute=60 * fractional;

    double floatingUpdate = minute;
    double fractionalUpdate, integerUpdate;
    //split the floating value(minute) into the integer and decimal
    fractionalUpdate = modf(floatingUpdate,&integerUpdate);
    seconds = 60 * fractionalUpdate;
    printf ("%g:%g:%g\n", integer, integerUpdate, seconds);

    return 0;
}

Would you propose any simplification for my solution? Would I face any problem with some specific conditions? Is the way I solved this kind of problem efficient or not?


texts:
The div and add functions are located randomly in my package structure. I have a function with this signature:

def calc(x, y, func_name='add')

How do I implement this function?

My idea is to import all the modules, then use the dir function, like so:

def import_submodules(package, recursive=True):
    """ Import all submodules of a module, recursively, including subpackages

    :param package: package (name or actual module)
    :type package: str | module
    :rtype: dict[str, types.ModuleType]
    """
    if isinstance(package, str):
        package = importlib.import_module(package)
    results = {}
    for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
        full_name = package.__name__ + '.' + name
        print 'full_name =', full_name
        results[full_name] = importlib.import_module(full_name)
        if recursive and is_pkg:
            results.update(import_submodules(full_name))
    return results

def create_symbol_module_d(module_name_module_d, include=None, exclude=None):
    """ Create mapping of symbol to module

    :param module_name_module_d
    :type module_name_module_d: dict[str, types.ModuleType]
    :rtype: dict[str, types.*]
    """
    inv_res = {}
    for mod in module_name_module_d.itervalues():
        for sym in dir(mod):
            if include and sym in include:
                inv_res[sym] = mod
            elif exclude and sym not in exclude:
                inv_res[sym] = mod
            else:
                inv_res[sym] = mod
    return inv_res

Then I can just do:

sym2mod = create_symbol_module_d(import_submodules('package_name'))
def calc(x, y, func_name='add'):  return sym2mod[func_name](x, y)


texts:
I have an array of data in the below format
let input = [
{
    time: "2020-7",
    tasks: [
      {
        key: "p1",
        value: 15
      },
      {
        key: "p2",
        value: 13
      },
    ]
  },
{
    time: "2020-8",
    tasks: [
      {
        key: "p1",
        value: 16
      },
      {
        key: "p2",
        value: 19
      },
    ]
  },
{
    time: "2020-9",
    tasks: [
      {
        key: "p1",
        value: 12
      },
      {
        key: "p2",
        value: 93
      },
    ]
  }
]

After config input array, then 'dataConvert' is formatted as follows:
dataConvert = [
  ["x","2020-7", "2020-8", "2020-9"],
  ["p1", 15, 16, 12],
  ["p2", 13, 19, 93]
]

I tried use reduce , I want to find another way of optimizing.
let dateConvert = [], valueConvert = [];
data2.forEach(x=>{
   let date = new Date(x.time);
   if (date) {
      let getYear = date.getFullYear();
      let getMonth = date.getMonth() + 1;
      let newDate = `${getYear}-${getMonth}-1`;
      return dateConvert = [...dateConvert, newDate];
   }
})
dateConvert.unshift("x");

// get p1 p2 value
let allTasks = data2.flatMap(x => x.tasks);

 valueConvert = Object.values(allTasks.reduce((arr, item) => {
 arr[item.key] = arr[item.key] || [item.key];
 arr[item.key].push(item.value);
 return arr;
}, {}));
dataConvert = [...[dateConvert], ...valueConvert];

thank u.


texts:
I want to process a ton of JSON objects as quickly as possible.

I've done my best to make the processing as concise and efficient as I can.

How can I make it more efficient?

private void processButton_Click(object sender, EventArgs e)
{
    // For measuring how long the processing takes.
    var stopwatch = Stopwatch.StartNew();

    // Get the IDs of the completed RootObjects.
    // There are no duplicate IDs.
    var completed = new List<string>();
    foreach (var file in Directory.EnumerateFiles("C:\\Completed", "*.json"))
    {
        completed.AddRange(
            JsonConvert.DeserializeObject<List<RootObject>>(File.ReadAllText(file)).Select(o => o.id));
    }
    Console.WriteLine($"completed.Count: {completed.Count}");

    // Get the unfinished RootObjects.
    //
    // 78,198 of the unfinished RootObjects share their ID with another.
    // The duplicates are removed in the next step. (#2)
    //
    // The unfinished RootObjects also contain ALL of the completed RootObjects.
    // The completed RootObjects are ignored in the next step. (#1)
    var unfinished = new List<RootObject>();
    foreach (var file in Directory.EnumerateFiles("C:\\Unfinished", "*.json"))
    {
        unfinished.AddRange(JsonConvert.DeserializeObject<List<RootObject>>(File.ReadAllText(file)));
    }
    Console.WriteLine($"unfinished.Count: {unfinished.Count}");

    var processed =
        unfinished.Where(o => !completed.Contains(o.id)) // (#1) Ignore all completed RootObjects.
            .GroupBy(o => o.id).Select(objects => objects.First()) // (#2) Remove all duplicate RootObjects.
            .ToList();
    Console.WriteLine($"processed.Count: {processed.Count}");

    stopwatch.Stop();
    Console.WriteLine($"stopwatch.ElapsedMilliseconds: {stopwatch.ElapsedMilliseconds}");
}

// Output:
//      complete.Count: 35649
//      unfinished.Count: 250315
//      processed.Count: 136468
//      stopwatch.ElapsedMilliseconds: 75875

If you require any further information, let me know.


texts: A CRUD blog with a basic auth system made with the MERN stack

texts:
I would like some feedback on things that maybe could've been written a lot better. I used redux for handling state.

GitHub repo

Demo

This blog project is meant to create, read, update, and delete posts. Those are the major functions. A user also must log in to do this.

Here are some redux actions. Any possible improvements you can see here?:

postActions.js

import axios from 'axios';

const fetch = require('node-fetch');

export const fetchPosts = () => function (dispatch) {
  dispatch({ type: 'FETCH_POSTS' });

  return axios.get('/posts')
    .then((response) => {
      dispatch({ type: 'FETCH_POSTS_FUFILLED', payload: response.data });
    })
    .catch((err) => {
      dispatch({ type: 'FETCH_POSTS_REJECTED', payload: err });
    });
};

export const deletePosts = (posts, cb) => function (dispatch) {
  axios.delete('/delete', { data: posts })

    .then((response) => {
      dispatch({ type: 'DELETE_POSTS_FUFILLED', payload: response.data });
    });
};

export const newPost = (title, body, date) => function (dispatch) {
  return axios.post('/newpost', {
    title,
    body,
    author: 'testUser',
    date,

  })
    .then((response) => {
      dispatch({ type: 'NEW_POST', payload: response.data });
      console.log(response);
    });
};

export const findSinglePost = postId => function (dispatch) {
  dispatch({ type: 'FIND_SINGLE_POST', payload: postId });
};

export const sendEdit = editStatus => function (dispatch) {
  dispatch({ type: 'CHANGE_EDIT_STATUS', payload: editStatus });
};

export const handleSave = changes => function (dispatch) {
  axios.put('/edit', { data: changes })

    .then((response) => {
      dispatch({ type: 'EDITED_POST', payload: response.data });
    });
};

export const load = data => ({ type: 'LOAD', payload: data });

export const changeRedirect = bool => function (dispatch) {
  dispatch({ type: 'CHANGE_REDIRECT_STATUS', payload: bool });
};

export const checkBoxChange = postId => function (dispatch) {
  dispatch({ type: 'CURRENT_POST', payload: postId });
};

Please give me any feedback you can think of. I'm trying to get better at React/Angular.