texts:
I have this ugly function, and I feel that the entire strncpy should just be an strcpy:

void PackData(char*& cursor, const std::string& data) {
    *(reinterpret_cast<int*>(cursor)) = static_cast<short>(data.length() + 1);
    cursor += sizeof(int);
    // copy the text to the buffer
    ::strncpy(cursor, data.c_str(), data.size());
    cursor += (data.length() * sizeof(char));
    *(reinterpret_cast<char*>(cursor)) = 0;
    cursor += sizeof(char);
}

cursor is guaranteed to have enough room to contain all the data copied. And data only contains a '\0' character at termination.

I want to update this function to use strcpy, and to remove some of the ugly. Here's what I have:

void PackData(char*& cursor, const std::string& data) {
    const int size = data.size() + 1;

    std::copy_n(cursor, sizeof(int), reinterpret_cast<char*>(&size));
    cursor += sizeof(int);
    strcpy(cursor, data.c_str());
    cursor += size;
}

My code works fine, but I wanted to ask if anyone sees any misbehavior that I may have missed?


texts: Optimize a Sql subquery containing multiple inner joins and aggregate functions

texts:
I have a select statement which is infact a subquery within a larger select statement built up programmatically. The problem is if I elect to include this subquery it acts as a bottle neck and the whole query becomes painfully slow.

An example of the data is as follows:

Payment
.Receipt_no|.Person |.Payment_date|.Type|.Reversed|
          2|John    |01/02/2001   |PA   |         |
          1|John    |01/02/2001   |GX   |         |
          3|David   |15/04/2003   |PA   |         |
          6|Mike    |26/07/2002   |PA   |R        |
          5|John    |01/01/2001   |PA   |         |
          4|Mike    |13/05/2000   |GX   |         |
          8|Mike    |27/11/2004   |PA   |         |
          7|David   |05/12/2003   |PA   |R        |
          9|David   |15/04/2003   |PA   |         |

The subquery is as follows :

select Payment.Person,
Payment.amount
from Payment
inner join (Select min([min_Receipt].Person) 'Person',
   min([min_Receipt].Receipt_no) 'Receipt_no'
   from Payment [min_Receipt]
   inner join (select min(Person) 'Person',
      min(Payment_date) 'Payment_date'
      from Payment
      where Payment.reversed != 'R' and Payment.Type != 'GX'
      group by Payment.Person) [min_date]
   on [min_date].Person= [min_Receipt].Person and [min_date].Payment_date = [min_Receipt].Payment_date
   where [min_Receipt].reversed != 'R' and [min_Receipt].Type != 'GX'
   group by [min_Receipt].Person) [1stPayment]
on [1stPayment].Receipt_no = Payment.Receipt_no

This retrieves the first payment of each person by .Payment_date (ascending), .Receipt_no (ascending) where .type is not 'GX' and .Reversed is not 'R'. As Follows:

Payment
.Receipt_No|.Person|.Payment_date
          5|John   |01/01/2001
          3|David  |15/04/2003
          8|Mike   |27/11/2004

I am unable to move the subquery out to a temporary table as temporary tables are simply not supported within the programming language used by my application.

Edit : Incorrect statement. Temporary tables are supported and therefore this is a valid option.

Following a post on StackOverflow -

The Query was rewritten as the following.

Query 1.

select min(Payment.Person) 'Person',
    min(Payment.receipt_no) 'receipt_no'
from
    Payment a
where
    a.type<>'GX' and (a.reversed not in ('R') or a.reversed is null)
    and a.payment_date =
      (select min(payment_date) from Payment i
      where i.Person=a.Person and i.type <> 'GX'
      and (i.reversed not in ('R') or i.reversed is null))
group by a.Person

I added this as a subquery within my much larger query, however it still ran very slowly. So I tried rewriting the query whilst trying to avoid the use of aggregate functions and came up with the following.

Query 2.

SELECT
    receipt_no,
    person,
    payment_date,
    amount
FROM
    payment a
WHERE
    receipt_no IN
      (SELECT
           top 1 i.receipt_no
       FROM
           payment i
       WHERE
           (i.reversed NOT IN ('R') OR i.reversed IS NULL)
           AND i.type<>'GX'
           AND i.person = a.person
       ORDER BY i.payment_date DESC, i.receipt_no ASC)

Which I wouldn't necessarily think of as being more efficient. In fact if I run the two queries side by side on my larger data set Query 1. completes in a matter of milliseconds where as Query 2. takes several seconds.

However if I then add them as subqueries within a much larger query, the larger query completes in hours using Query 1. and completes in 40 seconds using Query 2.

I can only attribute this to the use of aggregate functions in one and not the other.


texts: Linking input/output states and conditions in an input file

texts:
Consider the following CSV file:

A; B; ;
B; ; A;
C; ; E F;
D; ; E;
E; C; ;

The fields:

$1: the jname. A unique id of the entry.
$2: a " "(space)-separated list of incond.
$3: a " "(space)-separated list of outcond.

For the "link" A-B to be valid, jname A must define B as outcond, and job B must define A as incond.

In the above example, D-E is not a valid "link" because E doesn't define D as incond.
C-F is not a valid "link" because F doesn't exist.

A cond is not valid if the link it forms is not valid. The script must detect all non valid conds and which jobs are infected.

#!/usr/bin/awk -f

BEGIN {
    FS=" *; *";
    delim = "-";
    conds[""]=0;
}

{

    icnd_size = split($2, incond_list, " ");

    for (i=1; i<=icnd_size; ++i) {
    conds[incond_list[i] delim $1]++;
    }

    ocnd_size = split($3, outcond_list, " ");

    for (i=1; i<=ocnd_size; ++i) {
    conds[$1 delim outcond_list[i]]--;
    }

}

END {

    for (i in conds) {
    sz = split(i, answer, delim);

    if (conds[i] == 1) {
        j = answer[2];
        c = answer[1];
        inorout = "INCOND";
    }

    if (conds[i] == -1) {
        j = answer[1];
        c = answer[2];
        inorout = "OUTCOND";
    }

    if (conds[i] != 0)
        print "Invalid", inorout, c, "on job", j;
    }
}

The script works, although I do not have large data to test against. I see 2 problems with it:

the script will break if some cond has the character delim in the name
the script might break (and/or return false positives) if a line is inserted twice or if two lines have the same jname.

I could use any tip on addressing the two problems, as well as any critique of the code, it's literally my first Awk code.


texts:
I wrote a simple function to determine if a year is a leap year or not. It works, but does not feel idiomatic.

isLeapYear :: Int -> Bool
isLeapYear year =
    (mod year 400) == 0 || ((mod year 4) == 0 && not ((mod year 100) == 0))

Is there a more "haskelly" way to write this function ?


texts:
I have a form with 11 inputs that relate to each column on a table, which is displayed above. Each input has an id that matches the a class in the table based on the column name. I want all the inputs to be droppable, the logic for all of them is identical to below.

$(function() {
  $( "#dest_city" ).droppable({
    drop: function( event, ui ) {
        $( ".ui-selected.dest_city" ).each(function(){
            $( '#dest_city' )
                .val( $( '#dest_city' ).val() == "" ? $( this ).html() : $( '#dest_city' ).val() + ", " + $( this ).html() );
        })
    }
  });
});
$(function() {
  $( "#dest_state" ).droppable({
    drop: function( event, ui ) {
        $( ".ui-selected.dest_state" ).each(function(){
            $( '#dest_state' )
                .val( $( '#dest_state' ).val() == "" ? $( this ).html() : $( '#dest_state' ).val() + ", " + $( this ).html() );
        })
    }
  });
});
$(function() {
  $( "#car" ).droppable({
    drop: function( event, ui ) {
        $( ".ui-selected.car" ).each(function(){
            $( '#car' )
                .val( $( '#car' ).val() == "" ? $( this ).html() : $( '#car' ).val() + ", " + $( this ).html() );
        })
    }
  });
});

And the inputs -

    <input type="text" name="dest_city" id="dest_city" value="" size="7" />
    <input type="text" name="dest_state" id="dest_state" value="" size="3" />
    <input type="text" name="car" id="car" value="" size="11" />

And the data -

    AAAAAAA
    111111
    1111
    P
    FTSCOTT
    KS
    L
    AAAAA
    11111
    11
    AAAAA
    FRESNO
    CA

This checks on drop for all selected cars and inserts each of them to the input, the ternary checks if the input is empty or already has something, and adds the items to make a comma separated list.

My question is, is there any way to refactor this instead of writing the above for each input?

I am using Ruby on Rails so I can easily set up a loop to create that for each input, but that's only shorter on my end, the actual output would still have a nearly identical block of code for each input.

A .car can only be placed in #car, .dest_city in #dest_city etc...


texts: How can I make only one if-else statement among all of these?

texts:
I have these if-else statements that I am not able to refactor.  I have used them for doing validations on server-side using asp.net.

Would anyone please suggest ways to reduce these statements?  Here, validation fields and validation types are enum lists.

else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationFields.FO.ToString(), ValidationTypes.P.ToString()))
{
   BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
   args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationFields.FW.ToString(), ValidationTypes.P.ToString()))
{
   BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
   args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationFields.UF.ToString(), ValidationTypes.P.ToString()))
{
     BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
     args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.O.ToString(), ValidationTypes.P.ToString()))
{
      BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
      args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.W.ToString(), ValidationTypes.P.ToString()))
{
      BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
      args.IsValid = false;

}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.P.ToString(), ValidationTypes.C.ToString()))
{
      BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
      args.IsValid = false;

}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.C.ToString(), ValidationTypes.U.ToString()))
{
      BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
      args.IsValid = false;

}

This is method for Checknextitem:

 public static bool CheckNextItem(string Compareitem1, string comnpareitem2, string items1, string items2)
  {

        var listContains = Compareitem1 == items1 && comnpareitem2 != items2;
        return listContains;

  }


texts: Add active class to current menu with extension method or jQuery

texts:
In the layout, I have a menu that contains some ul and li.
I have three levels`. This code is a bit of a sample:

     reports

            text

text

 text

To select the current menu item, I use this code:

 public bool IsAny(params string[] controllers)
    {
        return controllers.Any(c => Is(c));
    }

    public bool Is(string controller, string action = null)
    {
        if (ViewContext.RouteData.Values["Controller"].ToString().ToLower() == controller.ToLower()
            && (action == null ||
             ViewContext.RouteData.Values["Action"].ToString().ToLower() == action.ToLower()))
            return true;
        return false;
    }

If I use jQuery, is it better than this one on page load speed?  Or is there a way to do this in faster way?

The jQuery code looks like this:

(function(){
    var current = 'current location';
    $('#nav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})


texts:
I've posted this to Stack Overflow, but someone voted to close as they felt it was opinion based, so I'm bringing it over to Code Review.

I have some Linq fluent chains to shape an original IEnumerable of objects into the proper form.

During this process, I'd like to capture and log the reason why some objects are "rejected" in a Where clause.

I was thinking about something similar to this (reduced use-case, just for the sake of demonstration):

var bar = SomeEnumerable
    .SelectMany(...)
    .Where(i =>
    {
        if(...)
        {
            return true;
        }
        else
        {
            //Log "failure" to in-memory list
            return false;
        }
    })
    .ToDictionary(...);

I understand that this introduces some side-effect, though minimal, but if at all possible, I would like to eliminate it.

Does this match some "pattern" that can be expressed in the context of Linq chains?

Thanks


texts: Phone number extraction with regular expressions

texts:
I've been working on my own phone number extraction snippet of Regex code and I'd appreciate your feedback on it. I've tried to make it match as many different types of numbers as I knew existed in the US. (I'm sure there's some I missed.) Is there anything I can do to improve this?

(?:\+?(\d{1})?-?\(?(\d{3})\)?[\s-\.]?)?(\d{3})[\s-\.]?(\d{4})[\s-\.]?

Here's a picture of it in action:

You can test the code out here.

Also for this interested, here is the flow of the "logic":

(Made from pasting the code into here)


texts:
public class BuscaDiretaBusiness
{
    PortalIOEntities portalIO = new PortalIOEntities();

    public IQueryable CarregaAlias(out int ItemsCount)
    {
        var query = from a in portalIO.DO_CadernoBuscaDiretaAlias
                    select new
                    {
                        a.CDP_ID,
                        a.CDA_Alias,
                        a.DO_CadernoDeParaBuscaDireta.CDP_NomeCaderno
                    };
        ItemsCount = query.Count();
        return query;
    }
}

Will it make two selects on DataBase?


texts: Project Euler #16 in Swift - Power digit sum

texts:
I just finished Project Euler #16 in Swift, and since there is not any version yet on Code Review, I would like to have some comments on what I did to try to improve it.

  2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

  What is the sum of the digits of the number 2^1000?

import Foundation

func addMulToResult(inout results:[Int], var mulResult:Int, index:Int) {

    if index == results.count {
        results.append(0)
    }

    mulResult = results[index] + mulResult

    var result = mulResult % 10

    results[index] = result

    var retain = mulResult / 10
    if retain > 0 {
        addMulToResult(&results, retain, index + 1)
    }
}

func infMult(left:[Int], right:[Int]) -> [Int] {

    var results:[Int] = [Int]()
    for (j, rightNumber) in enumerate(reverse(right)) {

        for (i, leftNumber) in enumerate(reverse(left)) {

            let mulResult = leftNumber * rightNumber
            addMulToResult(&results, mulResult, i + j)
        }
    }

    return results.reverse()
}

func infPow(x:Int, var power:Int) -> [Int] {

    var result = [1]
    var xArray = intToIntArray(x)
    while power > 0 {

        result = infMult(result, xArray)
        power--
    }

    return result
}

func intToIntArray(var number:Int) -> [Int] {
    var intArray:[Int] = []

    while number > 0 {

        intArray.append(number % 10)
        number /= 10
    }

    return intArray.reverse()
}

func powerDigitSum(x:Int, var power:Int) -> Int {
    let powerSum = infPow(x, power)

    let result = reduce(powerSum, 0) { $0 + $1 }

    return result
}

func euler16() {

    let number = powerDigitSum(2, 1000)

    println(number)
}

func printTimeElapsedWhenRunningCode(operation:() -> ()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    println("Time elapsed : \(timeElapsed) s")
}

printTimeElapsedWhenRunningCode(euler16)

The code executes in 0.06s


texts: Correctness of a minimal parallel workers queue in Ruby

texts:
I've programmed a minimal parallel workers queue in Ruby, and I wanted to know if it's correct, and if there are simpler ways of implementing it.

I'm aware of the existence of MonitorMixin, but it won't save any code, I think.

The design is kept intentionally trivial (e.g. it uses Thread.abort_on_exception).

# Usage:
#
#   queue = ParallelWorkersQueue.new( <threads> )
#   queue.push { <operation_1> }
#   queue.push { <operation_2> }
#   queue.join
#
class ParallelWorkersQueue

  def initialize( slots )
    @max_slots  = slots
    @free_slots = slots

    @mutex              = Mutex.new
    @condition_variable = ConditionVariable.new

    Thread.abort_on_exception = true
  end

  def push( &task )
    @mutex.synchronize do
      while @free_slots == 0
        @condition_variable.wait( @mutex )
      end

      @free_slots -= 1
    end

    Thread.new do
      yield

      @mutex.synchronize do
        @free_slots += 1

        @condition_variable.signal
      end
    end
  end

  def join
    @mutex.synchronize do
      while @free_slots < @max_slots
        @condition_variable.wait( @mutex )
      end
    end
  end

end


texts: Insert multiple columns in specific location based on two conditions in other columns

texts:
need to rewrite some code I already have. It insert columns where a 'Standard Deviation' column is missing. To do that it checks if the preceding column is a "variable" column, and if there already is a "Standard Deviation" column after it.

Right now I'm using a while loop that iterates through the columns checking df.iloc[1,x] and df.iloc[1,x+1].

i = 7
j = len(df.columns)-1

while i < j:
    if df.loc[1,i] != 'Standard Deviation' and df.loc[1,i] != 'Replicates' and df.loc[1,i] != 'Method':
        if df.loc[1,i+1] != 'Standard Deviation':
            df.insert(i+1,'Standard Deviation',np.nan)
            df.columns = pd.RangeIndex(df.columns.size)
            df.loc[1,i+1]='Standard Deviation'
    i+=1
    j = len(df.columns)-1

df.insert(len(df.columns),'Standard Deviation',np.nan)
df.columns = pd.RangeIndex(df.columns.size)
df.loc[1,len(df.columns)-1]='Standard Deviation'

Snippet from dataframe (hard to make sense of it):

50  51  52  53  54  55  56  57  58
0   Pour Point (°C) Pour Point (°C) Pour Point (°C) Pour Point (°C) Boiling Point Distribution- Temperature (°C)    Boiling Point Distribution- Temperature (°C)    Boiling Point Distribution- Temperature (°C)    Boiling Point Distribution- Temperature (°C)    Boiling Point Distribution- Temperature (°C)
1   Pour point  Standard Deviation  Replicates  Method  Initial Boiling Point   5%  10% 15% 20%
2   NaN NaN NaN NaN NaN NaN NaN NaN NaN
3   < -25   NaN NaN ASTM D97    NaN 35  52  70  88
4   < -25   NaN NaN ASTM D97    NaN 56  84  104 135
5   -6  NaN NaN ASTM D97    NaN 115 166 224 259
6   24  NaN NaN ASTM D97    NaN 279 303 322 339

Right now the code works and gives the expected outcome. I just want to rewrite it in a more efficient/elegant way.

I don't know how to do it without iterating over the columns to specify checking df.iloc[1,i] and df.iloc[1,i+1]


texts: Please review my implementation of a simple When/Then (pseudo Promise) in javascript

texts:
I'm hoping some folks can take a few minutes to review some code I was working on today.

https://gist.github.com/1115202

Essentially, I'm doing a lot of work in Node.js at the moment and I'm a big fan of Promises.

Since 99% of the work that I'm doing involves performing several asynchronous actions and then parsing the results, I wanted something a little simpler and more light-weight that some of the other Promise/Deferred/Futures libraries that are out there.

My aim with this is to have a simple when().then() format without having to instantiate a new Promise inside each function.

The usage is like this:

when(
    function(){ this.pass(1); },
    function(){ this.pass(2); }
)
.then(function(results){
    console.log( results );
});

In the Github gist I've linked to above, there are use cases near the bottom. Test case 1 uses timeouts, the 2nd test case uses several async http requests in Node.js and logs the total results at the end when all 3 have finished.

I'd love to hear any opinions good or bad, recommendations on how to make it better, etc.


texts: Structuring Service and DAO Layers in Go

texts:
I am having a bit of difficulty in designing my Go code.
I'll try to demonstrate things with a very simple example of adding a new user to the database.
My Handler is only doing one thing: Calling a service.
The service is managing all the business logic and then calling the DAO to interact with the database.
The DAO also has only responsibility: Storing in the database.
Also, just for context I am making GraphQL requests to interact with my ElasticSearch database, but the design shouldn't be affected by this too much.
I have read a lot of posts about using structs/interfaces to handle the service layer and DAO layer, but I am unable to implement the same in my usecase.
File: handlers/user.go
type Resolver struct {
    client *elastic.Client
    index  string
}

func (r *Resolver) CreateUser(ctx context.Context, userID string, name string, token *string) (*model.User, error) {
    u, err := CreateUserService(ctx, r.client, r.index, userID, name, token)

    if err != nil {
        fmt.Println("Could not add User to db")
        return nil, err
    }

    return u, nil
}

File: services/user.go
func CreateUserService(ctx context.Context, client *elastic.Client, index string, userID string, name string, token *string) (*model.User, error) {

    u := &model.User{
        UserID: userID,
        Name:   name,
        Token: token
    }

    s, err := utils.ParseToString(u)

    if err != nil {
        return nil, err
    }

    err := CreateUserDAO(ctx, client, index, s)

    if err != nil {
        return nil, err
    }

    return u, nil
}

File: dao/user.go
func CreateUserDAO(ctx context.Context, client *elastic.Client, index string, user string) error {
    _, err = client.Index().
        Index(index).
        BodyString(s).
        Do(ctx)

    if err != nil {
        return err
    }

    return nil
}

I don't have a background in Java/C# so I'm not well versed with OOP Principles but I did read a lot on MVC based on other answers. My code works for now, but is it bad code?
What are the things I can smooth out?
I don't want to be passing parameters from one function to another. Is there a way to that with receivers on methods?


texts: Excel VBA code midStr() function using left and right position instead of length used with mid()

texts:
In the early days of Basic (1970's when i started coding) the midStr() function used left and right positions directly rather than left and length we now use with mid(). I always found it more efficient in my mind to code using the old midStr() method, so I finally just created some code to do it. It's certainly not as efficient as mid(), and if I am dealing with lots of data I'd use mid() directly instead, but for simplicity, I do like the old way better, it's more direct to simply code rightPos rather then rightpos - leftPos + 1, and to test for null.
I also made the rightPos optional, and when not used, the length of the textin is used instead, so it will simply return the remainder of the text starting at the leftPos.
Any kind critique is welcome, thank you.
Function midStr(ByVal textin As String, _
                ByVal leftPos As Long, _
       Optional ByVal rightPos As Variant) As Variant
   'midStr returns textin string using leftPos and rightPos (rather than num_chars).
   'rightPos is optional, len(textin) is used for the rightPos when it's not otherwise defined.

   On Error GoTo midStrErr
   If IsMissing(rightPos) Then rightPos = Len(textin)
   If rightPos < leftPos Then
      midStr = vbNullString
   Else
      midStr = Mid(textin, leftPos, rightPos - leftPos + 1)
   End If
   Exit Function

midStrErr:
   On Error Resume Next
   midStr = CVErr(xlErrValue) '#VALUE!
End Function


texts: Thread-safe wrapper around WCF ServiceModel.ClientBase subclass

texts:
I have an ASP.NET application which uses a Service Reference to a (third-party, offsite) payment processor.

The service reference class is generated automatically.
Its implementation is a subclass of ServiceModel.ClientBase, which
MSDN documents as, "Any instance members are not guaranteed to be thread safe."

Is the following a good implementation of my wrapper class (to be called from my aspx pages), to guarantee that access to the service reference singleton is thread-safe?
Should I prefer to simply make the service reference an instance member of the wrapper class, without any locking? My fear was that would imply more than one concurrent service instance, and I don't know how to test whether the remote server side would handle that successfully.

class Authorize : IDisposable
{
    private static ServiceSoapClient s_serviceSoap = null;
    private static object s_locker;

    // This method is invoked from Global.Application_Start() in Global.asax.cs
    internal static void Application_Start()
    {
        // ServiceSoapClient derives from ServiceModel.ClientBase<ServiceSoap>
        s_serviceSoap = new ServiceSoapClient();
        s_locker = new object();
    }

    private bool lockWasTaken = false;
    internal Authorize()
    {
        // Emulate C# `lock` statement
        Monitor.Enter(s_locker, ref lockWasTaken);
        // http://stackoverflow.com/questions/2008382/how-to-heal-faulted-wcf-channels
        if (s_serviceSoap.InnerChannel.State ==
           System.ServiceModel.CommunicationState.Faulted)
        {
            s_serviceSoap.Abort();
            s_serviceSoap = new ServiceSoapClient();
        }
    }
    public void Dispose()
    {
        if (lockWasTaken)
            Monitor.Exit(s_locker);
    }

    internal bool IsAlive()
    {
        // delegate to the singleton
        ANetApiResponseType response = s_serviceSoap.IsAlive();
        log(response, "IsAlive");
        return response.resultCode == MessageTypeEnum.Ok;
    }
    // plus other methods which delegate to the singleton
}


texts:
I've implemented Many-To-Many relationship and wonder if this is the optimal way for it. Since I do not have extensive EF Core experience I would love if someone with more experience could check it out.
Scenario:

Many users
Many organizations
User can belong to multiple organizations
Organization can hold multiple users

// Organization.cs
public class Organization
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual IEnumerable<OrganizationUser> OrganizationUsers { get; set; }
}

// OrganizationUser.cs
public class OrganizationUser
{
    public Guid OrganizationId { get; set; }
    public virtual Organization Organization { get; set; }
    public Guid UserId { get; set; }
    public virtual User User { get; set; }

    public Role Role { get; set; }
}

public enum Role
{
    Owner,
    Admin,
    User
}

// User.cs
public class User
{
    public Guid Id { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public virtual IEnumerable<OrganizationUser> OrganizationUsers { get; set; }

    [NotMapped]
    public virtual IEnumerable<UserOrganizationOutputDto> Organizations
    {
        get
        {
            return OrganizationUsers.Select(x => new UserOrganizationOutputDto
            {
                Id = x.OrganizationId.ToString(),
                Name = x.Organization.Name,
                Role = x.Role
            });
        }
    }
}

// Database Context code that is related
modelBuilder.Entity<Organization>()
    .HasMany<OrganizationUser>()
    .WithOne(x => x.Organization);
modelBuilder.Entity<User>()
    .HasMany<OrganizationUser>()
    .WithOne(x => x.User);

modelBuilder.Entity<OrganizationUser>()
    .HasKey(x => new {x.OrganizationId, x.UserId});
modelBuilder.Entity<OrganizationUser>()
    .HasOne(x => x.User)
    .WithMany(x => x.OrganizationUsers)
    .HasForeignKey(x => x.UserId);
modelBuilder.Entity<OrganizationUser>()
    .HasOne(x => x.Organization)
    .WithMany(x => x.OrganizationUsers)
    .HasForeignKey(x => x.OrganizationId);

```


texts:
I have a dialog which populates my ConnectionStringData object with the URL of the service that I'm trying to connect to. I then consume that URL with the following property:

    /// <summary>
    /// Where the Service is located.
    /// </summary>
    public string ServiceLocation
    {
        get
        {
            string fullUrl = ConnectionStringData.Location.Trim();

            if (fullUrl.EndsWith("/"))
            {
                fullUrl += "Routes";
            }
            else
            {
                fullUrl += "/Routes";
            }

            Uri uri = null;

            if(Uri.TryCreate(fullUrl, UriKind.Absolute, out uri))
            {
                return uri.ToString();
            }

            throw new UriFormatException(String.Format("{0} is an invalid url", fullUrl));
        }
    }

Should I be doing work like this in the getter? Can I do this better?


texts:
I am learning Python and in particular learning about classes. Since I'm self teaching, I'd appreciate any feedback and constructive criticism.

I have a couple specific questions:

In Python you can have multiple functions and classes in a single file (module), but is it considered bad practice to do so?
Python doesn't have private, so is there a point to having accessor methods like I do below?
My IDE suggest I put a comment beneath each function signature. Is it still good to do this when the functions are short and simple, like withdraw(x) in a bank account?

BankAccount.py

# bank account class
class BankAccount:
    def __init__(self, name, balance=0.00):
        self.name = name
        self.balance = balance

    def deposit(self, amount):
        """make a deposit"""
        self.balance += amount

    def withdraw(self, amount):
        """make a withdraw"""
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount

    def get_balance(self): #are accessor methods needed in Python?
        """check the balance"""
        return self.balance

def main():
    customer1 = BankAccount('Alex')
    print(customer1.get_balance())
    customer1.deposit(100)
    customer1.withdraw(30)
    print(customer1.get_balance())

    customer2 = BankAccount('Sam', 200)
    print(customer2.get_balance())

if __name__ == "__main__":
    main()


texts: Create list and add 1 to list values from index [I,R].Print the Occurence of a specific number

texts:
def add(a,b):
    for i in xrange(a-1,b):
        box[i]+=1
def count(k):
    if box.count(k)!=0:
        box.index(k)
        return len(box)-box.index(k)
    else:
        return 0
from sys import stdin,stdout
box=[0]*int(stdin.readline()) #input the number of boxes of chocolate
for i in xrange(int(stdin.readline())):  #loops for M days
    a,b = stdin.readline().split()  #gets the starting and ending index.
    add(int(a),int(b)) #adding 1 each time to box for I,R
box.sort()
for i in xrange(int(stdin.readline())):
    print count(int(stdin.readline()))  #prints the number of boxes of chocolates greater than equal to the input number

For small values the program works but fails for large value.Suggest any faster method/algorithm.

Constraints:
1 <= N <= 100000

1 <= M <= 1000

1 <= l <= r <= N

1 <= Q <= 100000

1 <= K <= N


texts:
I'm doing a simple task in Rust after reading the Rust book:

read a text file
split it at whitespace
sanitize words by removing non-letter characters
sort the words by their frequency of occurrence

Here's what I've got, which works, but I'd like some advice:

are there any unnecessary implicit copies that could be replaced by moves?
are there nice ways to avoid let mut?

use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;

lazy_static! {
    static ref NON_LETTER_RE: Regex = Regex::new("[^a-zA-Z]").unwrap();
}

fn sanitize(s: &str) -> String {
    NON_LETTER_RE.replace_all(s, "").into_owned().to_lowercase()
}

fn main() {
    let words = std::fs::read_to_string("data.txt").unwrap();
    let words = words.split_whitespace().collect::<Vec<_>>();

    let mut freqs = HashMap::new();
    for word in words {
        *freqs.entry(sanitize(word)).or_insert(0) += 1;
    }

    let mut freqs = freqs.into_iter().collect::<Vec<_>>();
    freqs.sort_by(|(_, a), (_, b)| b.cmp(a));

    for (a, b) in freqs {
        println!("{}: {}", a, b);
    }
}


texts:
I wanted an uncomplicated project to get myself started again. Although this works I was wondering if it's the best approach, especially when it comes to validation parts? It seems to me that I'm potentially looping quite a while, and this may not be the best or even common practice. I was hoping the CR community could enlighten me on this matter, as well as any other shortcomings this suffers from, as it has graciously done thus far.

public enum Morse {
    MC_1(".----", '1'), MC_2("..---", '2'),MC_3("...--", '3'),

    MC_4("....-", '4'), MC_5(".....", '5'), MC_6("-....", '6'),

    MC_7("--...", '7'), MC_8("---..", '8'), MC_9("----.", '9'),

    MC_0("-----", '0'), MC_A(".-", 'A'), MC_B("-...", 'B'),

    MC_C("-.-.", 'C'), MC_D("-..", 'D'), MC_E(".", 'E'),

    MC_F("..-.", 'F'), MC_G("--.", 'G'), MC_H("....", 'H'),

    MC_I("..", 'I'), MC_J(".---", 'J'), MC_K("-.-", 'K'),

    MC_L(".-..", 'L'), MC_M("--", 'M'), MC_N("-.", 'N'),

    MC_O("---", 'O'), MC_P(".--.", 'P'), MC_Q("--.-", 'Q'),

    MC_R(".-.", 'R'), MC_S("...", 'S'), MC_T("-", 'T'),

    MC_U("..-", 'U'), MC_V("...-", 'V'), MC_W(".--", 'W'),

    MC_X("-..-", 'X'), MC_Y("-.--", 'Y'), MC_Z("--..", 'Z'),
    MC_SPACE("/", ' ');

    public final String morse;
    public final char code;

    Morse(String morse, char code) {
        this.morse = morse;
        this.code = code;
    }
}

This contains the Main class:

import java.util.Scanner;

public class MorseCodeConverter {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter String to be converted to Morse Code: ");
        String userInput = input.nextLine();
        System.out.println(morseConversion(userInput));
    }

    public static String morseConversion(String s) {
        String ms = s.toUpperCase().trim(); // modified string
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < ms.length(); i++) {
            isValid(ms.charAt(i));

            for (Morse c : Morse.values()) {
                if (ms.charAt(i) == ' ' && ms.charAt(i - 1) == ' '); // Ignore consecutive spaces
                else if (ms.charAt(i) == c.code) {
                    result.append(c.morse);
                    if (i != ms.length() - 1) { result.append((" ")); }
                }
            }
        }
        return result.toString();
    }

    public static boolean isValid(char c) {
        for (Morse m : Morse.values()) {
            if (c == m.code) return true;
        }
        throw new IllegalArgumentException("Invalid Entry: " + c + ". Non-space input may only be: 0-9, A-Z, or a-z");
    }
}


texts: PySide: Feedback progress of task back to GUI from QThread

texts:
I have some PySide GUI application which is capable of executing long running tasks.

The targets of my application design is to

put the task execution to a thread to not block the GUI (e.g. for pausing the task)
display the task progress in a progress bar in the GUI
be able to call a task method separately from my py.test envorionment

My current setup has a start_processing method, which starts a task depending on the inputs of the GUI.
I am using a generic worker object in combination with QThread as each task has a different set of arguments and i dont want to write a specialised thread subclass for each task.

class GenericWorker(QObject):
    start = QtCore.Signal(str)
    progress_changed = QtCore.Signal((int, int))
    finished = QtCore.Signal(object)

    def __init__(self, function, *args, **kwargs):
        super(GenericWorker, self).__init__()

        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.start.connect(self.run)

    def run(self, some_string_arg):
        try:
            return_value = self.function(*self.args, **self.kwargs)
        except Exception as e:
            # log exception
        else:
            if return_value is not None:
                finished.emit(return_value)
            else:
                finished.emit(0)

In start_processing the task - encapsulated in a generic worker object - gets moved to a thread and the processing gets started.

my_thread = QThread()
my_thread.start()

def start_processing():
    my_worker = GenericWorker(task)
    my_worker.moveToThread(my_thread)
    my_worker.progress_changed.connect(update_progressbar)
    my_worker.start.emit("hello")

def update_progressbar(i, total):
    # set progress bar to the corresponding percentage

In almost all use cases a task looks like that:

def task(some_arguments, some_kw_arguments):
    for filepath in filelist:
        # do some preparation for the actual "per file task"
        return_value = per_file_task(some_arguments, some_kw_arguments)
        # do some post processing with return value

    return task_result

To be able to report the progress of a task, i want to emit a signal from the generic worker (running in its thread) after each per_file_task which states the current progress value.
As the task is not defined inside the generic worker class but outside in some Processing class, i need to connect the signal of the generic worker to a update_progressbar method of the GUI.

My idea is to define a callback function in each task which gets called after each per_file_task.

def task(some_arguments, some_kw_arguments, progress_callback=None):
    for i, filepath in enumerate(filelist):
        # do some preparation for the actual "per file task"
        return_value = per_file_task(some_arguments, some_kw_arguments)
        # do some post processing with return value
        if progress_callback:
            proggress_callback(i, len(filelist))

    return task_result

Now that proggress_callback function has to get populated after the task has been registered with the generic worker thread.

def __init__(self, function, *args, **kwargs):
    super(GenericWorker, self).__init__()

    self.function = function
    self.args = args
    self.kwargs = kwargs
    self.kwargs["progress_callback"] = self.progress_changed.emit
    self.start.connect(self.run)

But for me this doesn't look really clean.

My first attempt was to then to split up the processing of the task's for loop into registering only the per file task with the GenericWorker and update its filepath argument for every file. So the update of the progress bar could be done outside of the thread.
But that would break my requirement for the testability as it introduces side effects into the task's logic.

So my final question is: How could i realize this in a cleaner way?
Or are there other patterns which are commonly used in such situations?


texts: Testing whether characters of a string are unique

texts:
Critiques (even pedantic ones) are welcome.

bool unique_chars(std::string &s) {
    if (s.length()>256) return false;
    std::bitset<256> bs;
    for (auto &c:s) {
        if (bs.test(c)) return false;
        bs.set(c);
    }
    return true;
}

EDIT 1:

for (auto &c:s) {         //OLD
for (unsigned char c:s) { //NEW

Reasoning:

char can be either signed or unsigned
if signed then bs[] can be out of bounds
casting to unsigned eliminates issue as negative values will wrap

EDIT 2:

This string is to be made up of characters from the standard ASCII character set, i.e. fitting into a 1 byte char.

EDIT 3:

Renamed function / added test harness with examples. Function parameter changed to const, as string not being modified.

#include <iostream>
#include <bitset>

bool areCharsUnique(const std::string &s) {
    if (s.length()>256) return false;
    std::bitset<256> bs;
    for (unsigned char c:s) {
        if (bs.test(c)) return false;
        bs.set(c);
    }
    return true;
}

int main() {
    std::string s1 = "hi there";
    std::string s2 = "hey man";
    std::cout << areCharsUnique(s1) << std::endl; //0
    std::cout << areCharsUnique(s2) << std::endl; //1
   return 0;
}


texts: Find a positive integer within range using only elementary operations

texts:
Background
The platform I'm coding for is an esoteric scripting engine coded some time ago that only has limited capabilities. Because I cannot produce a version of the engine that can be run on its own (it needs to attach to a running instance of a game), I have translated the code into C# with limitations to mimic the scripting environment.
Task
Given a blackbox function, find the secret in the blackbox using the following limitations:

You can only declare variables of the decimal type
You have access to the elementary operators (+, -, /, *, ==, != ...etc) except for modulo (%)
You cannot use library functions (Math.Floor() ...etc)

The function is as follows:
//the function returns the result of the operation between the secret and the input
//available operations are: >=, >, <=, <, ==, !=
public static bool BlackBox(decimal num, string operation)
{
    //the secret is always an integer greater than or equal to 1
    //you can assume a maximum value the secret cannot exceed, if it helps
    //in this example, the maximum is 400000
    decimal secret = 317810;

    if (operation == ">=" && secret >= num)
        return true;
    else if (operation == ">" && secret > num)
        return true;
    else if (operation == "<=" && secret <= num)
        return true;
    else if (operation == "<" && secret < num)
        return true;
    else if (operation == "==" && secret == num)
        return true;
    else if (operation == "!=" && secret != num)
        return true;
    else
        return false;
}

Implementation
My first thought was to try a binary search but was stumped because I can't use floor/ceil. I settled on using a Fibonacci search to get to the ballpark and follow with a linear search to find the exact value:
public static void Main()
{
    decimal num1 = 0;
    decimal num2 = 1;

    //use fibonacci sequence to get close to ballpark
    while (BlackBox(num2, ">="))
    {
        decimal temp = num1;
        temp += num2;
        num1 = num2;
        num2 = temp;
    }

    //use linear search for the last mile
    while (BlackBox(num1, "!="))
    {
        num1++;
    }

    Console.WriteLine("The number is " + num1.ToString());
}

This works well for small numbers but as the range of the secret grows the linear portion can get quite time consuming (I chose a worst-case example for this implementation for this reason) because the scripting engine is no where near as efficient as C#. My question is how can I improve this algorithm in terms of performance? Or, is there another algorithm that can perform better than Fibonacci search (maybe a binary search implementation is possible)?


texts: inString() Helper Function - Check if substring is in string

texts:
I've written a simple helper function for my helper class that allows me to check if a substring is in a string.

With my function, you can supply either a single needle to check for, or an array of needles to check for. There is also a parameter that allows you to select if you want to check word boundries or not, and a parameter to allow you to choose if the search should be case sensitive or not.

public function inString($needle, $haystack, $checkBoundries = false, $caseSensitive = false) {
        if(is_array($needle) && count($needle) < 2)
        {
            $needle = $needle[0];
        }
        if(is_array($needle))
        {
            $pattern = "(".implode("|", $needle).")";
            if($checkBoundries) {
                $pattern = "(\b{$pattern}\b)";
            }
            $pattern = $caseSensitive ?  "/{$pattern}/" : "/{$pattern}/i";
            return preg_match($pattern, $haystack);
        }
        $pattern = $needle;
        if($checkBoundries) {
            $pattern = "(\b{$pattern}\b)";
        }
        $pattern = $caseSensitive ?  "/{$pattern}/" : "/{$pattern}/i";
        return preg_match($pattern, $haystack);
    }

I would love some advice or pointers for my function. Thank you!


texts:
I would like to kindly ask others to review my code. I'd like suggestions, criticisms, and discussions on what is good and what could be done better.

const canvas = document.querySelector('.gameOfLife');
const ctx = canvas.getContext('2d');

// create an array
const canvasWidth = 100;
const canvasHeight = 100;
canvas.width = 3 * canvasWidth;
canvas.height = 3 * canvasHeight;
let gameBoard = createBoard(canvasWidth, canvasHeight);
let gameBoard2 = createBoard(canvasWidth, canvasHeight);
let gameBoard3 = createBoard(canvasWidth, canvasHeight);

function createBoard(width, height) {
  let board = new Array(0);
  for (let i = 0; i < width; i++) {
    board [i] = [];
    for (let j = 0; j < height; j++){
      board[i][j] = 0;
    }
  }
  return board;
}

function randomNumber(max) {
  return Math.floor(Math.random() * max);
}

function randomPos() {
  const x = randomNumber(canvasWidth);
  const y = randomNumber(canvasHeight);
  return [x, y];
}

function randomBoard(arr) {
  for (let i = 0; i <= 0.2 * canvasHeight * canvasWidth; i++) {
    const [x, y] = randomPos();
    arr[x][y] = 1;
  }
}

function drawBoard(arr) {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  for (let i = 0; i < canvasWidth; i++) {
    for (let j = 0; j < canvasHeight; j++){
      if (arr[i][j] === 1) {
        ctx.fillStyle = "#012345";
        ctx.fillRect(i*3, j*3, 3, 3);
      }
    }
  }
}

// calculate new cycle

function checkSurrounding(x, y) {
  let sum = 0;

  startX = x-1 < 0 ? x : x-1;
  stopX = x+1 >= canvasWidth ? x : x+1;
  startY = y-1 < 0 ? y : y-1;
  stopY = y+1 >= canvasHeight ? y : y+1;

  for (let i = startX ; i <= stopX; i++) {
    for (let j = startY ; j <= stopY; j++) {
      if (i !== x || j !== y) {
        sum += gameBoard[i][j];
      }
    }
  }

  return sum;
}

function deadOrAlive(x, y) {
  const surround = checkSurrounding(x, y);

  if (gameBoard[x][y] === 1 && (surround === 2 || surround === 3)) return 1;
  else if (gameBoard[x][y] === 0 && surround === 3) return 1;
  else return 0;
}

function nextGene() {
  let newBoard = createBoard(canvasWidth, canvasHeight);

  for (let i = 0; i < canvasWidth; i++) {
    for (let j = 0; j < canvasHeight; j++) {
      newBoard[i][j] = deadOrAlive(i, j);
    }
  }

  gameBoard = newBoard;
  drawBoard(newBoard);

}

randomBoard(gameBoard);
drawBoard(gameBoard);

setInterval(nextGene, 150);
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Game of Life - Canvas</title>
</head>
<body>
  <canvas class="gameOfLife" width="400" height="400"></canvas>
  <script type="text/javascript" src="scripts.js"></script>
</body>

<style>
  body {
    background-color: #ffc600;
  }
  .gameOfLife{
    margin: 15px auto;
    background-color: #ff6c00;
    display: block;
  }
</style>
</html>


texts:
I am trying to fully understand interfaces and abstract classes in Java and from what I understood, I created a sample console application. Is there an error in the design or is this basically what interfaces and abstract classes are?

Animals.java (interface):

interface Animals {

    void callSound();
    int run();

}

Feline.java (abstract class):

abstract class Feline implements Animals {

    @Override
    public void callSound() {
        System.out.println("roar");
    }

}

Canine.java (abstract class):

abstract class Canine implements Animals {

    @Override
    public void callSound() {
        System.out.println("howl");
    }

}

Lion.java (class):

class Lion extends Feline {

    @Override
    public void callSound() {
        super.callSound();
    }

    @Override
    public int run() {
        return 40;
    }

}

Cat.java (class):

class Cat extends Feline {

    @Override
    public void callSound() {
        System.out.println("meow");
    }

    @Override
    public int run() {
        return 30;
    }

}

Wolf.java (class):

class Wolf extends Canine {

    @Override
    public void callSound() {
        super.callSound();
    }

    @Override
    public int run() {
        return 20;
    }

}

Dog.java (class):

class Dog extends Canine {

    @Override
    public void callSound() {
        System.out.println("woof");
        super.callSound();
    }

    @Override
    public int run() {
        return 10;
    }

}

Main.java:

public class Main {

    public static void main(String[] args) {
        Animals[] animals = new Animals[4];
        animals[0] = new Cat();
        animals[1] = new Dog();
        animals[2] = new Wolf();
        animals[3] = new Lion();

        for (int i = 0; i < animals.length; i++) {
            animals[i].callSound();
        }
    }

}


texts:
Taking the following cases in consideration.
Witch one would you prefer and why?
Suggestions appreciated.

Using Delegates

private void cmdDelete_enterClick(object sender, EventArgs e)
    {
    var accountManager = new BLAccountManager();
    accountManager.OnAccountInUse = (msg) => MessageBox.Show(msg);

    accountManager.OnConfirmation = (msg) =>
    {
        var dialogResult = MessageBox.Show(msg);
        return (dialogResult == DialogResult.OK);
    };

    accountManager.DeleteAccount(selectedAccountId);
}

 public class BLAccountManager
 {

public Action<string> OnAccountInUse;
public Func<string, bool> OnConfirmation;

public void DeleteAccount(string accountId)
{
    var bookingsUsingAccount = GetBookingsUsingAccount(accountId);
    if (bookingsUsingAccount.Count > 0)
    {
        OnAccountInUse("msg");
        return;
    }
    BankAccount account = GetAccount(accountId);
    if (OnConfirmation("confirm"))
    {
        account.Delete(false);
    }
}
}

Using Interfaces

  public interface IUICallback
  {
     void SendMessage(string message,string caption);
         bool Confirmation(string message,string caption);
  }

public class WinFormsUICallback : IUICallback
{
  public void SendMessage(string message, string caption)
  {
    MessageBox.Show(message, caption, MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation);
  }

  public bool Confirmation(string message, string caption)
  {
    DialogResult result = MessageBox.Show(message);
    return result == DialogResult.OK;
  }
}

  private void cmdDelete_Click(object sender, EventArgs e)
  {
        IUICallback uiCallback = new WinFormsUICallback();
    var accountManager = new BLAccountManager(uiCallback);
    accountManager.Delete(selectedAccountId);
  }

  public void Delete(string accountId)
  {
    BookingList bookingsUsingAccount =     bookingManager.GetBookingsUsingAccount(accountId);
    if (bookingsUsingAccount.Count > 0)
    {
            _uiCallback.SendMessage(msg, caption);
            return;
    }

    if (_uiCallback.Confirmation(confirmationMessage, caption))
        {
           account.Delete(false);
    }
   }


texts: selecting an item in a listbox to assign it as a temp variable - Review Code

texts:
I got this answer here: https://stackoverflow.com/questions/15902299/selecting-an-item-in-a-listbox-to-assign-it-as-a-temp-variable

Suppose you have loaded the lisBox1 with objects of type Genre.

lisBox1.Datasource = this.GetAllGenresFromTextFiles();
lisBox1.DisplayMember = "Genre";

Add an event to SelectionChanged of your lstBox1 :

lstBox1.SelectionChanged += lstBox1_SelectionChanged;

And then in this event, filter the data for listbox2 :

void lstBox1_SelectionChanged(object sender, EventArgs e)
{
    var movies = m_allMovies;
    var genre = lstBox1.SelectedItem as Genre;
    if(genre != null)
    {
        movies = movies.Where(m => m.Genre == genre.Genre).ToList();
    }
    lstbox2.Datasource = movies;
}

m_allMovies is a list of all the movies you have loaded from your textfiles.
You can also read your text file every time the user clicked a different genre, it will consume less memory but more CPU:

void lstBox1_SelectionChanged(object sender, EventArgs e)
{
    var movies = this.GetAllMoviesFromTextFiles();
    var genre = lstBox1.SelectedItem as Genre;
    if(genre != null)
    {
        movies = movies.Where(m => m.Genre == genre.Genre).ToList();
    }
    lstbox2.Datasource = movies;
}

The keypoint here is not to filter row from the Listbox. You must think of it as your Listbox contains a subset of all your movies.
And each time you want to add or remove rows from a Listbox, in fact you are reloading it with appropriate datas.

and my problem is this:

With the first 2 lines of code (At the top of the answer), where would i place this (I'm new to C# so .Datasource & DisplayMember are new things to me). Also where you have "this.GetAllGenresFromTextFiles" (and the same for var movies = this.GetAllMoviesFromTextFiles) --> would i place the location of my text file within the brackets?


texts:
For various reasons, I wrote this. For one, I don't like to wrap every single function in a separate class, which is too verbose.

It's a state machine based on GoTW 57 function pointer wrapping and CRTP to make things readable, at least in client code parts.

template <class Derived>
struct StateMachine {
    typedef Derived Self;
    typedef StateMachine<Derived> Base;

    //http://www.gotw.ca/gotw/057.htm
    struct Func;
    typedef Func (Derived::*UpdateFuncPtr)();
    struct Func {
        UpdateFuncPtr updateFunc;
        Func(UpdateFuncPtr ptr) : updateFunc(ptr) {}
    };

    //actual statemachine .. can be as complex as needed
    Func currentState;
    StateMachine( Func init) : currentState(init) {}
    void update() {
        UpdateFuncPtr p = currentState.updateFunc;
        Self * pThis = (Self *)this;
        Func newPtr = (pThis->*p)();
        if(newPtr.updateFunc)
            currentState = newPtr;
        }
};

The client looks like this:

struct DemoSM : StateMachine<DemoSM> {
    int check; //just checking that *this is sane
    DemoSM() : Base( &Self::update1 ) {
        check = 42;
    }
private:
    Func update1() {
        log("update1 called, check %d\n\r",check);
        return &Self::update2;
    }
    Func update2() {
        log("update called\n\r");
        return NULL;
    }
};

And just checking:

DemoSM machine;
machine.update();
machine.update();

Any critique or suggestions for improvements or gotchas welcome.  The core principle is that the state machine functions themselves code, procedurally (not declaratively in a table), how the transitions get triggered - by returning the function that needs to be called next.

This can be made marginally more interesting with separate "update" and "state transition" functions maybe with different signatures.

I could not get GoTW suggested operator() to work for taking pointer to members.  C++ is insistent on &Class::member; syntax there.


texts: Running multiple games concurrently with node.js

texts:
I am currently creating multiple games by adding objects of type Game as properties of an object called games. The names of these properties are set programmatically - for example, the first game will be a property of games called game1. Sockets joining this game will join the room room1.

Is this the right approach? It feels like there might be a cleaner way.

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Game = require('./Game.js');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
    res.sendFile('/index.html');
});

var games = {
    //Games get put here
};

var gameCount = 0;

io.on('connection', function(socket) {

    var i = gameCount;
    var arrayOfGames = [];

    while(i){
        var gameInfo = {};
        gameInfo.name = games["game"+i]["getName"]();
        gameInfo.no = games["game"+i]["getNo"]();
        arrayOfGames.push(gameInfo);
        i--;
    }

    socket.emit('populate game list',arrayOfGames);

    socket.on('create game',function(options){
        gameCount++;
        options.no = gameCount;
        games["game"+ gameCount] = new Game(options);
        socket.join('room' + gameCount);
        socket.room = 'room'+gameCount;
    });

    socket.on('join game',function(no){
        socket.join('room'+no);
        socket.room = 'room'+no;
    });

});

var port = Number(process.env.PORT || 3000);
http.listen(port, function() {
    console.log('listening on *:3000');
});

I can show the client side code and class code if you request, but I don't feel it's relevant here.


texts:
I'm using a linear search as a spell checker. I need to time my code to get averages as I'm using different searches and comparing them. However I don't believe the code I've used to time the code is accurate enough or the best method. If anyone has any suggestion that would be great.

import re
import time

start_time = time.time()
f1=open('writefile.txt', 'w+')

def linS(target, words):
    '''linear search for target in words. words need not be sorted'''
    for s in words:
        if s==target:
            return True
    return False

words = [s.strip("\n").lower() for s in open("dict.txt")]
words.sort() # sort the list

with open("text.txt" , encoding="utf8") as text:
    content = text.read().split(" ")
    content = [item.lower() for item in content]
    content = ' '.join(content)
    content = re.findall("[a-z]+", content)

for w in content:
    if not linS(w, words):
        f1.write(w+'\n')

f1.close()

print("--- %s seconds ---" % (time.time() - start_time))


texts:
I have a array-object which should look something like this and is used to create a form
const questions = [
  {
    condition_action: "selected",
    label: "What is your name?",
    question_type: "free_text",
    required: true,
  },
  {
    condition_action: "selected",
    label: "Where do you live?",
    question_options: [
      {
        label: "India",
      },
      {
        label: "china",
      },
      {
        label: "japan",
      },
    ],
    question_type: "single_answer",
    required: false,
  },
];

Now, When user is done creating the form, I have to validate the data and add a key name order in the above snippet (more below) to array-object (main array and question_options)
For validation, There are two conditions

Main array-object should have a label (if not throw error).
Question option should have at-least 1 item and the label inside it can't be empty

Basically, question_options is for multiple-select and single select drop down. So question_option should only contain value if question_type key in the above snippet is single_answer or multiple_answer
The backend api also require attribute order on the main question array and question_options array (yeah even though it's an array we could determine the order through index)
So this is the code I wrote
   const validateAndFormatdata = (questions) => {
    // we will change this to true if error exist and send it at return of this function
    let errorsExsist = false
    // we are formating data here, if error exist while validation, we change flag
    const formatedData = (questions || []).map((question, index) => {
      // delete all previous errors since we are iterating and we don't care about our previous errors
      if (Object.prototype.hasOwnProperty.call(question, "errors")) {
        delete question.errors
      }
      // There can be more than one thing wrong, hence using an array
      const newErrors = []
      // if label does not have value, add it it in errors array
      if (question.label === "") {
        newErrors.push(errorReasons.missingLabel)
      }
      if (
        question.question_type === "multiple_answer" ||
        question.question_type === "single_answer"
      ) {
        const questionOptions = _.filter(question.question_options, "label").map(
          (option, position) => {
            return {
              ...option,
              order: position
            }
          }
        )
        // if question optiond does not have single item, add it it in errors array
        if (questionOptions.length < 1) {
          newErrors.push(errorReasons.noOption)
        } else {
          question.question_options = [...questionOptions]
        }
      } else if (Object.prototype.hasOwnProperty.call(question, "question_options")) {
        // remove question otpions of question type isn't single or mult-text
        delete question.question_options
      }

      if (newErrors.length > 0) {
        errorsExsist = true
        question.errors = newErrors
      }
      return { ...question, order: index }
    })
    return {
      errorsExsist,
      data: formatedData
    }
  }

Question: I was wondering if someone can share review, optimisation and suggestions (including naming)?


texts:
Just wanted a way of attaching a jQuery search plugin to an input element (or collection) and be able to pass specific options at invoke time:

This is the plugin code

(function($){

$.fn.extend({

  enableSearch:function(opts,callback){
    return this
    .bind('focus',function(){
      $(this.form.elements).val(''); // clears all search inputs
      $(this).trigger('keyup'); // triggers the search on an empty input element
    }) // END focus bind
    .bind('keyup',function(){
       var searchData = $.extend({},'source':this.form.id,'column':$(this).attr('id'),'value':$(this).val()},opts);
       $.ajax({
         url:opts.URL,
         type:'post',
         data:searchData,
         dataType:'json'
       })
       .promise().then(function(returndata){
         callback(returndata);
       }); // END ajax call
       return false;
    }); // END bind keyup
  } //END fn enableSearch

})

})(jQuery);

This is the call on the collection:

$('input') // collection on which to enable searching
  .enableSearch({
   URL:'<server side script url>',
   extra_param:extra_param_value, // extra param which gets passed in the data to the server side fn
  },function(data){
    //actions performed on the returned data, e.g. update a list
  });

I couldn't get my idea to work until I came across the jQuery promise implmentation. Opens many doors.

Works for me - any thoughts?


texts:
In my project I use std::set with custom Compare function for maintaining an event queue. It fulfills following criteria:

event duplication is not allowed
should maintain the insertion order

(tried std::vector first, but that performed poorly because of complicated duplicate removal)

The important code is:

template <typename T>
class EventQueue {
public:
  EventQueue() : set_(std::set<DataWrap>()) {}
  void Insert(T elem) {
    set_.insert(DataWrap(elem, set_.size()));
  }

  // ....

private:
  struct DataWrap {
    T data;
    unsigned int order;
    DataWrap(T d, unsigned int o) : data(d), order(o) {}
    bool operator<(const DataWrap& other) const {
      if (data == other.data)
        return false;
      else
        return order < other.order;
    }
  };
  std::set<DataWrap> set_;
};

Naturally I want to avoid undefined behaviour. As far as I can see my Compare fulfills the requirements of strick weak ordering (irreflexive, transitive, asymetric)

Can you confirm that this code is well-defined, or am I missing something? Thanks for your time!


texts:
I am considering an approach fo BDD tests on Android.

The sample app — a simple messenger — has been made in Kotlin, so will be the tests.

I ended up with something like this :

class IGotYourMessage : Scenario<LoginActivity>(LoginActivity::class.java, {

    Given()
        .iAmOnLoginScreen()
    .When()
        .iLogin()
    .Then()
        .iSeeContactsList()
        .iSeeAContact()
    .When()
        .iSelectAContact()
    .Then()
        .iSeeMessagesList()
        .iSeeAMessage()
    .With(hashMapOf(
        "email" to "john@doe.com",
        "password" to "foo",
        "contactFirstName" to "Jane",
        "contactLastName" to "Doe",
        "messageText" to "Hello John!"
    ))
    .With(hashMapOf(
        "email" to "jane@doe.com",
        "password" to "bar",
        "contactFirstName" to "John",
        "contactLastName" to "Doe",
        "messageText" to "Hello John!"
    ))
})

I ended up with this assessment :

The Given is a start state
The When is an action
The Then is an end state
The Then is also a start state for the next action

So I can Given -> When -> Then -> When -> Then.

Each With is a test case providing its own data.

Each "step" is an extension on the Given, When or Then classes as in:

fun Then.iSeeAContact() {
    add({
        (it["contactFirstName"] as String).canSee()
        (it["contactLastName"] as String).canSee()
    })
    return this
}

The canSee method is an extension on String, using Espresso:

fun String.canSee(): String {
    onView(withText(this)).check(matches(isDisplayed()))
    return this
}

So! I am here to get feedback, criticism and/or suggestions.

This question was originally posted on StackOverflow


texts: Is this correct way to setup DB Infrastructure with repository pattern and Dapper

texts:
So, I am using Repository pattern with Dapper and ADO.NET. I have my based DB infrastructure setup as follows:
public class ConnectionFactory: IConnectionFactory
{
    private readonly string dbConnectionString = Convert.ToString(ConfigurationManager.ConnectionStrings["MyDBConn"].ConnectionString);
    private MySqlConnection _dbConnection;
    public IDbConnection GetDBConnection
    {
        get
        {
            if(string.IsNullOrEmpty(dbConnectionString))
            {
                throw new ArgumentNullException("DB Connection string received a null argument!");
            }

            if (_dbConnection == null)
            {
                _dbConnection = new MySqlConnection(dbConnectionString);
            }

            if (_dbConnection.State != ConnectionState.Open)
            {
                _dbConnection.Open();
            }

            return _dbConnection;
        }
    }

    public void CloseDBConnection()
    {
        if (_dbConnection != null && _dbConnection.State == ConnectionState.Open)
        {
            _dbConnection.Close();
        }
    }
}

And I have a Repository class that uses this infrastructure:
public async Task<IEnumerable<UserInformation>> GetUserInformation()
{
    IEnumerable<UserInformation> list;
    string querystring = "SELECT * FROM users WHERE valid=1;";

    try
    {
        list = await SqlMapper.QueryAsync<UserInformation>(_connectionFactory.GetDBConnection, querystring, param, commandType: CommandType.Text);
    }
    finally
    {
        _connectionFactory.CloseDBConnection();
    }

    return list;
}

For reading my IReader and converting to a dataset, I do the following:
public async Task<DataSet> GetOrderDetails(int oid)
{
    DataSet dataset = new DataSet();
    string querystring = "select * from orders WHERE OrderId=@oid";
    DynamicParameters param = new DynamicParameters();
    param.Add("@oid", oid);

    using (var list = await SqlMapper.ExecuteReaderAsync(_connectionFactory.GetDBConnection, querystring, param, commandType: CommandType.Text))
    {
        dataset = helper.ConvertDataReaderToDataSet(list);
    }

    return dataset;
}

Here ConvertDataReaderToDataSet is a method that only converts the IReader to a Dataset.
The problem that I having is that I am getting the following error after a while (from logs):
2/10/2021 12:37:44 AM
Type: Exception
Error Message: error connecting: Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool.  This may have occurred because all pooled connections were in use and max pool size was reached.
Method Name: GetOrderDetails

I have researched this error and it suggests a memory leak. Can you guys help me identify what is the problem and review my DB infrastructure setup?
Edit: After a discussion, I have changed the implementation to this:
public async Task<IEnumerable<UserInformation>> GetUserInformation()
{
    IEnumerable<UserInformation> list;
    string querystring = "SELECT * FROM users WHERE valid=1;";

    using (var conn = new MySqlConnection(dbConnectionString))
    {
        list = await conn.QueryAsync<UserInformation>(querystring, commandType: CommandType.Text);
    }

    return list;
}


texts: View for displaying nounal and verbal pages

texts:
I've got this code in my View that just list two type of links.

Here's an example output:

Nounal Pages

cleaners/house-cleaners

Verbal Pages

cleaning/house-cleaning

Here's the view code. How could this be refactored to remove duplicate and push logic and loops out of the view?

  %h3 Nounal Pages
  %ul.row-fluid
  - categories.each do |category|
    - subcategories.each do |subcategory|
      %ul
        %li= link_to "#{category.pluralised_nounal_slug}/#{subcategory.pluralised_nounal_slug}", main_app.new_pluralised_nounal_subcategory_path(category: category.pluralised_nounal_slug, subcategory: subcategory.pluralised_nounal_slug), target: '_blank'

  %h3 Verbal Pages
  %ul
  - categories.each do |category|
    - subcategories.each do |subcategory|
      - if category.verbal_slug.present? && subcategory.verbal_slug.present?
        %ul
          %li= link_to "#{category.verbal_slug}/#{subcategory.verbal_slug}", main_app.new_verbal_subcategory_path(category: category.verbal_slug, subcategory: subcategory.verbal_slug, aspect: 'verbal'), target: '_blank'


texts:
Is there too much logic in this controller (should I migrate them to the model)? How else can it be refactored?

class StatsController < ActionController::Base

    def create
        @stats = Stat.receive_stats(STATS_SOURCE)
        sport_type = @stats["sportsID"]

        Stat.categories.each do |category|
            @stats["#{category}"].each do |stat|
                Player.store_stats(stat, sport_type, category)
            end
        end
        render './index'
    end

    def show
        queried_stats = Stat.queried_stats

        @players_query.each do |player|
            queried_player = Player.find_by(name: player)
            queried_player_stats = Stat.get_stats_of(queried_player)
            if queried_player
                Stat.categories.each do |category|
                    queried_stats[:"#{category}"] << queried_player_stats["#{category}"] unless queried_player_stats["#{category}"] == nil
                end
            end
        end
        @queried_stats = queried_stats.to_json
        render './show'
    end
end


texts:
I need to delete a file when an error occurs during loading it. It is not allowed to perform async operations in a catch block.

This has lead me to writing the following code:

    public async Task LoadFromStorageFile(string fileName)
    {
        StorageFile file = null;
        Exception ex1 = null;

        try
        {
            var folder = await ApplicationHelper.GetApplicationSaveFolder();
            file = await folder.GetFileAsync(fileName);
            // ...
        }
        catch (Exception ex)
        {
            ex1 = ex;
        }

        try
        {
            if (ex1 != null && file != null)
            {
                await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
            }
        }
        catch (Exception)
        {
             //...
        }
        finally
        {
            if(ex1 != null)
                throw ex1;
        }
    }

Is there a nicer way of doing this? The rethrown exception especially bugs me.


texts: One hash with params populate two objects

texts:
I have a JSON API where a user can update a post and related details to that post. To simplify the process the user just fills in one hash and we don't expose our architecture. What I did here works but I would like to know if their is a better way. This smells to me, but I don't know why...

def update
    params['blog_post'] = params.delete 'post'
    @blog_post.update_attributes blog_post_params
    update_blog_post_groups if params['blog_post']['group_ids']
    params['blog_post_details'] = params.delete 'blog_post'
    @blog_post.blog_post_details.update_attributes blog_post_details_params
    render :blog_post, status: 200
end

blog_post_params and blog_post_details_params are strong_parameter methods.

It seems that I should use first : accepts_nested_attributes_for


texts: Finding the n th term in Fibonacci series

texts:
Solving a problem in coding contest I came across a problem, which on digging a bit lead me to the data set in this question . Since the program to enumerate and finding the solution was too complex and execution time was below par I jot down the logic to the equation of curve (a single line)

Upon further digging deep I found that I missed the series which was forming a Fibonacci Series, hence by Binet's fourmla I found the nth term of the series which was even efficient. Here is the code

import math
import sys

def powLF(n):
    if n == 1:     return (1, 1)
    L, F = powLF(n//2)
    L, F = (L**2 + 5*F**2) >> 1, L*F
    if n & 1:
        return ((L + 5*F)>>1, (L + F) >>1)
    else:
        return (L, F)

def fib(n):
    if n & 1:
        return powLF(n)[1]
    else:
        L, F = powLF(n // 2)
        return L * F

def sum_digits(n):
   r = 0
   while n:
       r, n = r + n % 10, n // 10
   return r

def _print(string):
    fo = open("output.txt", "w+")
    fo.write(string)
    fo.close()

try:
    f = open('input.txt')
except IOError:
    _print("error")
    sys.exit()
num = f.readline()
try:
   val = int(num)
except ValueError:
    _print("error")
    sys.exit()

sum = sum_digits(int(num))
f.close()

if (sum == 2):
    _print("1")
else:
    _print(str(int(math.ceil(fib(sum)))))

Although still the code doesn't seem to match the par criteria, how can I optimize the code further ?


texts:
I'm new to programming, but want to build up a good habit of code review so that I can develop best practice. It's been couple of weeks I'm coding in C and my knowledge, so far, is data types, conditions, arrays, loop and, very minimal, pointers.

I'm creating multiple search and sorting algorithms - not only to understand them better, but also solidifying my understanding of concepts.

Please review and provide your advice so that I can get better:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
printf("How many numbers do you want to enter? ");
int len = get_int();

int input[len]; // creating an array to store values

for (int i=0; i<len; i++)
{
    printf("Enter %ith number: ", i+1);
    input[i] = get_int();
}

// determining minimum and maximum value
int min = input[0];
int max = input[0];

for (int i=1; i<len; i++)
{
    if (input[i]>max)
    {
        max = input[i];
    }
    if (input[i]<min)
    {
        min = input[i];
    }
}

// creating an array for all the digits needed
int digits[max+1];

for (int i=0; i<max+1; i++)
{
    digits[i] = 0; //giving all the elements of the array a default value
}

// counting numbers
for (int i=0; i<len; i++)
{
    digits[input[i]] = digits[input[i]] + 1; // increasing the value of default digit element (default is 0) by 1 each time
}

printf("Minimum = %i\n", min);
printf("Maximum = %i\n", max);
printf("Inputed integers are: ");

for (int i=0; i<len; i++)
{
    printf("%i ", input[i]);
}

printf("\n");

// count sort algorithm
int j=0;
for (int i=0; i<max+1; i++)
{
    if (digits[i] == 0) // if the default value is zero, the value is disregarded, because it's not used
    {
        //
    }
    else
    {
        do
        {
            input[j] = i; // updating the element's value with i
            j++; // updating j's value so that the next integer is stored in an updated address
            digits[i] = digits[i] - 1; // decreasing the count in digits by 1, tells that it's values are being accounted for
        }
        while(digits[i] != 0); //when digits hit 0, it becomes useless again and breaks the loop
    }
}

printf("The sorted numbers are: ");
for (int i=0; i<len; i++)
{
    printf("%i ", input[i]);
}
printf("\n");
}


texts: Program that prints out the initials of a given name

texts:
#include <string.h>
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>

int main(void)
{
    // store user input
    char * name = get_string();

    // print out the first character of firts string
        printf("%c", toupper(name[0]));

    // iterate through name
    for (int i = 0, n = strlen(name); i < n; i++)
    {
        // if i'th character is a space print next character as uppercase
        if (name[i - 1] == ' ')
        {
            printf("%c", toupper(name[i]));

        }

    }
    // print new line following initials
    printf("\n");

}

It does what it's supposed to do but I'm concerned about the style of the program.


texts: Simple object oriented design for an Temperature class

texts:
Design a temperature class for nurses to store patient temperature and the method of taking the temperature.
  How would you handle different units of temperature? Write a function to determine if a patient has a fever.

My approach

class Temperature
    attr_accessor :temp, :method

    def initialize(temp,method)
        @temp = temp
        @method =method
    end

end

class Celsius < Temperature

    TEMP = 37

    def has_fever
        if temp > TEMP
            true
        else
            false
        end
    end

end

class Fahrenheit < Temperature

    TEMP =98.6

        def has_fever
            if temp > TEMP
                true
            else
                false
            end
        end
end

I know there is a code duplication in Celsius and Fahrenheit class. I tried declaring has_fever method in Temperature class but it didn't work. It says "uninitialized constant Temperature::TEMP".

Is there something to improve this design?


texts:
I have a User entity. Each instance of the User class should have a first name, surname and email, and these shall never be assigned values aside from during their initialisation, since they should never change (in the context of my code).

public class User
{
    private string _firstName, _surname, _email;

    public string FirstName => _firstName;
    public string Surname => _surname;
    public string Email => _email;

    public User(string firstName, string surname, string email)
    {
        _firstName = firstName;
        _surname = surname;
        _email = email;
    }
}

As simple as it is, I'd like a quick review of the above since it's how I've started coding up all of my classes in favour of immutability (unless a particular class' property is subject to change).

For example, do you feel I should be using readonly instead? Or some other access modifier?

Also, are there any opinions on how I've declared multiple variables on one line (the privates)?


texts: Tokenizing texts from Gutenberg archive for analysis

texts:
I am writing a program to analyze books from the Gutenberg archive. The program takes the title and URL and finds the text and downloads it. Then it goes through the text and tokenizes it. Here is the code:

from urllib import request
import nltk
import os.path

canon_titles = [
    'Moby Dick',
    'Great Expectations'
]
canon_urls = [
    'http://www.gutenberg.org/files/2701/2701-0.txt',  # Moby Dick
    'http://www.gutenberg.org/files/1400/1400-0.txt'
]
# Canon_beginnings is the location of where the book actually begins in
# the text file (skips headers, publisher info, etc.)
canon_beginnings = [
    28876,
    886
]
# canon endings exists just to grab a small amount of text for prototyping
canon_endings = [x + 500 for x in canon_beginnings]
canon_raw = [None] * len(canon_titles)
canon_tokens = [None] * len(canon_titles)
canon_words = [None] * len(canon_titles)
canon_words2tokens = [None] * len(canon_titles)
canon_pos = [None] * len(canon_titles)

# Now I combine all these together into a dictionary
canon_dict = {z[0]: list(z[1:]) for z in zip(canon_titles, canon_urls, canon_beginnings, canon_endings, canon_raw, canon_tokens,
                                             canon_words, canon_words2tokens, canon_pos)}

# Now I go through each title in the dict and see if I already have the text (I rerun this in Jupyter Notebook sometimes)
# And if not I grab it from online
for x in canon_dict:
    print("Working on {}".format(x))
    if canon_dict[x][3] == None:
        print("{} does not already exist, grabbing the text".format(x))
        url = canon_dict[x][0]
        response = request.urlopen(url)
        canon_text_draft = response.read().decode('utf8')
        canon_dict[x][3] = canon_text_draft[canon_dict[x][1]:canon_dict[x][2]]
    else:
        print("Already have this text, skipping")

# OK, now we'll tokenize, do parts of speech, etc.
def tokinze_text(raw_text):
    tokens = nltk.word_tokenize(raw_text)
    return tokens

# Now let's find the tokens
for x in canon_dict:
    print(canon_dict[x][3])
    canon_dict[x][4] = tokinze_text(canon_dict[x][3])

I would like to go much further with this - extracting parts of speech, rare words, etc., but I'm worried that my basic data structures are wrong. The python dictionary is feeling unwieldy as it gets larger. Should this entire thing be done in a pandas dataframe instead? Also, should the raw text be held in a separate structure from the rest? If I want to run a bunch of analysis on some of the results (like the tokenized text), will having the massive raw text slow everything down?


texts: A command line reader buffering the commands in Java

texts:
Until now, all my command readers expect the entire command on a single line, so that it may be read with the call scanner.nextLine(). This code here caches the input line and after each Enter attempts to build command(s) from the currently stored lines. If no commands may be built, the previous lines remain in the line list, and the entire program expects more input.

Here is what I have:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CommandLineReader {

    private static final String COMMAND_SEPARATOR = ";";
    private static final String QUIT_COMMAND = "quit";
    private static final String PROMPT = "> ";

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        StringBuffer stringBuffer = new StringBuffer();
        List<String> lineList = new ArrayList<>();

        main_loop:
        while (true) {
            System.out.print(PROMPT);
            String inputLine = scanner.nextLine();
            lineList.add(inputLine);
            stringBuffer.delete(0, stringBuffer.length());

            for (String line : lineList) {
                stringBuffer.append(line.trim()).append(' ');
            }

            String bufferContent = stringBuffer.toString().trim();
            String[] bufferCommands = bufferContent.split(COMMAND_SEPARATOR);
            boolean lastCommandTerminated =
                    bufferContent.endsWith(COMMAND_SEPARATOR);

            if (!lastCommandTerminated && bufferCommands.length < 2) {
                continue;
            }

            if (lastCommandTerminated) {
                for (String bufferCommand : bufferCommands) {
                    String command = bufferCommand.trim();
                    System.out.println(command + COMMAND_SEPARATOR);

                    if (command.equals(QUIT_COMMAND)) {
                        break main_loop;
                    }
                }

                lineList.clear();
            } else {
                for (int i = 0; i < bufferCommands.length - 1; ++i) {
                    String command = bufferCommands[i].trim();
                    System.out.println(command + COMMAND_SEPARATOR);

                    if (command.equals(QUIT_COMMAND)) {
                        break main_loop;
                    }
                }

                lineList.clear();
                // Return the last unfinished command:
                lineList.add(bufferCommands[bufferCommands.length - 1]);
            }
        }

        System.out.println("Bye!");
        scanner.close();
    }
}

A possible session might look like this:

> yargh
> aye
> captain; abc; def; hello
yargh aye captain;
abc;
def;
> world
> ; quit;
hello world;
quit;
Bye!

My primary critique concern is usability: Can it be improved?


texts: Bubble Sort: Time and Space Complexities

texts:
Algorithm

Bubble sort, also known as sinking sort, is a sorting algorithm that repeatedly steps through a list, compares adjacent pairs and swaps them if they are not in the right order. The pass through the list is repeated, until the sorting is complete. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list.

Solution 1

This is my BubbleSort function:

def BubbleSort(l):
    for i in range(len(l)-1):
        for j in range(len(l)-1-i):
            if (l[j]>l[j+1]):
                l[j],l[j+1]=l[j+1],l[j]
    return l

which outputs:

print(BubbleSort([1,5,-5,0,10,100]))
[-5, 0, 1, 5, 10, 100]

Solution 2

With some detailed advice, here is a second solution, limited to using one list comprehension:

def BubbleSort(l):
    [l.append(l.pop(0) if i == len(l) - 1 or l[0] < l[1] else l.pop(1)) for j in range(0, len(l)) for i in range(0, len(l))]

which somewhat outputs the same:

l = [1,5,-5,0,10,100]
BubbleSort(l)
print(l)
[-5, 0, 1, 5, 10, 100]

Would you be so kind and review it? I'd also like to know about time/space complexities, if you possibly had time.


texts:
As a post processing step of a similarity matrix computation that leads to the non-negative matrix mt4_ in gpu, I am performing an assignment step to determine which element in rows/columns is most similar to which element in columns/rows. So this is more like a first-come-first-serve algorithm in which the largest similarity is picked up and then that particular row and column is excluded (by flagging the first element of that row and column --using -1.0f) and the process continues as such until all rows/columns are exhausted. The results are exported to two contiguous sub-arrays of sms one for each row-to-column and column-to-row assignment. Here is the function in which sZ is a const unsigned int equal to 5000 (mt4_, and by extension mt2, are of size sZ x sZ):

void asn(float *mt2, float *mt4_, unsigned int *sms) {

  unsigned int i, j;
  unsigned int a, b;
  register unsigned long k;
  register float mx;
  register unsigned int mm = 0, nn = 0;

  for (j=0; j<2; j++) {
    k = j*sZ;
    cudaMemcpy(mt2, mt4_, mtb, cudaMemcpyDeviceToHost);
    for (i=0; i<sZ; i++) {
      mx = -1.0f;
      for (a=0; a<sZ; a++) {
        if (mt2[a*sZ] != -1.0f)
          for (b=0; b<sZ; b++) {
            if (mt2[a*sZ+b] > mx && mt2[b] != -1.0f) {
              mx = mt2[a*sZ+b];
              mm = a;
              nn = b;
            }
          }
      }
      if (fabsf(mt2[mm*sZ+mm] - mt2[mm*sZ+nn]) <= thd)
        nn = mm;
      sms[k+mm] = nn+1;
      mt2[mm*sZ] = mt2[nn] = -1.0f;
    }
  }
}

Here thd is the const float threshold that introduces a bias towards assigning a column index to its identical row index if their similarity is a within a tolerance thd of the best available score (this is to compensate for numerical errors).

The code runs fine but my problem is that it takes too long (about 100 seconds on my compute node), and this is something I can't afford due to the large number of calls to this function.

I am new to C and it is very well probable that I am missing straightforward performance optimizations, so I would really appreciate if you would comment in case you see a window for improvement.

Background: Blondel et al., A measure of similarity between graph vertices


texts:
I am attempting to create a lock free pool of resources and I need the ability to access any one that is not already accessed and then return it back when I do not need it. This will happen very very often in many threads and I felt that a locked queue would create a lot of contention.

My solution is a relatively simple one (lots of atomics) but that simplicity and speed is pretty important to me.

I am not very familiar with atomics and I was wondering if I missed a potentially unsafe use. Although I am aware of the lack of protection against unsafe use of these functions (releasing an index that has not been acquired) but for my use case this will never happen. Just assume I am going to use the class correctly, I know its not good practice to write code that can easily break but the purpose is to be quick; therefor, I can not make useless checks.

That being said, I would like to know if there are any ways I can improve it: are there more optimal memory orders than sequential that I can use for some of them? Is the array of atomic ints safe? Can I get away with a simple volatile array? Is the do while loop necessary in the acquire method?

If you have any other thoughts please, let me know.

#pragma once
#include <atomic>

template <typename T>
class LFPoolQueue {
public:
    const uint16_t END = 0xffff;

    LFPoolQueue(uint16_t size)
    {
        m_size = size;
        m_pool = new T[size];
        m_ptrs = new std::atomic<uint16_t>[size];
        uint16_t lindex = size - 1;
        for (uint16_t i = 0; i < lindex; i++)
            m_ptrs[i].store(i + 1);
        m_ptrs[lindex].store(END);
        m_next.store(0);
        m_last.store(lindex);
    }
    ~LFPoolQueue()
    {
        delete[] m_pool;
        delete[] m_ptrs;
    }

    int dequeue()
    {
        bool wasMaxed = false;
        struct VersionRef
        {
            uint16_t version;
            uint16_t ref;
        };
        uint32_t unsafePtr = m_next.load();
        uint32_t newPtr = 0;
        VersionRef vrOld = {};
        VersionRef vrNew = {};
        do
        {
            memcpy(&vrOld, &unsafePtr, sizeof(uint32_t));

            vrNew.version = (vrOld.version + 1) & 0x7FFFU;

            wasMaxed = vrOld.version & 0x8000U;
            vrNew.ref = m_ptrs[vrOld.ref].load();
            if (vrNew.ref == END)
            {
                if (wasMaxed)
                    return END;
                else
                {
                    vrNew.ref = vrOld.ref;
                    vrNew.version |= 0x8000U;
                }
            }

            memcpy(&newPtr, &vrNew, sizeof(uint32_t));
        } while (!m_next.compare_exchange_weak(unsafePtr, newPtr));

        if (wasMaxed)
            return dequeue();
        else
            return vrOld.ref;
    }

    void enqueue(uint16_t index)
    {
        m_ptrs[index].store(END);
        m_ptrs[m_last.exchange(index)].store(index);
    }

    uint16_t size() { return m_size; }
    T& operator[](const int index) { return m_pool[index]; }

private:
    uint16_t m_size;
    T* m_pool;
    std::atomic<uint16_t>* m_ptrs;

    std::atomic<uint32_t> m_next;
    std::atomic<uint16_t> m_last;
};

main.cpp test app

#include <iostream>
#include "LFPoolQueue.h"

int main()
{
    LFPoolQueue<int> q(3);
    q[0] = 0;
    q[1] = 1;
    q[2] = 2;

    for (int i = 0; i < 6; i++)
    {
        if (i == 3)
        {
            q.enqueue(1);
            std::cout << "returned 1" << std::endl;
        }
        else
        {
            int index = q.dequeue();
            std::cout << i << ": " << index << std::endl;
        }
    }
}

Output:

0: 0
1: 1
2: 2
returned 1
4: 1
5: 65535


texts: Iterate between dates and INSERT values in a performant way

texts:
I have created a query that populates a datapoint with random values.
The logic is simple: Iterate between the START and END dates and INSERT random values.

I want from this query to be very perfomant. For example populate every second of a year with values (what with this code will last ages). I am new to SQL statements of this complexity and I dont know the pitfalls and of it.

Are there some hidden areas in my code that can be improved? If I replace the random function with just a hardcoded value will it cause much boost?
Is a loop with a lot of INSERT INTO time consuming; Is there a better way to Insert (some kind of batch insert)?

DO $$
DECLARE --Variables
    NODE_ID         bigint      :=  11;   -- The node id of the datapoint
    TIMESTAMP_START TIMESTAMP   := '2018-12-06 22:00:00';
    TIMESTAMP_END   TIMESTAMP   := '2018-12-10 00:00:00';
    TS_STEP         INTERVAL    := '30 minute';

    MAX_VALUE integer := 100;

BEGIN
    LOOP
        EXIT WHEN TIMESTAMP_START > TIMESTAMP_END;

        INSERT INTO datapoint_values (dp_id, ts, datatype, source, int_value, float_value)
        VALUES (NODE_ID, TIMESTAMP_START, 2, 0, floor(random()*(MAX_VALUE+1)), 0);

        TIMESTAMP_START := TIMESTAMP_START + TS_STEP;
    END LOOP;
END $$;


texts: Custom ListAdapter with ViewHolder Pattern

texts:
I wrote this class for a custom list adapter for my list view. I use the view holder pattern to make the list view move smoother.

Could anyone advice tell me if I did something wrong, or some way to refine my code?

Example: defining my views. Is there way to make it faster?

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.validate.R;

import java.util.List;

/**
 * Created by Mina on 30/06/2015.
 */
public class vault_listadapter extends BaseAdapter {
    private List<Vault_item_class> vault_items;
    private Context context;
    private LayoutInflater inflater;

    TextView merchantName_tv, voucherType_tv, voucherName_tv, voucherDetail_tv, voucherValue_tv,
            issueDate_tv, expiryDate_tv, voucherCode_tv;
    ImageView barcode_imageview;

    public void vault_listadapter(Context context, List<Vault_item_class> vault_items) {
        this.context = context;
        this.vault_items = vault_items;
        this.inflater = LayoutInflater.from(context);

    }

    @Override
    public int getCount() {
        return vault_items.size();
    }

    @Override
    public Vault_item_class getItem(int position) {
        return vault_items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.vault_item, null, false);
            holder = new ViewHolder();

            holder.merchantName_tv = (TextView) convertView.findViewById(R.id.merchantName_id);
            holder.voucherName_tv = (TextView) convertView.findViewById(R.id.voucherName_id);
            holder.voucherType_tv = (TextView) convertView.findViewById(R.id.voucherType_id);
            holder.voucherDetail_tv = (TextView) convertView.findViewById(R.id.voucherDetails_id);
            holder.voucherValue_tv = (TextView) convertView.findViewById(R.id.voucherVaule_id);
            holder.issueDate_tv = (TextView) convertView.findViewById(R.id.issueDate_id);
            holder.expiryDate_tv = (TextView) convertView.findViewById(R.id.expiryDate_id);
            holder.voucherCode_tv = (TextView) convertView.findViewById(R.id.voucherCode_id);

            holder.barcode_imageview = (ImageView) convertView.findViewById(R.id.barcodeimg_id);

            convertView.setTag(holder);
        } else {
           holder = (ViewHolder) convertView.getTag();
        }

        return convertView;
    }

    static class ViewHolder {
        TextView merchantName_tv, voucherType_tv, voucherName_tv, voucherDetail_tv, voucherValue_tv,
                issueDate_tv, expiryDate_tv, voucherCode_tv;
        ImageView barcode_imageview;
    }
}


texts:
I have seen this question asked a few times, but I do not entirely understand the solutions provided.
Below is a bit of code I came up with for splitting up an arraylist into five parts. I have tested and changed the array size from 0 to 16 and it works fine.

I am sure there is a "better" way of doing this, so I would like to see what others think.

public static void main(String[] args)
{
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("A");//1
    arrayList.add("B");//2
    arrayList.add("C");//3
    arrayList.add("D");//4
    arrayList.add("E");//5
    arrayList.add("F");//6
    arrayList.add("G");//7
    arrayList.add("H");//8
    arrayList.add("I");//9
    arrayList.add("J");//10
    arrayList.add("K");//11
    arrayList.add("L");//12
    arrayList.add("M");//13
    arrayList.add("N");//14
    arrayList.add("O");//15
    arrayList.add("P");//16
    arrayList.add("X");//17

    int i1 = (int) Math.ceil(arrayList.size()/5.0);

    List<String> sublist = new ArrayList<String>();
    int x=0;
    for(int p=0; p<i1; p++)
    {
        if(arrayList.size()>=(x+5))
        {
            sublist = new ArrayList<String>(arrayList.subList(x, x+5));
            x+=5;
        }
        else
            sublist = new ArrayList<String>(arrayList.subList(x, arrayList.size()));
        for(String slist : sublist)
        {
            System.out.println("i:"+slist);
        }
    }
}


texts:
I'm working on an angular codebase that very frequently uses constructs like:

<c-whatever [action]='doSomething.bind(this)'>

to pass reference to the doSomething() method on the parent component to the child component. The bind() seems to be necessary, because Angular presumably  stores the function object somewhere and doesn't call it by getting it from the parent component.

This irks me because it's boilerplatey, and also because it makes WebStorm throw a bunch of red squiggles because typechecking in templates isn't quite bug-free yet.

(Arguably some of those should be replaced with @Output events, but that's neither here nor there, and not all of those can.)

Since Typescript only supports stage 2 decorators, I can't use the @bound decorator in the stage 3 proposal documentation, so I tried rolling my own TS-compatible one:

function bound<T extends Function>(target: any, key: string|symbol, pd: TypedPropertyDescriptor<T>) {
    const value = pd.value;
    delete pd.value;
    delete pd.writable;
    pd.get = function() {
        console.log('get()', {'this':this});
        return value && value.bind(this);
    }
};

Is there anything that sticks out here? Is it okay to delete value and writeable on the passed in descriptor or would it be better to return a new descriptor object?