Getting the Twitter account from various input formats I have an input for users to enter a Twitter account in any different way and I want to extract the user account.

For example:

twitters = [
    "www.twitter.com/twitteruser1",
    "@twitteruser2",
    "twitteruser3",
    "https://twitter.com/twitteruser4",
    "https://www.twitter.com/twitteruser5",
    "www.twitter.com/twitteruser6",
    "http://www.twitter.com/twitteruser7",
    "http://www.twitter.com/twitteruser8",
    "twitter.com/twitteruser9"
]

The script that I've written to extract the data is the following:

twitters.each do |twitter|
    # for the url
    twitter_user = twitter.match(/twitter.com\/([^\/.]*)$/)
    if twitter_user != nil
        puts twitter_user[1]
        next
    end

    # for @ beginning
    twitter_user = twitter.match(/^@([^\/.]*)$/)
    if twitter_user != nil
        puts twitter_user[1]
        next
    end

    # if we arrive, we haven't found any coincidence
    puts twitter

end

It actually works, outputting the following:

twitteruser1
twitteruser2
twitteruser3
twitteruser4
twitteruser5
twitteruser6
twitteruser7
twitteruser8
twitteruser9

But as I'm really newbie in Ruby I wanted to check for possible improvements.

You can use a ruby case statement to check for different regex matches.  If a match is found, it is by definition not nil, so it removes the need for a nil check as well.

twitters.each do |twitter|
  case twitter
    # for the url
    when /twitter.com\/([^\/.]*)$/
      puts $1

    # for @ beginning
    when /^@([^\/.]*)$/
      puts $1

    # if we arrive, we haven't found any coincidence
    else
      puts twitter
  end
end

When ruby does a regex match, any capture groups are assigned to the global variables $1, $2, $3, and so on.  See this question on StackOverflow for more details about the mechanic.

Note on your regex: If you want the capture groups to actually contain anything, you should change the asterisk to a plus: ([^\/.]+).  Without the plus, "www.twitter.com/" will be captured by one of the regex.  With the plus, that string will fall into the default case.


Generates a randomized locally-administered unicast MAC address This is the first time I've attempted writing something in bash, and would appreciate any feedback or criticism to make it better.

#! /bin/bash
macArr=( 0 0 0 0 0 0 )
for ((i=0; i < ${#macArr[@]}; ++i))
do
    let "byte=$RANDOM%255"
    # the first byte must have the least significant bits set to "10"
    # in order to identify as a locally administered unicast MAC
    if [ $i -eq 0 ];then
        let "byte=(((byte>>1)|1)<<1)"
    fi
    prependZero=$([ $byte -lt 16 ] && echo 1 || echo 0)
    # convert byte from decimal int to hex string
    byte=$(printf "%x" "$byte")
    # uppercase any letters in the string
    macArr[$i]="${byte^^}"
    if [ $prependZero -eq 1 ];then
        macArr[$i]="0${macArr[$i]}"
    fi
done
printf "%s" "${macArr[@]}"

Interesting idea, and pretty good first Bash script.

Bash arithmetics

Instead of this:

let "byte=$RANDOM%255"

I find this more readable:

((byte = RANDOM % 255))

You can use math like this within ((...)), without $ of variables, and with spaces around operators to keep the expressions nicely readable.

You can use this in conditions too,
in fact, instead of this:

if [ $i -eq 0 ];then

It's better to write like this:

if (( i == 0 )); then

And here, this is really awkward, as you are running a sub-shell, and storing the output of echo commands:

prependZero=$([ $byte -lt 16 ] && echo 1 || echo 0)

When it could be simply:

((prependZero = byte < 16))

Padding with 0

Since you already use printf to convert from integer to hexadecimal,
you can actually use it to 0-pad too:

byte=$(printf "%02x" "$byte")

This will pad with zeros on the left to make it 2-digits wide

Suggested implementation

With the above tips, the script can be simpler and cleaner.

#!/bin/bash

macArr=( 0 0 0 0 0 0 )
for ((i = 0; i < ${#macArr[@]}; ++i))
do
    ((byte = RANDOM % 255))

    # the first byte must have the least significant bits set to "10"
    # in order to identify as a locally administered unicast MAC
    if (( i == 0 )); then
        ((byte = ((byte >> 1) | 1) << 1))
    fi

    # convert byte from decimal int to hex string
    byte=$(printf "%02x" "$byte")

    # uppercase any letters in the string
    macArr[$i]="${byte^^}"
done
printf "%s" "${macArr[@]}"


Intersect knockoutjs observablearray using linqjs I wrote a extender function to observableArray in knockout js. What I'm looking for is a way to extract the intersection records based on one property. This works well on smaller number of arrays, but shows pretty poor performance in larger arrays. I dont know if it is the observables that makes it slower?

How would you guys write it?

obsArray2 - The array to compare with

Key - Name of the property to compare between

ko.observableArray.fn.intersect = function (obsArray2, Key) {
    var self = Enumerable.From(ko.unwrap(this));
    var arrValues1 = self.Select(function (item) { return ko.unwrap(item[Key]); });
    arrValues2 = Enumerable.From(ko.unwrap(obsArray2)).Select(function (item) { return ko.unwrap(item[Key]); });
    var IntersectedValues = arrValues1.Intersect(arrValues2).ToArray();

    return self.Where(function (item) { return IntersectedValues.contains(ko.unwrap(item[Key])) }).ToArray();
    return obsArray1.Intersect(obsArray2).ToArray();
};

I would not use linq.js for anything time sensitive, it is known to be slow, definitely compared to just using old skool for loops and arrays. Which is what I would use.

Other than, if I were to write this, I would consider naming some thing differently:

obsArray2 -> observableArray, there is no obsArray1, and it was not clear at first if obs means there are objects in the array or it is an observable arrays.
self -> anything but self which usually refers to this, perhaps enum1 ?
arrValues1 really contains an Enumerable which is not really an array, confusing, I would perhaps have chosen set1 because in maths, intersections are made of sets or enum1 because that is what the variable type is
Same for arrValues2 of course
intersectedValues -> I would have gone for simply intersection

Furthermore,

You have 2 return statements, there can be only one
It seems silly to go back to self and filter out only elements that are in the intersection, can't you build the return value from intersectedValues ?


Filtering data from an exisiting table using psycopg2+sqlalchemy I am using psycopg2 & sqlalchemy to connect to a database and extract information from a table as follows:
def db_connection():
        eng = db.create_engine('my_URI')
        conn = eng.connect()
        return eng, conn

def table_conn():
    engine, connection = db_connection()
    metadata = db.MetaData()

    admin_table = db.Table(
        'myTableName',
        metadata,
        autoload=True,
        autoload_with=engine
    )
    return engine, connection, admin_table

def get_table_data(user_id):
    _, connection, table_data = table_conn()

    # first filter using user_id and sort the data by datetime column
    query = db.select([table_data]).where(
        table_data.columns.user_id == user_id,
    ).order_by(
        table_data.columns.created_at.desc()
    )
    result = connection.execute(query).fetchall()

    # 5th element is time
    # filtering the data to find data that has been saved at the same time
    # making it the latest data
    time = result[0][5]
    time_filtering_query = db.select([table_data]).where(
        table_data.columns.created_at == time
    )
    time_result = connection.execute(time_filtering_query).fetchall()
    return time_result

The functions: db_connection() & table_conn() are connecting to the database and the table respectively.
In the get_table_data function, I am doing the following:

Use the user_id to filter the table
Order the table in desc order on the created_at column (which is the 5th column of the table)
Extract the first created_at value (which is result[0][5] in the code above)
And use this extracted value to filter the table again

In the code, I am hardcoding the column index in the result[0][5] part. Is there a way the above code can be modified to avoid hardcoding of the values and filter the values, if possible, based on the column names or in any other neater way?

You should avoid doing [0] after your query. Instead, add a .limit(1) at the end of your select.
SQA supports named column references on individual result tuples. So in addition to supporting [5], which is (as you've identified) a bad idea - it should just support .time assuming that's what your column name is. However, even better is - rather than selecting the entire table_data - simply select only the column you want.


Dynamic List Application as first Vue.js App Task Description:

Create a div-element and take control over it using a Vue-Instance.
Print an array of hobbies into the div-element. Provide some default hobbies.
Add a 'New Hobby' button and a text-input element. So that the user can add additional hobbies.
When a hobby list-item is clicked, it shall be removed from the list.
Add a "Hobby deleted"-paragraph which is only shown when a hobby-item has been deleted at least one time.
Above the list of hobbies add a hobby-counter which shows the current count of hobby-items.
Style the hobby-list depending on whether you have more or less then 3 hobbies in the list.
Outsource  your hobbies (the list-item elements) into a component (so that it becomes re-usable).

Here's my solution for the points 1 to 7:

new Vue({
  el: '#app',
  data: {
    hobbies: [{
        name: 'Running'
      },
      {
        name: 'Chess'
      },
      {
        name: 'Cooking'
      },
      {
        name: 'Hiking'
      }
    ],
    newHobby: '',
    deleted: false
  },
  methods: {
    addHobby: function() {
      this.hobbies.push({
        name: this.newHobby
      });
    },
    removeHobby: function(event) {
      let updatedHobbies = this.hobbies.filter((hobby) => {
        return hobby.name !== event.target.textContent.trim();
      });

      this.hobbies = updatedHobbies;

      if (!this.deleted) {
        this.deleted = true;
      }
    },
    setStyle: function() {
      if (this.hobbies.length < 3) {
        return 'pink';
      } else if (this.hobbies.length === 3) {
        return 'orange';
      } else {
        return 'cyan';
      }
    }
  }
});
#app {
  max-width: 800px;
  margin: 0 auto;
}

li {
  margin: 10px;
}

Hobbies: {{ hobbies.length }}

    <input type="text" id="newHobby" v-model="newHobby" />
    <button v-on:click="addHobby" id="addNewHobby">Add New Hobby</button>

Hobby deleted!

    {{ hobby.name }}

Is everything done in a good way and manner?

Where could my implementation been improved?

Any ideas how to solve point 8?

There I get finally stucked.

Looking forward to read your comments and answers.

At the moment all your current hobbies only consists of a name. I think you could use a simple string instead of wrapping it in an object (for point 8 this is not possible though, of course).
No need to check if (!this.deleted) before setting this.deleted = true;
setStyle should be a computed property
You can use @click instead of v-on:click, you can also use :style instead of v-bind:style (just syntactic sugar)
I would put the v-if="deleted" on the <div id="deleted-message"> instead of the inner <p> element.


Automatic Databinding of controls to Model I have developed a prototype framework (MVVM) where control on the form is bound to a model property using a naming convention and its UI behavior is controlled using custom attributes.

As of now the control name is divided into two parts - 3 part prefix and then the Name of the property in model to bind to.

For eg txtFirstName textbox is bound to FirstName in model. During construction/load, all controls are looped through -

BaseEdit baseEdit = (BaseEdit) control;
baseEdit.DataBindings.Add("EditValue", viewModelBindingSource,
                          baseEdit.Name.Remove(0, 3),
                          true, DataSourceUpdateMode.OnPropertyChanged);

There are some other attributes such as [ReadOnly], [Unbound] which are used to control the UI behavior.

baseEdit.Properties.ReadOnly = Util.GetReadOnlyAttributeValue(
    control.Name.Remove(0, 3), viewModel.GetType());

I am thinking of doing the looping the other way around, ie the Model properties, using a Bound attribute. Bound[ControlName, PropertyName]

Bound["txtFirstName", "EditValue"]
FirstName

All the dropdown type controls, combobox, dropdown, checkeddropdown etc are autofilled by using a 'Key' from their tag property.

if (control.GetType() == typeof(LookUpEdit) &&
    !string.IsNullOrEmpty(Convert.ToString(control.Tag))) //Exact match
{
       LookUpEdit lookUpEdit = (LookUpEdit)control;
       DataBinding.InitializeLookUpEdit(lookUpEdit, lookUpEdit.Tag.ToString());
}

I took the biggest data-entry form with around 45 controls and tested the framework.

Is the above approach suitable for a big project? Any suggestions for improving the framework?

IMHO Anything that relies on controls' Tag property is fishy. In 15 years of VB4-5-6/VBA and then WinForms development, every single time I saw the Tag property assigned, there was a better way to solve the problem. I think using that property more often than not violates the principle of least surprise (POLS), because it's not typical to put anything in there - if anything it means a control is begging to be derived from that control's class, and featured with the relevant properties - which is obviously too much trouble to be worth the while.
That's my rant against using the Tag property. That said it looks rather clean, much cleaner than this similar question, but it suffers from the same issue:

WinForms applications are better off with the Model-View-Presenter pattern.
[...] if you want to simulate WPF behavior in WinForms, the real thing will be much less trouble, and leave you with much cleaner code.
Sorry if that's not what you wanted to hear...

For a big project I'd seriously consider either MVP or MVVM with WPF.


Get tuple data in an array containing only one element from another tuple Example: I want to select tuple in an array(t_bet), which contains just one element from judge_tpl = (5,12,24). For example, (3, 4, 5, 16, 30) is ok while (3, 12, 24, 29, 30) is not because it contains two elements.

t_bet = [(3, 12, 24, 29, 30),
 (3, 13, 18, 19, 22),
 (1, 11, 16, 17, 22),
 (3, 4, 5, 16, 30),
 (1, 11, 15, 20, 24)]

lst = []
for i in t_bet:
    if (5 in i) and (12 not in i) and (24 not in i ) :
        lst.append(i)
    elif (5 not in i) and (12 in i) and (24 not in i ):
        lst.append(i)
    elif (5 not in i) and (12 not in i) and (24 in i ):
        lst.append(i)

lst: [(3, 4, 5, 16, 30), (1, 11, 15, 20, 24)]

I have to list all combinations using if..elif,which is inconvenient especially when there are so many elements in judge_tpl.

Notice: The tuples in t_bet have same lengths while there are more than 10 elements in  judge_tpl.

You don't need parenthesis around the conditions in your if statements
if x in y and another_x in y is the same as if (x in y) and (another_x in y)

Use list comprehensions when possible see PEP8#202

Use intersection of sets to get how many elements occur in both tuples
If duplicated don't matter (as they do not in your code) it is possible to convert the tuples into sets and check if the intersection between the sets are 1 (Meaning there is only 1 element that occurs in both) Like @Maarten Fabré suggested

JUDGE = (5, 12, 24)

def valid_bet(bets):
    return [bet for bet in bets if len(set(bet) & set(JUDGE)) == 1]
    # return [bet for bet in best if len(set(bet).intersection(set(JUDGE))) == 1]
    # set_a & set_b == set_a.intersection(set_b)

if __name__ == "__main__":
    bets = [(3, 12, 24, 29, 30),
            (3, 13, 18, 19, 22),
            (1, 11, 16, 17, 22),
            (3, 4, 5, 16, 30),
            (1, 11, 15, 20, 24)]
    print(valid_bet(bets))


Methods to search for a client in MySQL by ID or by phone I have this code that returns a client object, but to do it I use two methods.

How can I improve this to be more efficient and ensure it meets common standards?

    //Method that returns a client from a string
    private static Cliente ObtenerCliente(string query)
    {
        try
        {
            abrirConexion(); //Static method that opens a connection

            cmd = new MySqlCommand(query, mySqlConexion);
            MySqlDataReader dataReader = cmd.ExecuteReader();

            if (dataReader.Read())
            {
                return new Cliente(
                    Convert.ToInt32(dataReader["id_cliente"]),
                    dataReader["nombre_cliente"].ToString());
            }
            else
            {
                dataReader.Close();
                return null;
            }
        }
        catch (MySqlException e)
        {
            MessageBox.Show(e.ToString());
            return null;
        }
        finally
        {
            cerrarConexion(); //Static method that closes the connection
        }
    }

    //Method that returns a customer from a phone number given
    public static Cliente ObtenerCliente_Telefono(string telefono)
    {
        string query = "SELECT * FROM clientes WHERE (telefono1_cliente = '" + telefono + "' OR telefono2_cliente = '" + telefono + "');";
        return ObtenerCliente(query); //Metodo que hace la consulta
    }
    public static Cliente ObtenerCliente_Id(int id)
    {
        string query = "SELECT * FROM clientes  WHERE id_cliente = " + id + ';';
        return ObtenerCliente(query);
    }

Nothing wrong with Cliente ObtenerCliente accepting the query text.

Suffers from non-deterministic.  You are only going to get the first but without an order by then SQL will just pick one for you.

using is a better approach in my opinion

For sure I don't like

  Static method that opens a connection

Create the connection and let it be properly disposed

private static Cliente ObtenerCliente(string query)
{
    using (Connection mySqlConexion = new Connection(conString))
    {
        try
        {
            //abrirConexion(); //Static method that opens a connection
            mySqlConexion.Open();
            using (cmd = new MySqlCommand(query, mySqlConexion))
            {
                using (MySqlDataReader dataReader = cmd.ExecuteReader())
                {
                    if (dataReader.Read())
                    {
                        return new Cliente(
                        Convert.ToInt32(dataReader["id_cliente"]),
                        dataReader["nombre_cliente"].ToString());
                    }
                    else
                    {
                        //dataReader.Close();  let the using dispose
                        return null;
                    }
                }
            }
        }
        catch (MySqlException e)
        {
            MessageBox.Show(e.ToString());
            return null;
        }
        finally
        {
             //cerrarConexion(); //Static method that closes the connection
        }
    }
}


Print which CPU flags are set at the start of the program This is my first "real" x86 program developed from scratch. Please critique:

format PE console
entry start

include 'win32a.inc'

section '.text' code executable
start:  pushf
        push hello
        call [printf]
        pop ecx
        pop eax
check_carry_flag:
        mov dx, ax ; ax has flags reg
        test ax, 1h
        jnz carry_flag_set
        mov esi, edx
check_parity_flag:
        mov eax, esi
        test ax, 4h
        jnz parity_flag_set
        mov esi, edx
check_aux_flag:
        mov eax, esi
        test ax, 10h
        jnz aux_flag_set
        mov esi, edx
check_zero_flag:
        mov eax, esi
        test ax, 40h
        jnz zero_flag_set
        mov esi, edx
check_sign_flag:
        mov eax, esi
        test ax, 80h
        jnz sign_flag_set
        mov esi, edx
check_dir_flag:
        mov eax, esi
        test ax, 400h
        jnz dir_flag_set
        mov esi, edx
check_OF_flag:
        mov eax, esi
        test ax, 800h
        jnz OF_flag_set
jmp endme

carry_flag_set:
        mov esi, edx
        push carry_flag
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_parity_flag
parity_flag_set:
        mov esi, edx
        push parity_flag
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_aux_flag
aux_flag_set:
        mov esi, edx
        push aux_flag
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_zero_flag
zero_flag_set:
        mov esi, edx
        push zero_flag
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_sign_flag
sign_flag_set:
        mov esi, edx
        push sign_flag
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_dir_flag
dir_flag_set:
        mov esi, edx
        push dir_flag_set
        call [printf]
        pop ecx
        mov edx, esi
        jmp check_OF_flag
OF_flag_set:
        mov esi, edx
        push OF_flag
        call [printf]
        pop ecx
endme:
        push p
        call [system]
        pop ecx

        push 0
        call [ExitProcess]
section '.rdata' data readable
        hello db 'The flags are: %X', 10, 0
        p db 'pause>nul'
        carry_flag db 'Carry flag set', 0
        parity_flag db 'Parity flag set', 0
        zero_flag db 'Zero flag set', 0
        sign_flag db 'Sign flag set', 0
        dir_flag db 'Direction flag set', 0
        OF_flag db 'Overflow flag set', 0
        aux_flag db 'Aux flag set', 0

section '.idata' data readable import
        library kernel32, 'kernel32.dll', \
                msvcrt,   'msvcrt.dll'
        import kernel32, ExitProcess, 'ExitProcess'
        import msvcrt, printf, 'printf', \
        system, 'system'

You have a bit of code duplication that could and should be removed to avoid mistakes. FASM supports macros that you can use to remove duplicated parts.

One can define a check_flag macro:

macro check_flag op1, op2
{
   local flag_not_set
   test eax, op1
   jz flag_not_set
   push eax
   push op2
   call [printf]
   pop eax
   pop eax
flag_not_set:
}

A bit of explanation. This macro will do all the work that is required to check if a specific flag is set (specified as operand op1) and if so print the message specified by operand op2. We need to specify also our label as local so that there is no label duplication when macro is placed in code multiple times. We also keep the flags to be restored after printing.

Having this we can simplify the code a bit to basically this:

    check_flag 1h, carry_flag
    check_flag 4h, parity_flag
    check_flag 10h, aux_flag
    check_flag 40h, zero_flag
    check_flag 80h, sign_flag
    check_flag 400h, dir_flag
    check_flag 800h, OF_flag

Which such approach it is easy to add new ones, just by writing:

    check_flag 200h, interrupt_flag

You could also add a new line to those strings so that, they are a bit separated from each other when printing like this:

  aux_flag db 'Aux flag set', 13, 10, 0

The whole program:

format PE console
entry start

include 'win32a.inc'

section '.text' code executable

macro check_flag op1, op2
{
   local flag_not_set
   test eax, op1
   jz flag_not_set
   push eax
   push op2
   call [printf]
   pop eax
   pop eax
flag_not_set:
}

start:  pushf
    push hello
    call [printf]
    pop ecx
    pop eax

    check_flag 1h, carry_flag
    check_flag 4h, parity_flag
    check_flag 10h, aux_flag
    check_flag 40h, zero_flag
    check_flag 80h, sign_flag
    check_flag 400h, dir_flag
    check_flag 800h, OF_flag

    push p
    call [system]
    pop ecx

    push 0
    call [ExitProcess]

section '.rdata' data readable
    hello db 'The flags are: %X', 10, 0
    p db 'pause>nul'
    carry_flag db 'Carry flag set', 13,10,0
    parity_flag db 'Parity flag set',13,10, 0
    zero_flag db 'Zero flag set',13,10, 0
    sign_flag db 'Sign flag set',13,10, 0
    dir_flag db 'Direction flag set',13,10, 0
    OF_flag db 'Overflow flag set',13,10, 0
    aux_flag db 'Aux flag set',13,10, 0

section '.idata' data readable import
    library kernel32, 'kernel32.dll', \
            msvcrt,   'msvcrt.dll'
    import kernel32, ExitProcess, 'ExitProcess'
    import msvcrt, printf, 'printf', \
    system, 'system'


Clarification on "if" statement - Digital Clock Tutorial C# I am building a digital clock in C# after watching a tutorial. The code in the tutorial I need help understanding looks like this:

if (hh < 10) {
    time += "0" + hh;
}
else {
    time += hh;
}
time += ":";

Can anyone explain to me why hh < 10? Should it not be at least 12?

My end  game is to make a timer that starts at 9am and stops at 5pm. Ongoing applications under development. Looking at time money management.

Welcome to Codereview. As I can see you are having troubles understanding the line that adds a "0" in front of hh. Let's say hh is 9. Then, as 9 is smaller than 10, time will be "09", if hh is "10", or greater, it won't add that "0" at the beginning. After that (time += ":"), the program will add a ":" which would represent the hours in the clock and a ":" character afterwards, like "10:" or "09:". So, When it adds the minutes, the algorithm will use a similar if statement, like this:

if (hh < 10) {
    time += "0" + hh;
}
else {
    time += hh;
}
time += ":";
if (mm < 10) {
    time += "0" + mm;
}
else {
    time += mm;
}

at the end the time that will be shown, will look something like "09:09", and such.


Simplify Generic Method I am writing a GenericDeserializer for Apache Kafka. My class implements IDeserializer<T> from Confluent.Kafka.Net package. I need to supply a Deserialize method which has this signature, T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context). But I also need to use Deserializers class of Confluent because it implements some low level details such as decoding a big endian message from network as primitive types, as byte array, as UTF8 string etc. How can I simplify this method. One example of simplification may be removing the use of casts which I introduced to make the compiler happy.
My logic in this method is like this, use every supported type in already implemented Deserializers class. For other types that are not deserialized with the help of this class, use Json Serialization. Here is my code:
public class GenericDeserializer<T> : IDeserializer<T>
{
    public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context)
    {
        var type = typeof(T);

        if (type == typeof(double))
        {
            var retVal = Deserializers.Double.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(float))
        {
            var retVal = Deserializers.Single.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(int))
        {
            var retVal = Deserializers.Int32.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(long))
        {
            var retVal = Deserializers.Int64.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(Null))
        {
            var retVal = Deserializers.Null.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(string))
        {
            var retVal = Deserializers.Utf8.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(byte[]))
        {
            var retVal = Deserializers.ByteArray.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (isNull)
        {
            return default;
        }

        return JsonSerializer.Deserialize<T>(data, new JsonSerializerOptions()
        {
            PropertyNameCaseInsensitive = true
        });
    }
}

Here is the source of Deserializers class from Confluent.Kafka
https://github.com/confluentinc/confluent-kafka-dotnet/blob/master/src/Confluent.Kafka/Deserializers.cs

You can define a mapping between Types and the Deserializers. You can do this for example like this:
public class GenericDeserializer<T> : IDeserializer<T>
{
    private readonly ImmutableDictionary<Type, object> _deserializers =
        new Dictionary<Type, object>
    {
        { typeof(double), Deserializers.Double },
        { typeof(float), Deserializers.Single },
        { typeof(int), Deserializers.Int32 },
        { typeof(long), Deserializers.Int64 },
        { typeof(Null), Deserializers.Null },
        { typeof(string), Deserializers.Utf8 },
        { typeof(byte[]), Deserializers.ByteArray },
    }.ToImmutableDictionary();
}

You can't use the IDeserializer<T> in the Dictionary's Value type parameter that's why it is an object.
Then all you need to do is to make a lookup call and try to cast the value to IDeserializer<T>
if (_deserializers.ContainsKey(typeof(T)))
{
    var deserializer = _deserializers[typeof(T)] as IDeserializer<T>;
    ...
}

If the type was found then you can make branching based on the isNull value:
if (_deserializers.ContainsKey(typeof(T)))
{
    var deserializer = _deserializers[typeof(T)] as IDeserializer<T>;
    var retVal = deserializer.Deserialize(data, isNull, context);
    return !isNull ? retVal : default;
}

If it is not found then you can use the JsonSerializer as your fallback.
return JsonSerializer.Deserialize<T>(data, new JsonSerializerOptions()
{
    PropertyNameCaseInsensitive = true
});

The final code would look like this:
public class GenericDeserializer<T> : IDeserializer<T>
{
    private readonly ImmutableDictionary<Type, object> _deserializers =
        new Dictionary<Type, object>
    {
        { typeof(double), Deserializers.Double },
        { typeof(float), Deserializers.Single },
        { typeof(int), Deserializers.Int32 },
        { typeof(long), Deserializers.Int64 },
        { typeof(Null), Deserializers.Null },
        { typeof(string), Deserializers.Utf8 },
        { typeof(byte[]), Deserializers.ByteArray },
    }.ToImmutableDictionary();

    public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context)
    {
        if (_deserializers.ContainsKey(typeof(T)))
        {
            var deserializer = _deserializers[typeof(T)] as IDeserializer<T>;
            var retVal = deserializer.Deserialize(data, isNull, context);
            return !isNull ? retVal : default;
        }

        return JsonSerializer.Deserialize<T>(data, new JsonSerializerOptions()
        {
            PropertyNameCaseInsensitive = true
        });
    }
}


Getting s3 objects with Rails I have been using aws-sdk gem with Rails, for uploading and downloading objects. I believe it's working fine.

Demo code:

begin

s3 = AWS::S3.new
bucket = s3.buckets[ENV['BUCKET_NAME']]
bucket.objects.create(fname, data)
object = bucket.objects[fname]
exported_url   =  object.url_for(:get, {expires: 3.weeks,
             response_content_type: "text/csv", response_content_disposition:
"attachment; filename=#{fname}.csv"}).to_s
rescue Aws::S3::Errors::ServiceError => e
 puts e.message
end

Are there any issues if uploading a large file to s3? I mean, that issues will affect my code. Will it handle that situation for large files? Should I go for the multipart options in s3?

There are two issues you should watch out for:

This will block the current thread while it's running. For a large file, this could be a substantial amount of time. You should consider moving this code out to a Sidekiq (or similar) worker, so that you aren't blocking threads in your web app.
When you rescue exceptions, you just puts them, which you're likely to ignore in production. You should be logging that exception to a place that you can get ahold of it later. I would personally just not rescue it and use BugSnag or similar in my application to ensure that errors are collected and kept for resolution.


An R function for checking whether a variable is binary or continuous This function takes a numeric vector and returns "con" if it's continous and "bin" if it's binary.

It does not take the multinomial case into account, i.e. if a variable y has three possible values 0, 1, 2, it's treated like a continuous variable.

Code:

checkBinaryTrait = function(v, naVal="NA") {
    if(!is.numeric(v)) stop("Only numeric vectors are accepted.")
    vSet = unique(v)
    if(!missing(naVal)) vSet[which(vSet == naVal)] = NA
    vSet = vSet[which(!is.na(vSet))]
    if(any(as.integer(vSet) != vSet)) return("con")
    if(length(vSet) > 2) return("con")
    "bin"
}

Tests:

v = c(1, 1.1, 1, 1.1, NA)
checkBinaryTrait(v)
v = c(1, 2, 1, 2, NA)
checkBinaryTrait(v)
v = c(-9, 2.3, 4.1, -9, -9)
checkBinaryTrait(v, -9)
v = c(-9, 2, 4, -9, -9)
checkBinaryTrait(v, -9)

Using the return statement is not recommended.
You can get the same effect by rewriting with else if and else, like this:

checkBinaryTrait = function(v, naVal="NA") {
  if (!is.numeric(v)) stop("Only numeric vectors are accepted.")
  vSet = unique(v)
  if (!missing(naVal)) vSet[vSet == naVal] = NA
  vSet = vSet[!is.na(vSet)]

  if (any(as.integer(vSet) != vSet)) "con"
  else if (length(vSet) > 2) "con"
  else "bin"
}

I also removed the unnecessary which calls.
This code still passes all your tests.

Actually the last statement can be further simplified to:

  if (any(as.integer(vSet) != vSet) || length(vSet) > 2) "con"
  else "bin"

You might also want to change the return type to TRUE or FALSE,
in which case the last statement would become simply:

  !(any(as.integer(vSet) != vSet) || length(vSet) > 2)

And then, how about renaming checkBinaryTrait to is.binary?

Finally, the <- operator is more common than =.
For example Google's style guide explicitly forbids using =.


PHP PDO mysql multiple queries mak I ran into a problem, I'm using MyIsam tables in mysql database, using PDO to connect.

In all my tests (calling for 1 user everything works fine), now having around 300 users connected at the same time all day making requests is really really slowing down mySQL. Ive got my.cnf with (key_buffer=512M and max_connections=200) my server is VPS with 2GB RAM and 3 cores. And each table has around 40K records

All queries/updates/inserts are super slow, but I've discovered that this PHP file is the root of the problem, it's requested every 10 seconds for every user (not at the same time, and if the call fails it's delayed another 10 seconds):

 //User Info -----------------------
    $sqlcommand = "SELECT * FROM tbl_User WHERE FB_ID='". $FB_ID . "'";
    $statement = $pdo->query($sqlcommand);
    $row = $statement->fetch(PDO::FETCH_ASSOC);

    if($row) {
       //Do its thing
    }
//How Many Gifts are there-----------------
    $sqlcommand = "SELECT * FROM tbl_Gifts_Sent WHERE FB_ID='". $FB_ID . "'";

    $statement = $pdo->query($sqlcommand);
    $row = $statement->fetchAll();

    if (!$row) {
        $amountOfGifts=0;
    } else {
        foreach ($pdo->query($sqlcommand) as $row){
                $amountOfGifts=$amountOfGifts+1;
        }
    }

//Daily Leaderboard King---------------
    $sqlcommand = "SELECT * FROM tbl_Leaderboard_DAY WHERE Today = " . $midnight . " ORDER BY XP_Gain DESC";

    $statement = $pdo->query($sqlcommand);
    $row = $statement->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        //Do its thing
    }

//-------- THE STATE ON ALL Themes WITH GIFTS AND ALL
    $sqlcommand = "SELECT * FROM tbl_User_Reel WHERE FB_ID='". $FB_ID . "'";
    foreach ($pdo->query($sqlcommand) as $db_gmInfo){
         //DO its thing
    }

this 4 queries are on the same php file.

Im a newbie in this and this is my first php mysql project, so I'm thinking there's gotta be a better way to do this, :S any recommendations, help or pointers on how to make it work super fast are greatly appreciated! thank you

One thing I can see right off the bat is that you're likely to be selecting more data than you need. A good rule of thumb is to never use SELECT * FROM. Only select the columns that you need for your query.

For example, in your gifts query you could change the query to "SELECT COUNT(*) FROM tbl_Gifts_Sent WHERE FB_ID='". $FB_ID . "'"; and only ever get one row with one field to check. You could then use $row = $statement->fetch(PDO::FETCH_NUM); and examine $row[0] to find out whether there are any rows that match that $FB_ID and use that value for $amountOfGifts. That will save you from loading too much data (all the fields in tbl_Gifts_Sent as well as saving you from looping over a potentially large resultset in PHP (much slower than letting MySQL do the work). Revised full (untested) code below:

//How Many Gifts are there-----------------
    $sqlcommand = "SELECT COUNT(*) FROM tbl_Gifts_Sent WHERE FB_ID='". $FB_ID . "'";

    $statement = $pdo->query($sqlcommand);
    $row = $statement->fetch();

    if (!$row) {
        $amountOfGifts=0;
    } else {
        $amountOfGifts = $row[0];
    }

Also, I don't know where you're getting your query variables like $FB_ID, but it's probably a bad idea to trust them not to be SQL Injection vectors. You should probably be using PDO::prepare to build your statements; that will at least minimise the injection risk.


Code for calculating the books dispatched Recently I came across this, here is an excerpt from it,

  This is another problem about Indraneel's library. His library has one
  long shelf. His books are numbered and he identifies the books by
  their number. Each book has a distinct number.

  He has lost many books, since many of his friends borrow his books and
  never bother to return them. He does not want to lose any more books
  and has decided to keep a record of all books that he lends to his
  friends. To make the task of borrowing a book a little difficult, he
  has given the following instructions to his friends: when they borrow
  a book, they must record in a register its position from the left
  among the books currently on the shelf.

  Suppose there are 5 books in the library and they are arranged as
  follows:

  26  1  42  15  3

  If someone walks in and borrows the book 42, then he will record 3 in
  the register because this book is the third from the left on the
  shelf. Now the shelf looks like this:

  26  1  15  3

  If the next person borrow the book 3, he writes down 4 in the register
  since this is currently the fourth book from the left on the shelf,
  and so on.

  Indraneel knows the initial arrangement of the books in his library at
  the time that he introduced the register system. After a while he
  examines his register and would like to know which books have been
  borrowed. Your task is to write a program to help Indraneel solve this
  problem.

My approach is count from left if the value of the book is -1 then skip the the book , when the count is equal to the count of the book then print the name of the book and make that value -1.But this approach though correct is giving time limit exceeded on a handful of testcases. Anyone having a better approach for this problem?

Here is the code:

#include <iostream>
#include <vector>

int main(){
    //Input for the number books with the values
    int m;
    std::cin >> m;
    std::vector<int>books(m);

    for(int i=0;i<m;i++){
        std::cin>>books[i];
    }
    //Input for the dispatches made
    int n;
    std::cin >> n;
    std::vector<int>taken(n);

    for(int i=0;i<n;i++){
        std::cin >> taken[i];
    }

    for(int i=0;i<n;i++){
        int bookNum = taken[i]-1;                       //Get the position of book needed
        int k=0;
        for(int j=0;j<m;j++){                          //Go through the book array
            if(books[j] != -1){
                if(k == bookNum){
                    std::cout << books[j] << std::endl; //Display the name if the k is equal
                    books[j] = -1;
                    break;
                }
                k++;                                    //Increment k if the value of the book is not negative
            }
        }
    }

    return 0;
}

Here are the testcases.

There are some minor nits about the general code

Separate operators like >> with spaces, that makes the code much easier to read. Also you should separate language constructs like for or while with a space afterwards, to readily separate them from function calls.
You should use range based loops when you already have the vector fully initialized, it is much more concise.

int numBooks;
std::cin >> numBooks;
std::vector<int> books(numBooks);
for (auto &book : books){
    std::cin >> book;
}

The return 0; at the end is not necessary anymore with modern compilers.
You should prefer pre increment ++book over post increment book++, as the later involves a copy (at least for non trivial data types)
Actually your code itself is way to complicated. Rather than assigning a new vector you can just shrink the old one

int numTaken;
std::cin >> numTaken;
for (int book = 0; book < numTaken; ++book) {
    int bookId;
    std::cin >> bookId;
    std::cout << books[bookId];
    books.erase(bookId);
}

Full code

#include <iostream>
#include <vector>

int main() {
    std::ios_base::sync_with_stdio(false);
    size_t numBooks;
    std::cin >> numBooks;
    std::vector<int> books;
    books.reserve(numBooks);
    for (size_t book = 0; book < numBooks; ++book) {
        size_t bookId;
        std::cin >> bookId;
        books.push_back(bookId);
    }

    size_t numBorrowed;
    std::cin >> numBorrowed;
    for (size_t borrow = 0; borrow < numBorrowed; ++borrow) {
        size_t bookId;
        std::cin >> bookId;
        std::cout << books[bookId] << "\n";
        books.erase(bookId);
    }
}


Quicksort using pointers As an exercise, I've written quicksort algorithm in C using pointers. Please comment and help me find the cases where it breaks (if any).

void qsort(int *, int, int);
void swap(int *, int *);

void qsort(int *v, int left, int right)
{
    int i, *last;

    if (right <= left)
        return;
    last = v + left; //choosing the first element as the pivot
    for (i = left + 1; i <= right; i++)
        if (*(v + i) < *(v + left))
            swap(++last, v + i); //swapping the numbers < pivot
    swap(v + left, last);
    qsort(v, left, last - v - 1); //sub-array containing numbers < pivot
    qsort(v, last - v + 1, right); //sub-array containing numbers >= pivot
}

void swap(int *i, int *j)
{
    int temp;

    temp = *i;
    *i = *j;
    *j = temp;
}

I'd make right an exclusive instead of inclusive upper bound, that is write i < right instead of i <= right and last - v instead of last - v - 1.

This has the advantage of making the base call qsort(v, 0, length) instead of qsort(v, 0, length - 1).


Print a string of characters with their occurrences I have worked out a solution for this problem, however I am trying to reach an O(1) solution without the use of two for loops. The output should read as a3b2c4d1 for the solution below.

i.e. I want to be able to describe which is a "greedy" approach and the tradeoffs of each.

Here is my current solution:

let countLetters = (str) => {
    let arr = str.split(''),
      map = {},
      ret = '';

    for (var i = 0; i < arr.length; i++) {
      map[arr[i]] = str.match(new RegExp(arr[i], 'g')).length
    }

 for (let i in map) {
     ret += `${i + map[i]}`
    }

    return ret;
}

console.log(countLetters('aaabbccccd'));

Can someone explain to me what is the time complexity of the current solution, and possible how to think in better terms of reaching a better time complexity?

Big \$O\$
Time complexity is a ratio of some input metric (e.g. the number of character in the string) to the number of instructions required to complete the function.
In this case the metric \$n\$ is the string length. The first loop that uses String.match must for each character check all characters to find a count. That means at least \$n * n\$ steps need to be performed to do the operation.
Thus the complexity of the function is said to be \$O(n^2)\$
If you think about how you would solve it on paper. You would go over each character once with a list of characters found adding 1 to each count as you find them. This would have a time complexity of \$O(n)\$
Maps use a hash function to locate an item \$O(1)\$. So the time complexity to find out if you have counted a character before is \$O(1)\$, rather than your regExp \$O(n)\$
function countLetters(str) {
    const charCounts = {};
    var result = "";
    for (const c of str) {
        if (charCounts[c]) { charCounts[c] += 1 }
        else { charCounts[c] = 1 }
    }
    for (const [char, count] of Object.entries(charCounts)) {
        result += char + " has " + count + " ";
    }
    return result;
}

The second loop to create the result, will count in the worst case each character again. Thus the number of instructions is \$2n\$ In big \$O\$ notation the scale \$2\$ is insignificant compared to powers, even if it was \$1000000n\$ we ignore the scale and make it just \$n\$
It can not be done with less complexity as you need to check every character at least once. Because you do not know what the characters are before you check them.
Style Notes.

Use ; or not, never use them sometimes.
Careful with indentation. You indent 4 and sometime 2 spaces, use either not both.
Use Function declarations in favor of arrow functions when in global scope.
Variables that do not change should be declared as constants const
Use for of rather than  for in


Laravel Scope get request data/param I want to pass the param from the request on the scope method in the model and serve it as json to be rendered by select2. Which is better?
1. Pass request from the controller like this
controller:
public function selectJson(Request $request)
{

    $request = Customer::getSelect2($request)

    return \Response::json($request);
}

model:
public function scopeGetSelect2($query, $request)
{
    $customers = $query->select('id','name')->orderBy('name','asc')->where("name", "like", "%".$request->q."%");

    if($request->city_id)
    {
        $customers = $query->where("city_id", $request->city_id);

    }
    $customers = $customers->limit(5)->get();
    $formatted_tags = [];

    foreach ($customers as $customer) {
        $formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
    }

    return $formatted_tags;
}

2. Use request() helper in the model
Controller:
public function selectJson()
{

    $request = Customer::getSelect2()

    return \Response::json($request);
}

Model:
public function scopeGetSelect2($query)
{
    $customers = $query->select('id','name')->orderBy('name','asc')->where("name", "like", "%".request()->q."%");

    if($request->city_id)
    {
        $customers = $query->where("city_id", request()->city_id);

    }
    $customers = $customers->limit(5)->get();
    $formatted_tags = [];

    foreach ($customers as $customer) {
        $formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
    }

    return $formatted_tags;
}

Which is better in performance and best practice? And should I format the return in the model like above codes or in the controller like below:
public function selectJson()
{

    $customers = Customer::getSelect2()->limit(5)->get();
    $formatted_tags = [];

    foreach ($customers as $customer) {
        $formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
    }

    return \Response::json($formatted_tags);
}

Or any other method or concern that I need to know?
Thanks in advance

Laravel scopes are not a way to create static methods, they should be used to add parts to a database query. They should always return a query builder.
Aim to make your scopes as small as possible so you can then combine them together to make more complex queries.
It doesn't matter if you use the Request passed in to the controller or the request() helper, use whichever you prefer.
If you aren't going to reuse the getSelect2() method you don't need to add it to the model, just do the query in the controller. If you do need to repeat the query elsewhere you can make a new class that can build the options ($formatted_tags).
class Customer extends Model
{
    // ...

    public function scopeNameLike($query, $name): void
    {
        $query->orderBy('name','asc')->where("name", "like", "%{$name}%");
    }

    // ...
}

class Controller
{
    public function selectJson(Request $request)
    {
        return Customer::nameLike($request->q)
            ->when($request->city_id, function ($query, $value) {
                $query->where('city_id', $value);
            })
            ->limit(5)
            ->get(['name', 'id'])
            ->map(function ($item) {
                return ['id' => $item->id, 'text' => $item->name];
            });
    }
}

Is return something in scope really bad practice? What about the normal method in the model? I have so many tables/models that I need to format to select2 format. Am I need to format it in every controller? – Muhammad Dyas Yaskur

I was mistaken that scopes shouldn't return a value, as per the Laravel documentation they should return a query builder instance. It would be bad practice to return any other value from a scope.
If you need many of these types of queries for different models you can create a helper class that can then be reused.
class Select2
{
    public static function customer(Request $request)
    {
        // Query moved from controller
    }
}

class Controller
{
    public function selectJson(Request $request)
    {
        return Select2::customer($request);
    }
}


Panagram solution for a given string I want to check if the given string is a Panagram or not.

  A Panagram is a sentence containing every letter of the alphabet at least once.

This is what I've come up with as solution:

import java.util.Scanner;

public class Panagram {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String inputString = "";

        System.out.print("Enter the input: ");
        inputString = sc.nextLine();
        sc.close();

        if (inputString != null && inputString.length() > 0) {
            System.out.print("The given string, \"" + inputString + "\", is " + (isPanagram(inputString) ? "" : ("not ")) + "a Panagram");
        } else {
            System.out.print("Not a valid string!");
        }
    }

    /**
     * Checks if the given input is a panagram.
     *
     * @param inputString
     * @return boolean
     */

    private static boolean isPanagram(String inputString) {

        if (inputString.length() < 26) {
            return false;
        }

        inputString = inputString.toLowerCase();

        for (char i = 'a'; i <= 'z'; i++) {
            if (!(inputString.contains(i + ""))) {
                return false;
            }
        }

        return true;
    }

}

Any review comments or suggestions?

List of well known Panagrams.

Your solution is actually quite decent, and the code style is good, etc. There are a couple of style changes I would recommend:

In a for loop, the variable i typically indicates an int, and people tend to use c to indicate a char. So, I would write for (char c = 'a'; c <= 'z'; c++) {...
your isPanagram method should be public.

Now, about the algorithm, your code will scan the result as many as 26 times. In reality, this will happen fast, and there's no pressing need to change that, but it could be faster, but would require a little work to get it right.

If you reverse the logic, and just iterate through each characters in the String once, then you can reference it back to an index for the characters.... It would go something like:

boolean[] seen = new boolean[26]; // or a constant for the number of characters.
int stillNeed = seen.length;
for (int i = 0; i < inputString.length(); i++) {
    char c = Character.toLowerCase(inputString.charAt(i));
    if (c >= 'a' && c <= 'z') {
        c = c - 'a';
        if (!seen[c]) {
            seen[c] = true;
            stillNeed--;
            if (stillNeed == 0) {
                return true;
            }
        }
    }
}
return false;

Now, for long strings, the above will be more efficient than your solution. It goes through each character in the string just once, but it has to create a list of what's been seen, or not. If it is a new character, it has to count it as seen.

Your mileage may vary.


Increment number in jQuery I have this number returned from an Ajax request: 015-0011-00001. I want to increment the last part of the number (00001) on document load. What I did was get the last number and increment it then combine the numbers again. Is there a cleaner way of incrementing this number without slicing the number into many parts?

DEMO

var data = [{"code":"456100010011","incrementingnumber":"015-0011-00001"}];

var code = data[0].code;
var inc = data[0].incrementingnumber;
var res = code.slice(-4);
var inc1 = inc.slice(-4);
//alert(inc1);
var inc2 = parseInt(inc1) + 1;

var incrementvalue = ("00000" + inc2).slice(-5); // -> result: "0001"

console.log("015-" + res + "-" + incrementvalue);

var data = [{"code":"456100010011","incrementingnumber":"015-0011-00001"}];

var code = data[0].code,
    inc = data[0].incrementingnumber;
var inc1 = inc.split('-');
inc1[2] = ('00000' + ++inc1[2]).slice(-5);

document.write(inc1.join('-'));

You don't need the code.slice, but you'd still need to split your incrementingnumber value.


Pattern search in a text Is this a practical algorithm for pattern matching in a text? Assume text can be very large, is there anything I can do to speed up the performance?

 public static int match(String pattern, String text) {
    int i = 0;
    int M = pattern.length();
    int N = text.length();
    int ret = -1;
    while (i < N) {
        StdOut.printf("i = %d\n", i);
        int j = 0;
        ret = i;
        while (j < M) {
            if (pattern.charAt(j) == text.charAt(i)) {
                ++i;
                ++j;
                continue;
            } else {
                ++i;
                break;
            }
        }
        if (j == M) return ret;
    }
    return -1;
}

Is this a practical algorithm for pattern matching in a text?

Are you trying to reinvent the wheel?
String has .indexOf for exactly this purpose.
These statements will print the same things, for example:

// both prints 2
System.out.println(match("hello", "x hello, there"));
System.out.println("x hello, there".indexOf("hello"));

// both prints -1
System.out.println(match("hello", "x, there"));
System.out.println("x, there".indexOf("hello"));

  Assume text can be very large, is there anything I can do to speed up the performance?

In this example, using String.indexOf is probably the fastest you can get.
If you have a more complex pattern,
like a regular expression,
then using Pattern will be more efficient than hand-coded solutions.

If you're reinventing the wheel intentionally, then here are some tips to improve your implementation:

Rename the method to indexOf(text, pattern), as "match" doesn't imply that it actually returns the starting index of the matched pattern. indexOf will also look familiar to other developers
The continue statement is unnecessary when it's the last statement in a loop
The int ret = -1 initialization before the loop is pointless: the value is reassigned in every iteration
It's better to declare variables in the smallest possible scope. So ret should be declared inside the loop.

The same goes for i, it would be better to convert that outer while loop to a for loop: for (int i = 0; i < N; ) {


Calling a function within stored procedure to derive a value I am trying to write a sql storeprocedure that basically returns a derived value from an outcome of a function call. The  derived field returns the difference in days and if the difference is less than 24 hours then returns hours. It is working as desired but just need to ensure if the approach is right.

Storeprocedure query

SELECT ua.ID AS UserAgreementID
          , A.ID AS AgreementID
          , A.Code
          , A.ComplianceCode
          , A.Name
          , A.Description
          , A.Version
          , ua.UserAgreementStateID
          , uas.Name AS UserAgreementStateName
          , ua.AcceptanceWindowExpiry
          , declaration.GetDifferenceInDaysOrHours(ua.AcceptanceWindowExpiry) AS NoOfDays
          , A.Data
          , pa.ID AS AuthoredByID
          , pa.FirstName + ' ' + pa.LastName AS AuthoredByName
          , A.Authored
          , ia.ID AS IssuedByID
          , ia.FirstName + ' ' + pa.LastName AS IssuedByName
          , A.Issued
        FROM declaration.Agreement AS A
        INNER JOIN declaration.UserAgreement AS ua
            ON A.ID = ua.AgreementID
        INNER JOIN declaration.UserAgreementState AS uas
            ON ua.UserAgreementStateID = uas.ID
        LEFT JOIN common.Person AS pa
            ON A.AuthoredBy = pa.ID
        LEFT JOIN common.Person AS ia
            ON A.IssuedBy = ia.ID
        WHERE ua.UserID = 607
        AND uas.Code IN ('ISS', 'DEF') -- Issued, Deferred
        AND A.Draft = CONVERT(BIT, 0) -- Not a draft.
        AND A.Deleted = CONVERT(BIT, 0) -- Not deleted.
        AND ISNULL(A.Issued, '9999-12-31') <= GETUTCDATE() -- Issued date less than equal to today's date (Issued date).
        AND ISNULL(A.Expires, '9999-12-31') > GETUTCDATE()

I am not sure if writing a function and calling it within the storeprocedure has any implications and is the right way to do it. The results that I am getting are correct though. Could somebody throw some light.

CREATE FUNCTION declaration.GetDifferenceInDaysOrHours(@AcceptanceWindowExpiry datetime)
RETURNS int
AS

BEGIN
    DECLARE @timeDifferenceInDays INT;
    DECLARE @timeDifferenceInHours INT;
    DECLARE @timeDifference INT;

    SELECT @timeDifferenceInDays = DATEDIFF(d,  GETUTCDATE(), @AcceptanceWindowExpiry)
    IF @timeDifferenceInDays > 1
      BEGIN
            SELECT @timeDifference = @timeDifferenceInDays
       END
    ELSE
     BEGIN
        SELECT @timeDifferenceInHours = DATEDIFF(HOUR,  GETUTCDATE(),  @AcceptanceWindowExpiry)
          IF @timeDifferenceInHours >= 0 AND @timeDifferenceInHours <= 24
             BEGIN
                SELECT @timeDifference = @timeDifferenceInHours
             END
          ELSE
            BEGIN
                SELECT @timeDifference = -1
          END
        END
        RETURN @timeDifference;
    END;

Calling a function from a stored procedure is absolutely fine.

As far as the code goes, you could reduce the number of statements.

e.g. instead of

 IF @timeDifferenceInHours >= 0 AND @timeDifferenceInHours <= 24
     BEGIN
        SELECT @timeDifference = @timeDifferenceInHours
     END
  ELSE
    BEGIN
        SELECT @timeDifference = -1
    END

I would suggest

  select @timedifference =
    case when @timeDifferenceInHours >= 0 AND @timeDifferenceInHours <= 24
         then @timeDifferenceInHours
         else -1
    end


Project Euler #6 in Ruby Question:

  Difference between the Sum of squares from 1 to 100 and the square of sums of 1 to 100.

Answer in Ruby:

range.inject(:+) ** 2 - range.map{|x| x ** 2}.inject(:+)

This one seems pretty straightforward but welcome any improvements to make it more elegant!

The elegance of Mathematics:

def sum_below(n)
    n * (n + 1) / 2
end

def sum_squares_below(n)
    n * (n + 1) * (2*n + 1) / 2
end

limit = 1000
puts sum_below(limit) ** 2 - sum_squares_below(limit)

The Math under  n * (n + 1) / 2

We have some natural numbers and we want to find their sum, the list is:

1, 2, 3, 4 ... n

Now we can note that the sum of n + 1 is equal to the sum (n - 1) + (1 + 1) and is in turn equal to (n - 1 - 1) + (1 + 1 + 1). In practice in the following

1, 2, 3, 4, 5, 6

We can see that 1 + 6 == 2 + 5 == 3 + 4 == 7.

We must repeat this (sum that equals n + 1)  (n / 2) times so we arrive to the final formula:

sum_below(n) = (n + 1) * n / 2


Retrieving a list, by iterating through a list I'm using VB.Net, MVC 5, EF 6, and Linq.  I have a list of Integers (category attribute IDs).  I need to create a second list of String (values).  There will be one string for each integer.

I am currently accomplishing my task like this:

Function getValues(catAttIDs As List(Of Integer), itemID As Integer) As List(Of String)
    Dim db As New Model1
    Dim values = New List(Of String)

    For i As Integer = 0 To catAttIDs.Count - 1
        Dim catAttID = catAttIDs(i)

        Dim currentValue = (From row In db.tblEquipment_Attributes
                     Where row.Category_Attribute_Identifier = catAttID _
                     And row.Unique_Item_ID = itemID
                     Select row.Value).SingleOrDefault()

        values.Add(currentValue)
    Next

    Return values
End Function

I have a strong feeling that there is a better way to do this, but I have not been able to find the information I'm looking for.

I'm particularly interested in changing this code so that the database is called once for the list, instead of calling the database 5 or 6 times as I work my way through the list.

You're looking for the LINQ-equivalent of an IN clause in SQL. So something like this:

SELECT value FROM tblEquipment_Attributes
WHERE Category_Attribute_Identifier IN (<list of integers>)
AND Unique_Item_ID = itemID;

So what you could do is write your LINQ statement to see if the Category_Attribute_Identifier is in the list. Then your function will look something like this:

Function getValues(catAttIDs As List(Of Integer), itemID As Integer) As List(Of String)
    Dim db As New Model1

    Dim currentValues as List(Of String) = (From row In db.tblEquipment_Attributes
                     Where catAttIDs.Contains(row.Category_Attribute_Identifier) _
                     And row.Unique_Item_ID = itemID
                     Select row.Value).ToList()

    Return currentValues
End Function

Note that ToList will create a List<T>, where T is the type of the elements. As long as Value in your db is a varchar, it'll be a List.


Finding the closest node I have a function that I need to optimize:

def search(graph, node, maxdepth = 10, depth = 0):
    nodes = []
    for neighbor in graph.neighbors_iter(node):
        if graph.node[neighbor].get('station', False):
            return neighbor
        nodes.append(neighbor)
    for i in nodes:
        if depth+1 > maxdepth:
            return False
        if search(graph, i, maxdepth, depth+1):
            return i
   return False

graph should be a networkx graph object. How can I optimize this?  This should find the closest node in the network with 'station' attribute to True.

def search(graph, node, maxdepth = 10, depth = 0):
    nodes = []
    for neighbor in graph.neighbors_iter(node):
        if graph.node[neighbor].get('station', False):
            return neighbor
        nodes.append(neighbor)

Why store the neighbor in the list? Instead of putting it in a list, just combine your two loops.

for i in nodes:

i typically stands for index. I suggest using neighbor to make your code easier to follow

    if depth+1 > maxdepth:
        return False

This doesn't relate to this individual node.  What is it doing inside this loop?

        if search(graph, i, maxdepth, depth+1):
            return i
   return False

Failure to find is better reported using None rather than False.


JavaScript / jQuery stopwatch Just as a learning exercise, I set out making a stopwatch without looking up how to do it etc.

I know it will have been done many times before.  I'm just looking for some feedback on what I should do to make the code more efficient / cleaner / in keeping with standards etc.

This is the result

// declare vars
var secondsDiv = $("#seconds");
var minsDiv = $("#mins");
var hoursDiv = $("#hours");
var interval = null;
var timer = false;

// return the value of a given div
function getCurrentValue(value) {
  return value.html();
}

// reset the value of a chosen div to 00
function resetValue(value){
  value.html("00");
}

// check if values are more than 59 to progress the timer
function check59() {
  var currentSec = getCurrentValue(secondsDiv);
  var currentMins = getCurrentValue(minsDiv);
  var currentHours = getCurrentValue(hoursDiv);
  // check the seconds to become a minute
  if (currentSec > 59) {
    currentMins++;
    if (currentMins < 10) {
      minsDiv.html("0" + currentMins);
    } else {
      minsDiv.html(currentMins);
    }
    resetValue(secondsDiv);
  }
  // check the minutes to become an hour
  if (currentMins > 59) {
    currentHours++;
    if (currentHours < 10) {
      hoursDiv.html("0" + currentHours);
    } else {
      hoursDiv.html(currentHours);
    }
    resetValue(minsDiv);
  }
}

// add seconds
function addSecond() {
  var currentSec = getCurrentValue(secondsDiv);
  currentSec++;
  if (currentSec < 10) {
    secondsDiv.html("0" + currentSec);
  } else {
    secondsDiv.html(currentSec);
  }
  check59();
}

// run the initial addSecond function every second
$("#startTimer").click(function(){
  if (timer===false) {
    timer = true;
    interval = setInterval(addSecond, 1000);
  }
});

// stop the addSecond function every second
$("#pauseTimer").click(function(){
  clearInterval(interval);
  timer = false;
});

// reset all values
$("#clearTimer").click(function(){
  resetValue(secondsDiv);
  resetValue(minsDiv);
  resetValue(hoursDiv);
});

Looks pretty good! Here's a couple of pointers for you:

It's custom to declare jQuery variables with a $ prefix. This way it's easy to tell at a glance that it is a element collection. So your top variables would look like this:

var $secondsDiv = $("#seconds");
var $minsDiv = $("#mins");

Instead of:

  if (timer===false)

Consider:

if (!timer)

If you're looking for legibility there are probably a few other things I'd do differently.

Grouping your variables allows you to make a few shortcuts:

var time = {
  seconds: $("#seconds"),
  minutes: $("#mins"),
  hours:   $("#hours")
}

function getValue(timeStr) {
  return time[timeStr].html();
}

getValue('seconds')

And I'm not sure about the check59() implementation. I'm sure we could make that more efficient, and reduce the repetition.

But the next step for you is definitely to create a class for this and scope your variables, that way you'll be able to include multiple timers in the same page :)


Efficient way to add a colon before and after every word in strings inside a Series I was working with twitter data, and extracted every emoji from the data. But, when I passed that data through CountVectorizer, colons where substracted from the strings. So, the string emoji :ok_hand: :thumbs_up: turned into  ok_hand thumbs_up. I wanted to re-add those colons so then I could emojize them back. I managed to do that, but I'm quite sure my method is very inefficient. The emojis are the indexes of a coefficients DataFrame, like this:

    index              coef

ok_hand thumbs_up      0.4
    airplane           0.2

So what I did was this:

to_emojize=pd.Series(coef_mat_emoji.index)
to_emojize=to_emojize.apply(lambda x: x.split())
to_emojize=to_emojize.apply(lambda x:[':'+i+':' for i in x])
to_emojize=to_emojize.apply(lambda x: emoji.emojize(x, use_aliases=True))
coef_mat_emoji.index=to_emojize

Is there a better way to do this?

Both pandas.Series and pandas.Index have vectorized string additions. You can just do:

to_emojize = pd.Series(":" + coef_mat_emoji.index + ":")
coef_mat_emoji.index = to_emojize.apply(emoji.emojize, use_aliases=True)

Note that pandas.Series.apply passes any additional keyword arguments along to the function, so there is no need for the lambda here at all.

This will create an intermediate series from the first addition, which might not be the most memory efficient way to do this. But it is the easiest and most readable, so unless you run out of memory with this, this is what I would use.

Alternatively you could put it all into one apply call (Python 3.6+ for f-strings):

coef_mat_emoji.index = pd.Series(coef_mat_emoji.index).apply(
                        lambda x: emoji.emojize(f":{x}:", use_aliases=True))

You would have to timeit with your actual data to see if this is any faster. It might be that the call to emoji.emojize will dominate anyway.


Using Enum to Handle String literals I have a java component that was using a lot of string literals that I need to make comparisons on and return booleans based on these comparisons.

In order to make the code more robust I externalized these strings first as class constants, then after other classes started to use these constants I had to separate them to decrease the dependency between the classes.

Knowing that the best practice is not to use variable-classes dedicated for string for many reasons, and since I am using Java 6, I decided to go for enums. below is the implementation that I had in mind

public enum SecurityClassification {
    SENSITIVE("Sensitive"), HIGHLY_SENSITIVE("Highly Sensitive"), PUBLIC("Public"), INTERNAL("Internal");

    private String value;

    private SecurityClassification(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public boolean hasValue(String param) {
        return value.equalsIgnoreCase(param);
    }

    public static SecurityClassification enumForValue(String param){
        for (SecurityClassification securityClassification : SecurityClassification.values()) {
            if(securityClassification.getValue().equals(param)){
                return securityClassification;
            }
        }
        return null;
    }
}

I was wondering specifically about the enumForValue method, is this an optimal solution? is there any other better way?

It looks fine overall, but...

A few pointers

You should make private String value final too though, to clearly indicate that they cannot be modified after instantiation.
One thing to note for values() is that it always returns a new array, so for that reason, sometimes it may be recommended to also construct a lookup Map<String, SecurityClassification> to avoid the extra arrays creation.
Also, is it really OK to just return null if an invalid security classification is specified here? Depending on your implementation, you may want to consider whether you should throw an IllegalArgumentException here to have a slightly better modelling of such cases.
How is hasValue() used? In fact, can it be used in enumForValue() for a case-insensitive comparison?
Finally, enumForValue() may seem like a mouthful, you can consider a shorter name like of(). The other thing to consider is that you don't really need to express that it's an enum this method is returning.


Dynamic social media component w/ dark mode Note: This is my first post for a code review, so any feedback on what other info would be helpful to post (if any) would be much appreciated!
React component: Social.js
The component has an input of 4 properties:

dark: Boolean - if dark is supplied, the component renders white icons for contrast against a dark background
facebook: String - if facebook url is supplied, the component renders the facebook icon, else no icon at all
twitter: String - if twitter url is supplied, the component renders the twitter icon, else no icon at all
instagram: String - if instagram url is supplied, the component renders the instagram icon, else no icon at all

If only 1 social media url is supplied, the text "Follow us on: " is rendered along with the single icon
let count = 0;

function countProp (prop) {
  if (prop !== undefined) {
    if (prop.url !== ``) {
      count++;
    }
  }
  return prop;
}

const Social = props => {
  count = 0;
  let facebook = countProp(props.facebook);
  let twitter = countProp(props.twitter);
  let instagram = countProp(props.instagram);
  return (
    <>

      { (count == 1) ? Follow us on: : `` }

      { (!props.dark) ?
                ( (facebook.url !== ``) ?

                  : null )
                : ( (facebook.url !== ``) ?

                  : null ) }

      { (!props.dark) ?
                ( (twitter.url !== ``) ?

                  : null )
                : ( (twitter.url !== ``) ?

                  : null ) }

      { (!props.dark) ?
                ( (instagram.url !== ``) ?

                  : null )
                : ( (instagram.url !== ``) ?

                  : null ) }

    </>

)};

export default Social;

consider using The strict equality operator (===) over the abstract equality operator (==) , see == VS ===

avoid nested if blocks using optional chaining , it can get pretty messy if you have a lot of nested properties, it's a relatively new feature but you can always use a babel plugin.

consider a different aproach to styling ( i recommend styled-components ), adding styles like that would affect other components on the same page.

since the images urls' are hardcoded , use an object to toggle dark mode

keep your code DRY , you can use an Array of social media names and loop through it to display the icons

for counting the props , you could use Object.keys or if you have other props to pass along the social media icons, use Array.filter to check how many are there and grab the resulting array's length

snippet of the end result :
import styeld from "styled-components";

const Wrapper = styled.div`
  .social {
    display: flex;
    flex-wrap: wrap;
    align-content: center;
    justify-content: center;
  }

  .social img {
    max-height: 25px;
    margin: 0 15px;
  }
`;

const icons = {
  darkMode: {
    facebook: "facebook_white",
    twitter: "twitter_white",
    instagram: "instagram_white"
  },

  lightMode: {
    facebook: "facebook",
    twitter: "twitter",
    instagram: "instagram"
  }
}

const options = ["facebook", "twitter", "imstagram"];

const Social = props => {
  // check for dark mode
  const mode = props.dark ? "darkMode" : "lightMode";

  // count social media icons
  const count = option.filter(option => props[option]?.url ? true : false).length();

  return (
    <Wrapper>

        {/* show the text if there's at least one social media is supplied */}
        {count > 1 ? Follow us on: : ``}

        {
          // loop through the social media array to display the ones available in props
          options.map(option => props[option]?.url
            ?
               <img src={`./assets/social/${icons[mode].facebook}.svg`} alt={option} />

           : null)
        }

    </Wrapper>

  )
};

export default Social;


Converting an integer to a 3 character String (base62) I wrote a code to convert an Integer between 1 and 238328 to a unique String, formed from base62 characters (A-Za-z0-9) and of length 3. The String generated can be reconverted to get back the initial Integer.

For example, if the number was 238328 I can convert it to "zzz". I want to be able to use that String "zzz" and get back the number 238328. I have written 2 methods to perform these operations and based on my testing it is working fine.

I am looking for some inputs on making it more readable and possibly more efficient. The conversion consists of 3 nested loops which really does not look right, though I can't get my head around a better way to do this.

class Permutation {

    private final String[] DICTIONARY = new String[]{
            "0","1","2","3","4","5","6","7","8","9",
            "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
            "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

    private Map<String, Integer> codes = new HashMap<>();
    private Map<Integer, String> numbers = new HashMap<>();

    String generateCode(int num){

        int maxNumber = 238328;
        if(num > maxNumber || num < 1) return null;

        if(numbers.containsKey(num)){
            return numbers.get(num);
        }

        int counter = 0;

        for (int i = 0; i < DICTIONARY.length; i++) {
            for (int j = 0; j < DICTIONARY.length; j++) {
                for (int k = 0; k < DICTIONARY.length; k++) {
                    String code = DICTIONARY[i] + DICTIONARY[j] + DICTIONARY[k];
                    counter++;
                    numbers.put(counter, code);
                    codes.put(code, counter);
                    if(counter == num) return code;
                }
            }
        }

        return null;
    }

    int decode(String code){
        if(codes.containsKey(code)){
            return codes.get(code);
        }

        return 0;
    }
}

Your problem definition is .... odd. your code, will, for the input value 1 generate the output 000. Is that what you really want? Why do you need to 1-index the value set instead of 0-index it?

Further, your code caches all values up-to-and-including the input value in a HashMap. This can become quite large.... for the full dataset you're looking at about a quarter-million values where each is about 128 bytes of memory (a String, an Integer, and a Map.Entry plus some other overheads), or about 70 megabytes of data.

Your DICTIONARY should be an array of chars, not an array of String.

The maxNumber should be a static constant too.

Finally, you return a null value for an invalid input. That's very unconventional, you should throw an IllegalArgumentException instead.

As mentioned in a comment, you can "easily" solve your problem with a few "simple" operations.

private static final char[] DIGITS = ("0123456789"
       + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
       + "abcdefghijklmnopqrstuvwxyz").toCharArray();
private static final int BASE = DIGITS.length;
private static final int MAX_NUMBER = BASE * BASE * BASE;

public static String generateCode(int num) {
    if (num < 1 || num > MAX_NUMBER) {
        throw new IllegalArgumentException("Illegal input value: " + num);
    }

    int value = num - 1;

    char ac = DIGITS[((value / BASE) / BASE) % BASE];
    char bc = DIGITS[(value / BASE) % BASE];
    char cc = DIGITS[value % BASE];
    return new String(new char[]{ac, bc, cc});
}

Note that I compute each digit separately (in to ac, bc, and cc) and then return the combination as a string.

Further, when running the code, I discovered that you are off on your zzz assertion .... the max value you propose for zzz is wrong, what you have is yyy. - I discovered I had a text transpose of zy instead of yz in my constant.

See the code running on ideone: https://ideone.com/EZqXlJ

For the inputs supplied in the tests I get the values:

Value 0 Error Illegal input value: 0
Value 1: 000
Value 2: 001
Value 62: 00z
Value 63: 010
Value 1000: 0G7
Value 238328: zzz
Value 238329 Error Illegal input value: 238329


Invert the colors of the graph I've heard that Lbl and Goto use up memory that they don't give back. I've noticed clearing the RAM on my calculator frees up a lot of space and makes my programs run a lot faster. Any suggestions on how to minimize memory leaks here would be greatly appreciated. (This code does function correctly other than leaking memory).

:-1->B
:Lbl H
:B+1->B
:0->A
:If B=95
:Goto E
:Lbl V
:Pxl-Change(A,B)
:A+1->A
:If A=63
:Goto H
:Goto V
:Lbl E

I've represented the STO→ character, → with -> Also, the graph is 94 pixels wide and 62 pixels tall.

I've heard that Lbl and Goto use up memory that they don't give back

If you replace the following ...

:If B=95
:Goto E
... etc. ...
:Goto V
:Lbl E

... with ...

... etc. ...
:If B<95
:Goto V

... then you have eliminated the final Lbl E as well as its Goto.

I don't think you can do better than that: the remaining two gotos are required: unless you unroll the loops.


Am I correctly testing that methods from Kernel have been called? Any time I'm testing a Ruby class that calls a Kernel method such as sleep or exit, i define a singleton method on the class instance and test that it has been invoked:

it "must throttle requests" do
  sleep_was_called = false

  subject.define_singleton_method(:sleep) { |seconds|
    sleep_was_called = true
  }

  subject.request query
  subject.request query

  sleep_was_called.must_equal true
end

I have seen far more sophisticated method stub testing in RSpec, but it there a more fancy and less verbose way to do this using MiniTest?

I know MiniTest has an expectations framework, but I'm not familiar with it.  I use rspec-expectations to accomplish this, like so:

describe ClassName do
  let(:subject) { described_class.new }

  describe '#method' do
    it 'should sleep 3 times and output hello world' do
      expect(subject).to receive(:sleep).exactly(3).times
      expect(subject).to receive(:puts).with('Hello world!').exactly(3).times

      subject.method
    end
  end
end

I know this doesn't directly answer your question, but my hope is it leads you in the right direction.


Database of survey information How does this look?  It has been over a year since my database concepts class and I have never worked with MySQL.  I have chosen InnoDB as my engine because of foreign key support using UTF-8 based on advice from an earlier review.  Everything works as it should when deleting and updating, but I am worried I am doing something that may be considered bad practice.

The main table Tracker manages different survey name and descriptions.  The table Card holds information on each person who has been surveyed.  Survey holds the results of each Card response for the survey being tracked by Tracker and has a unique composite key.

If a cardID is deleted or updated the corresponding composite key of Survey will be deleted or updated.  If  a trackID is deleted or updated this will delete or update the corresponding cardID fields in Card.

ERD design image:

Is this the right way to apply a composite key in this way? Are there any changes that should be made? Are there any suggestions for changes?

CREATE TABLE `Tracker` (
 `trackID` int(11) NOT NULL AUTO_INCREMENT,
 `tName` varchar(40) DEFAULT NULL,
 `tDesc` varchar(200) DEFAULT NULL,
 PRIMARY KEY (`trackID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

CREATE TABLE `Card` (
 `cardID` int(11) NOT NULL AUTO_INCREMENT,
 `trackID` int(11) NOT NULL,
 `fName` varchar(21) NOT NULL,
 `mName` varchar(1) DEFAULT NULL,
 `lName` varchar(21) DEFAULT NULL,
 `email` varchar(50) NOT NULL,
 `isMember` int(1) NOT NULL,
 PRIMARY KEY (`cardID`),
 FOREIGN KEY (`trackID`) REFERENCES `Tracker`(`trackID`) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

CREATE TABLE `Survey` (
 `cardID` int(11) NOT NULL,
 `trackID` int(11) NOT NULL,
 `q0` int(1) NOT NULL,
 `q1` int(1) DEFAULT NULL,
 `q2` int(1) DEFAULT NULL,
 `q3` int(1) DEFAULT NULL,
 `q4` int(1) DEFAULT NULL,
 `q5` int(1) DEFAULT NULL,
 PRIMARY KEY (`cardID`, `trackID`),
 FOREIGN KEY (`trackID`) REFERENCES `Tracker`(`trackID`) ON UPDATE CASCADE,
 FOREIGN KEY (`cardID`) REFERENCES `Card`(`cardID`) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;

Just a quick thing:  int(1) probably does not mean what you think it means.

mysql> create table int_length (x int(1));
Query OK, 0 rows affected (0.04 sec)

mysql> INSERT INTO int_length VALUES (1234);
Query OK, 1 row affected (0.05 sec)

mysql> SHOW WARNINGS;
Empty set (0.00 sec)

mysql> SELECT x FROM int_length;
+------+
| x    |
+------+
| 1234 |
+------+
1 row in set (0.00 sec)

int(x) is basically used for zerofill and nothing else.  If you want a smaller data type, you'll need to use a small data type (tinyint, etc).  (Note that this doesn't apply to var types.  varchar(5) is <= 5 characters, and varchar(10) is <= 10 characters.


Map a hierarchy of nested DTO objects to a list of business objects Consider I download my data into this data structures:

public class AThingDTO
{
   int AID { get; set; }
   string AName { get; set;}
   Dictionary<int, BThingDTO> BThingsColl { get; set;}
}

public class BThingDTO
{
   int BID { get; set; }
   string BName { get; set;}
   int AID { get; set; }
   List<CThingDTO> CThingsColl { get; set;}
}

public class CThingDTO
{
   int CID { get; set; }
   string CName { get; set;}
   int BID { get; set; }
   int AID { get; set; }
}

Consider I want to map it into this data structures:

public class AThing
{
   int AID { get; set; }
   string AName { get; set;}
   List<BThing> BThingsColl { get; set; } = new List<BThing>();
}

public class BThing
{
   int BID { get; set; }
   string BName { get; set;}
   List<CThing> CThingsColl { get; set;} = new List<CThing>();
}

public class CThing
{
   int CID { get; set; }
   string CName { get; set;}
}

I did like this:

public List<AThing> MapFromDTO(Dictionary<int, AThingDTO> dtoThingsHierarchy)
{
    var mappedThings = new List<AThing>();

    foreach (var aThingDto in dtoThingsHierarchy)
    {
        var aThing = new AThing();
        aThing.AID = aThingDto.AID;
        aThing.AName = aThingDto.AName;

        foreach (var bThingDto in BThingsColl.Values)
        {
            var bThing = new BThing();
            bThing.BID = bThingDto.BID;
            bThing.BName = bThingDto.BName;

            foreach (var cThingDto in CThingsColl)
            {
                var cThing = new CThing();
                cThing.CID = cThingDto.CID;
                cThing.CName = cThingDto.CName;

                bThing.CThingsColl.Add(cThing);
            }

            aThing.BThingsColl.Add(bThing);

        }

        mappedThings.Add(aThing);

    }

    return mappedThings;
}

Is there a more elegant way / more expressive way to express this mapping? Maybe with LINQ?

The first thing you can do is assign all the properties for a thing in one line using an object initializer.  The following:

var cThing = new CThing();
cThing.CID = cThingDto.CID;
cThing.CName = cThingDto.CName;

would become:

var cThing = new CThing {CID = cThingDto.CID, CName = cThingDto.CName};

You can create a list before creating the parent thing so you can assign in the object initializer.  I don't think your code works currently because you're not specifying the DTO in the foreach loops and not getting the values from the dictionary that's passed in.  If the object initializer is too long, you can expand it to multiple lines or create and use a constructor for each class.

public List<AThing> MapFromDTO(Dictionary<int, AThingDTO> dtoThingsHierarchy)
{
    var mappedThings = new List<AThing>();

    foreach (var aThingDto in dtoThingsHierarchy.Values)
    {
        var aThing = new AThing {AID = aThingDto.AID, AName = aThingDto.AName};
        foreach (var bThingDto in aThingDto.BThingsColl.Values)
        {
            var bThing = new BThing {BID = bThingDto.BID, BName = bThingDto.BName};
            foreach (var cThingDto in bThingDto.CThingsColl)
            {
                var cThing = new CThing {CID = cThingDto.CID, CName = cThingDto.CName};
                bThing.CThingsColl.Add(cThing);
            }
            aThing.BThingsColl.Add(bThing);
        }
        mappedThings.Add(aThing);
    }
    return mappedThings;
}

Here's one way to rewrite your code using LINQ's method syntax:

public List<AThing> MapFromDTO(Dictionary<int, AThingDTO> dtoThingsHierarchy)
{
    return dtoThingsHierarchy.Values
        .Select(a => new AThing {AID = a.AID, AName = a.AName, BThingsColl = a.BThingsColl.Values
            .Select(b => new BThing{ BID = b.BID, BName = b.BName, CThingsColl = b.CThingsColl
                .Select(c => new CThing {CID = c.CID, CName = c.CName}).ToList()}).ToList()}).ToList();
}

Here's LINQ's query syntax:

public List<AThing> MapFromDTO(Dictionary<int, AThingDTO> dtoThingsHierarchy)
{
    return
       (from a in dtoThingsHierarchy.Values
        let bThings =
           (from b in a.BThingsColl.Values
            let cThings = b.CThingsColl.Select(c => new CThing {CID = c.CID, CName = c.CName}).ToList()
            select new BThing{ BID = b.BID, BName = b.BName, CThingsColl = cThings }).ToList()
        select new AThing {AID = a.AID, AName = a.AName, BThingsColl = bThings}).ToList();
}

Both LINQ methods are quite a bit shorter, but the tradeoff in this case is they're kind of tough to read.  Moving logic to the constructors could help.


Capturing a string in a specific format I have a requirement to capture a string in a specific format of * [Numeric Digits] *. This is how I have done right now but I think it would be faster with Regular Expressions. I don't have a lot of experience with RegEx, so please help me optimize this code using RegEx.

if (string.IsNullOrEmpty(BarcodeScan) && e.KeyChar.ToString() == "*")
    BarcodeScan = e.KeyChar.ToString();
else
{
    if (BarcodeScan.StartsWith("*"))
    {
        if (int.TryParse(e.KeyChar.ToString(), out i))
            BarcodeScan += i.ToString();

        else if (e.KeyChar.ToString() == "*")
        {
            BarcodeScan += "*";
            ArticleID = BarcodeScan.Substring(1, BarcodeScan.Length - 2);
        }
        else
            BarcodeScan = string.Empty;
     }
}

The above code is written in KeyPress event so I have to capture the string as the user is doing the input. Basically the first * means that the user has started entering Article ID and I keep on capturing numeric digits till he enters another *.

This means that

*2323 is valid but incomplete
*34h is invalid
*343f33 is invalid
*3434hsds3 * is invalid
*3412 * is valid and complete

How do I check for *2323 in regex?  I tried ^\*\d+ but it allows *22f as well.

Could you possibly provide more samples of your data? In any case, try this

Regex regex = new Regex(@"^[*]\d+[*]$");

If you actually expect the brackets (e.g. []) using the following:

Regex regex = new Regex(@"^[*][\[]\d+[]][*]$");


The dwindling Fibonacci I've recently taken a renewed interest in non-standard languages like Brainfuck and TIS-100. I'm currently writing a Fibonacci generator in Brainfuck which differs a bit in approach from the usual generators already around.

Since my current understanding of the language is very limited, the limited debugging capabilities in the average Brainfuck IDE and the fact that I've never written a Fibonacci generator before, I decided to write one in Python first.

The usual Fibonacci generator seems to be recursive. If I understand correctly, mine isn't. Since the goal was to produce a generator which would serve as a blueprint for it's Brainfuck equivalent, I tried writing it as straight-forward as possible.

The straight-forwardness means no fancy stuff. Exception handling is for the weak and it's too short to warrant a function just for the sake of defining a function. If this is to be re-used, the whole thing will turn into a function.

Again, it's a blueprint for an implementation in a language where such constructs don't exist.

import sys

HIGHEST_FIBO = int(sys.argv[1])

Fibo = [1, 1, 2]

for i in Fibo:
    print i

for i in xrange(HIGHEST_FIBO-len(Fibo)):
    Fibo[0] = Fibo[1]
    Fibo[1] = Fibo[2]
    Fibo[2] = Fibo[0] + Fibo[1]
    print Fibo[2]

It's speed surprised me. 2000 under 2 seconds, where print is likely the most expensive operation. It should be very memory efficient as well.

I think this is about as simple and as clear as it gets, but let's see if there is room for improvement anyway.

There is indeed room for improvement, however slim it may be.

Get rid of the list

import sys

highest_fibo = int(sys.argv[1])

f1 = 0
f2 = 1

for _ in xrange(highest_fibo):
    f1, f2 = f2, f1 + f2
    print f2,

If you want to make it even simpler, there is even a function to compute fibonacci numbers and if you are interested, I leave it up to you to find it.

Before I go, I think I should explain this part which may seem confusing:

f1, f2 = f2, f1 + f2

This takes advantage of tuple assignment in python. The process begins by creating a tuple of both the left hand side and the right hand side of the expression. Then the right hand side of the expression is evaluated. Then the process of tuple unpacking begins where in each value on the left hand side is assigned to the one on the right.
This simple python trick allows for us to write a one line swap


Generate graph in Matlab I use this Matlab code:

load ~/emailAnalysis/results.txt
results=results(size(results,1)-400:size(results,1),:)
temp = results(:,3)-1238370000;
h=plot(temp,smooth(results(:,1)),':b')
set(h,'LineWidth',1)
ylim([0 80])
xlim([max(temp)-(86400*7),max(temp)-1])
set(gca,'XGrid','on')
ylabel('Emails')
hold on
i=plot(temp,smooth(results(:,4)),'r')
j=plot(temp,smooth(results(:,5)),'-g')
k=plot(temp,smooth(results(:,6)),'m')
xlim([max(temp)-(86400*7),max(temp)-1])
set(gca,'XTick',[1:86400:(86400*max(temp))+1])
set(gca,'XTickLabel',['Mon';'Tue';'Wed';'Thu';'Fri';'Sat';'Sun'])
set(j,'LineWidth',2)
set(h,'LineWidth',1)
set(i,'LineWidth',2)
set(k,'LineWidth',2)
xlabel('Time')
title('Size of inbox over time (seven days)')
print -r3000 -djpeg /XXXX/inbox7day.jpeg
hold off

to generate this graph:

from data like:

34 2012-01-21 1327152611 5 16 10
32 2012-01-21 1327154411 5 14 9
32 2012-01-21 1327156209 5 14 9
34 2012-01-21 1327158012 5 14 9
34 2012-01-21 1327159808 5 15 9
34 2012-01-21 1327161611 5 15 9
34 2012-01-21 1327163406 5 15 9
33 2012-01-21 1327165211 5 13 9
34 2012-01-21 1327167011 5 13 9
31 2012-01-21 1327168810 4 12 8

but it's a little slow, and also probably not very elegant (it's my first use of Matlab) I'm interested in any tips for best practice, tips for speeding it up, or examples of how I might do the same things in R...

clear all;
load('results.txt');
time = results(:,3) - 1238370000;

There's no need to plot all of the points if you're going to restrict the range to the past week. So I'd suggest you find the index where the time is less than a week ago and limit your plotting to that period to reduce complexity

firstTimeIndex = find(time >= (max(time) - 86400*7), 1);

Also note that you can use 'end' instead of 'size(results,1)'

results = results(max(1,firstTimeIndex-1):end, :);
clf;
h = plot(time,smooth(results(:,1)),':b');
hold on;

Line properties like linewidth can be specified at the time of plotting

plot(time, smooth(results(:,4)), 'r', 'linewidth', 2);
plot(time, smooth(results(:,5)), 'g', 'linewidth', 2);
plot(time, smooth(results(:,6)), 'm', 'linewidth', 2);
xlabel('Time');
ylabel('Emails');
xlim([max(time)-(86400*7) max(time)-1]);
ylim([0 80]);
set(gca,'XGrid','on');
set(gca,'XTickLabel',['Mon';'Tue';'Wed';'Thu';'Fri';'Sat';'Sun']);
title('Size of inbox over time (seven days)');

I'm not sure why you are setting the resolution to 3000 dpi? Maybe you could elaborate on what you're using this for, but if your goal is high resolution and low storage size then you might like to use -dmeta for a metafile on windows, or -deps for an encapsulated postscript on unix

print -djpeg inbox7day.jpeg;

I'm not sure what you are trying to achieve with the 'XTick' property, but the vector you're passing in is extremely large (~100 million elements) which is why the code is running so slow. I'm guessing that you don't want 100 million ticks?


"Random Quote Of The Day" program Problem Statement:

  Create a class diagram and Java code for the following system and
  scenario, taking into account the possibility of future extensions.
  "The system is a command line utility that prints a short 'quote of
  the day' on the user's terminal when run. To begin with the quote is
  selected randomly from a set of hard-coded strings within the program
  itself, but that might change later on -- the quotes might be based on
  the user's history, the time of day, the date, etc.. Scenario:

  User types "java QuoteOfTheDay" on the command line.
  System prints out a quote of the day, with an attribution.

This is my code for the following:

package quoteOfTheDay;
import java.util.Random;

public class QuoteOfTheDay {

    public static void main(String[] args) {

        System.out.println();

        Random rand = new Random();
        int randomInt = rand.nextInt(20);

        switch (randomInt) {
        //Print a quote depending upon the generated random number..
        }
    }
}

Is this the right approach? Am I missing some things from the problem requirements? I am open for any kind of suggestions.

Am I missing some things from the problem requirements?

I would say that you are:

  Create a class diagram and Java code for the following system and scenario, taking into account the possibility of future extensions.

You don't really have classes (and thus also didn't really take into account future extensions).

I would think that the expectation is something like this:

Create classes Quote, Person (for the attribution, maybe also an Attribution class), a class containing a collection of Quotes, from which you can retrieve items via index, an Output class with methods for print quote and print attribution.

That way, it would be easy to add a GUI for output, to add additional attribution information, add a date for the quote, etc.

Misc

There isn't really much to your code to review, but a couple of points:

you should not have all your code in the main method. The main method should only start your program, not perform any actions itself.
package names should be all lowercase
extract magic numbers to fields (but if you actually change your code as I suggested above, you would not need it at all)