NodeJS broker between MongoDB and RabbitMQ I wrote a small program that aims to take some data from the MongoDB database and put them in the RabbitMQ queue.

I tried to use only promise style but I am a beginner in JavaScript. Could you please help me to improve my first draft?

var mongo = require('mongod');
var amqp = require('amqplib');
var _ = require('underscore');

var TaskBroker = function () {
  this.queueName = 'task_queue';
  this.rabbit = {};
  this.mongo = {};
};

TaskBroker.prototype.connectRabbit = function() {
  return amqp.connect('amqp://localhost')

    .then(function (connection) {
      this.rabbit.connection = connection;
      return connection.createChannel()
    }.bind(this))

    .then(function(channel) {
      this.rabbit.channel = channel;
      return channel.assertQueue(this.queueName, {durable: true});
    }.bind(this))
};

TaskBroker.prototype.connectMongo = function(){
  return function() {
    this.mongo.db = mongo('mongodb://127.0.0.1:27017/test', ['test']);
    return this.mongo.db;
  }.bind(this);
};

TaskBroker.prototype.connect = function () {
  return this.connectRabbit()
    .then(this.connectMongo());
};

TaskBroker.prototype.disconnect = function() {
  this.mongo.db.close();
  this.rabbit.channel.close();
  this.rabbit.connection.close();
};

TaskBroker.prototype.get_url_array = function(_data) {
  return _.chain(_data).pluck('probes').flatten().pluck('url').uniq().value();
};

TaskBroker.prototype.getTask = function() {
  return function () {
    return this.mongo.db.test.find({ 'status': 'ONGOING' }, { 'probes.url':1, '_id':0})
      .then(function(results) {
        var url_array = [];
        if (results != null && results.length > 0) {
          url_array = this.get_url_array(results);
        }
        return this.mongo.db.test.find({ 'probes.url' : { $nin: url_array } });
      }.bind(this))

      .then(function(results) {
        if (results.length > 0) return results[0];
        return null;
      });
  }.bind(this);
};

TaskBroker.prototype.produceTask = function() {
  return function(_message) {
    if(_message != null) {
      _message.status = 'ONGOING';
      this.rabbit.channel.sendToQueue(this.queueName, new Buffer(JSON.stringify(_message)), { deliveryMode: true });
      return this.mongo.db.test.update({_id: _message._id}, { $set: { 'status': _message.status }}).then(function() {
        return _message;
      });
    }
    return null;
  }.bind(this);
};

var taskBroker = new TaskBroker();

taskBroker.connect()
  .then(function() {
    setInterval(
      function () {
        taskBroker.getTask()()
          .then(taskBroker.produceTask())
          .then(function(result) {
            if(result == null) {
              console.log('No job to produce');
            } else {
              console.log('Produce', result);
            }
            //console.log('Disconnected');
            //taskBroker.disconnect();
          }
          , function(error) {
            console.log('ERROR', error.stack);
          }
        );
      }
      , 10000
    );
  });

Interesting question, it was hard to find things I would do different.

To Malachi's point, there are a few strings you could put in a config object, I would definitely add also 10000 to that config object as config.delay and your statuses like 'ONGOING'.
Also, I would write this:

.then(function(results) {
    if (results.length > 0) return results[0];
    return null;
});

As

.then(function(results) {
    return results[0] || null;
});

In the bottom part, you have very stylized code, very functional except for the  2 blocks. I would create 2 named functions called logResults and logError and use those.
In produceTask, you are stretching quite a bit your horizontally, part of that is your atypical use of then on the same line ( different from the rest of your code ). I would counter-propose cutting the code a bit up:

TaskBroker.prototype.produceTask = function() {
  var sendOptions = { deliveryMode: true };
  var statusUpdate = { $set: { 'status': 'ONGOING' }};
  return function(message) {
    if(!message) {
      return;
    }
    message.status = 'ONGOING';
    var content = new Buffer(JSON.stringify(message));
    this.rabbit.channel.sendToQueue(this.queueName, content , sendOptions);
    return this.mongo.db.test.update({_id: message._id}, statusUpdate)
      .then(function() {
        return message;
      });

  }.bind(this);
};

I also declared sendOptions and statusUpdate outside of the returned function, there is no sense in re-creating these all the time.
I also return early if there is no message to reduce arrow pattern code
I renamed _message to message, more on that later

Anonymous functions; you are using a number of anonymous functions. This becomes a problem if you have to analyze stack traces, simply add well named function names, and your code becomes that much easier to support:

TaskBroker.prototype.connectRabbit = function() {
  return amqp.connect('amqp://localhost')

    .then(function onConnect(connection) {
      this.rabbit.connection = connection;
      return connection.createChannel()
    }.bind(this))

    .then(function onChannelCreated(channel) {
      this.rabbit.channel = channel;
      return channel.assertQueue(this.queueName, {durable: true});
    }.bind(this))
};

JsHint.com -> Use it, you have missing semi colons and bad line breaks
Commented out code -> Dont do that in production code
Console.log -> I would wrap this in a function where I can control whether I really want to log and where I can optionally also log into a file for later analysis
I am not sure why you prefix some variables and parameters with underscore, I would advise against it. I know that mongo does this, to distinguish between mongo properties and data properties on an object, which is okay. But I see no good reason in your code for you to prefix variables/parameters with _
Connection to Mongo db; your approach is okay for development, for quality and production I would get the details from the environment:

this.mongo.db = mongo('mongodb://'+ process.env.MY_APP_MONGODB_HOST + '/myapp' , ['myapp']);

You can write

if (results != null && results.length > 0) {
  url_array = this.get_url_array(results);
}

as

if (results instanceof Array) {
  url_array = this.get_url_array(results);
}

I dont like url_array, I tend to take whatever is in the array and an 's' in JavaScript, but urls does not read much better in my mind. All I can say is that you should have some deep thoughts about that variable name.
The usage of null; the usage of null is not idiomatic JavaScript. Consider converting your code to check for undefined instead. Since functions return undefined if you dont return something yourself, you can then avoid statements like return null

All in all, I wish could write code like that when I am a beginner in a new language ;) Sometimes the code feels a bit forced into the promise style, but all in all this is pretty good.


A hash cracker for Python 3.0 and up (module) I've worked on pycrack.py to improve it (hopefully). New features:

Renamed to kronos (kronos.py).
Attack modes:

Bruteforce;
Wordlist attack.

Portability:

Kronos can run on Windows, MacOS and Linux, as well as Android (iPhone?).
Kronos can run under any Python 3 installation, not just Python 3.6 or higher.

The full code is now available on GitHub, along with a guide on how to use it.

I'm looking to get some feedback on the current state of the project. What do you think of the setup of classes and functions within the file? Is there a way to significantly shorten the code, without decreasing functionality? -Any other feedback-

GitHub

GitHub guide

I have included a code sample below:

class Bruteforce:
"""Class containing Active and Passive classes,
for verbose and non-verbose bruteforcing.
Class contents:

* class Active
* class Passive
"""
    class Active:
        """Class for active bruteforce attacks, with
        optional debug mode (boolean). Active mode
        should be utilized from the command line or in
        situations where statistical information is required.
        Class contents:

        * __init__()
        * timer()
        * bruteforce()
        """
        def __init__(self, hash_, algo, charset, min_, max_, debug):
            # Function arguments:

            # hash_:
                    # [1] UTF-8-encoded hash hashlib.<algo>().hexdigest().
                    # [1] Supported algorithms from
                    # [1] hashlib.algorithms_available.

                    # [2] A valid file name or valid file path.
                    # [2] The program will treat each new line
                    # [2] as a new hash. Files must be UTF-8 encoded.
                    # [2] Results will be returned as a list.

                    # [3] A list containing one or more hashes.
                    # [3] Results will be returned as a list.

            # algo: Hashlib algorithm (must be available on system).
            # charset: String, can contain "L" / "U" / "D";
                    #  for lowercase, uppercase and digits.
                    #  Example: lower + upper = LU.
            # min_: Minimum length for expected string (any integer);
                  # bruteforce() will echo a warning if min_ > 6,
                  # because of performance.
            # max_: Maximum length for expected string (any integer).
            # debug: Boolean (1 or True for debug mode, else 0 or False);
                  # Debug mode is not recommended due to performance,
                  # use only if absolutely needed.

            self.hash_ = hash_
            self.algo = algo
            self.algo_ = algo       # This retains a copy of algo argument.
            self.charset = charset
            self.min_ = min_
            self.max_ = max_
            self.debug = debug

            if self.min_ > 5 and self.debug:
                print("""{}Warning: minimum length > 5.
Bruteforcing may take a long time. Consider a wordlist attack.{}"""
                .format(colors['yellow'], colors['none']))

            if path.isfile(self.hash_):
                with open(self.hash_, "r") as infile:
                    hashes = infile.read()
                self.hash_ = hashes.split()

            charset = ""
            charsets = {"L":ascii_lowercase,
                    "U":ascii_uppercase,
                    "D":digits
                   }
            for key in self.charset:
                charset += charsets[key]
            self.charset, charset = charset, None

            self.algo = hashlib.new(self.algo)

This can be shortened:

self.charset = charset
...
charset = ""
charsets = {"L": ascii_lowercase,
            "U": ascii_uppercase,
            "D": digits}
for key in self.charset:
    charset += charsets[key]
self.charset, charset = charset, None

To:

charsets = {"L": ascii_lowercase,
            "U": ascii_uppercase,
            "D": digits}
self.charset = ""
for key in charset:
    self.charset += charsets[key]

The last part can be shortened further by the use of str.join:

self.charset = ''.join(charsets[key] for key in charset)

You might want to wrap this in a try:...except KeyError block for some nice feedback if an unsupported key is supplied, or just leave it as is.

You should also have a look at Python's official style-guide, PEP8. It recommends using a space after the : when defining key: value pairs.


Shopping List application I'm new to java and was just wondering if you could see anything wrong with my code. The program works but I have a feeling it's not the right way to do it.

public class ShoppingItem {

private String ItemName;
    private double ItemPrice;
    private int ItemQty;

public ShoppingItem()
{
        ItemName = "Fruit";
        ItemPrice = 100;
        ItemQty = 1;

}

    public ShoppingItem(String ItemName, double ItemPrice, int ItemQty )
{
        this.ItemName = ItemName;
        this.ItemPrice = ItemPrice;
        this.ItemQty = ItemQty;

}

public String getItemName() {
    return ItemName;
}

public double getItemPrice() {
    return ItemPrice;
}

public double getItemTotalPrice() {
    return ItemPrice * ItemQty;
}

public int getItemQty() {
    return ItemQty;
}

public void setItemName(String ItemName)
{
    this.ItemName = ItemName;
}

    public void setItempPrice(double ItemPrice)
{
    this.ItemPrice = ItemPrice;
}

    public void setItemQty(int ItemQty)
{
    this.ItemQty = ItemQty;
}

    @Override
public String toString()
{
    String state = ItemName + " -  €" + ItemPrice + " x " + ItemQty;
    return state;
}
}

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

public class ShoppingList {

    ArrayList<ShoppingItem> list = new ArrayList<ShoppingItem>();
    //Add a new ShoppingItem to the list
         public void addItem()
    {
            System.out.println();
            System.out.println("enter in the name of your item");
            Scanner keyboard = new Scanner(System.in);
            String ItemName = keyboard.nextLine();

            System.out.println("enter in the price of your item");
            double ItemPrice = keyboard.nextDouble();

            System.out.println("enter in the Qty of your item");
            int ItemQty = keyboard.nextInt();

            ShoppingItem Item = new ShoppingItem(ItemName, ItemPrice,
                        ItemQty);
            list.add(Item);
            System.out.println("Item Added");
    }

    //Display list and total number of items.
         public void displayItem(){
             System.out.println( list.size()+ " items. ");
                for (ShoppingItem x : list) {
                    System.out.println(x.toString());
                }

                 }

 }

import java.util.Scanner;
public class Application {

    public static void main( String [] args) {
        Scanner input = new Scanner(System.in);
        ShoppingList myList = new ShoppingList();
        int userOpt = 0;
        while (userOpt != 3) {
            System.out.println("");
            System.out.println("----- Shopping List------");
            System.out.println("(1) Add an item to the list. ");
            System.out.println("(2) Display list and total number of items. ");
            System.out.println("(3) Exit. ");
            userOpt = input.nextInt();

            if (userOpt == 1) {
            myList.addItem();

            }

            if (userOpt == 2) {
            myList.displayItem();
            }
        }
    }
}

janos already pointed out some important issues. I'm just going to add a few

Separate concerns

A ShoppingList is a shopping list, nothing more. It could be simply a wrapper around a List with maybe some additional convenience functions. It shouldn't be responsible for creating items from user input, much less asking the user for that input. Therefore, most of the code in method addItem() belongs to another class.

Explicitly declare menu options

You are using magic numbers to identify your menu options. Wait, I just said menu option. This is a very important entity in your program, yet it doesn't appear explicitly anywhere, only implicitly in your println()s and ifs. Let's make an enum for it. This will also allow us to get rid of the magic numbers.

enum MenuOption {
    ADD_ITEM("Add an item to the list."),
    DISPLAY_ITEMS("Display list and total number of items."),
    EXIT("Exit.");

    private final String message;

    private MenuOption(String message){
        this.message = message;
    }

    public String getMessage(){
        return message;
    }
}

ShoppingList myList = new ShoppingList();
Scanner scanner = new Scanner(System.in);
MenuOption selectedOption = null;

while(selectedOption != MenuOption.EXIT){

    selectedOption = askUserOption(scanner);

    switch(selectedOption){
        case ADD_ITEM:
            myList.addItem();
            break;
        case DISPLAY_ITEMS:
            myList.displayItem();
            break;
    }
}

private MenuOption askUserOption(Scanner scanner){
    System.out.println("");
    System.out.println("----- Shopping List------");
    for(int i=0; i<MenuOption.values().length; i++){
        MenuOption option = MenuOption.values()[i];
        System.out.println("(" + i + ") " + option.getMessage());
    }

    int numericInput = scanner.nextInt();
    // TODO check for invalid inputs
    return MenuOption.values()[numericInput];
}

Wrap user prompting

Instead of writing System.out.println() at every point where you need to comunicate to your user, it might be a good idea to write a class for this purpose. For example:

class UserPrompter {
    public void prompt(String message){
        System.out.println(message);
    }
}

This has at least two benefits:

It makes the intent of your code more clear. You are not just printing to stdout (maybe for debugging purposes) - you are actually sending a message to the user of your application.
It makes it easier to change the means of communication in the future. At one time you may want to display the messages on a web page instead of printing to stdout.

This last piece of advise, however, will add additional indirection that may not be needed. You may omit it if you feel that you'll be able to refactor your code at any time and just replace the println()s with something else.


Create better Unit test Question: Is there anything you could do in order to improve the test?

I am using Spring Framework 4, Hibernate 4, JUnit 4. All DAO unit tests inherit from TestDaoSetup class:

@ContextConfiguration(locations={
        "classpath:/config/test/spring.xml",
        "classpath:/config/test/hibernate.xml"
})
@TransactionConfiguration
@Transactional
public class TestDaoSetup {
}

One of unit tests:

@RunWith(SpringJUnit4ClassRunner.class)
public class CityDaoImplTest extends TestDaoSetup {
    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Autowired
    private CityDao cityDao;

    @Autowired
    private CountryDao countryDao;

    @Test
    public void create_Created(){
        CountryEntity countryEntity = countryDao.find(1L);

        CityEntity cityEntity = new CityEntity();
        cityEntity.setName("Košice");
        cityEntity.setCountryEntity(countryEntity);

        cityDao.create(cityEntity);

        Assert.assertNotNull("Expected not null value.",cityDao.find(cityEntity.getId()));
    }

    @Test
    public void create_NoCountryAssociation_ExceptionThrown(){
        exception.expect(ConstraintViolationException.class);

        CityEntity cityEntity = new CityEntity();
        cityEntity.setName("Košice");

        cityDao.create(cityEntity);
        cityDao.flush();
    }

    @Test
    public void create_ExistingNameSameCountry_ExceptionThrown() {
        exception.expect(ConstraintViolationException.class);

        CountryEntity countryEntity = countryDao.find(1L);

        CityEntity cityEntity = new CityEntity();
        cityEntity.setName("Bratislava");
        cityEntity.setCountryEntity(countryEntity);

        cityDao.create(cityEntity);
        cityDao.flush();
    }

    @Test
    public void create_ExistingNameDifferentCountry_Created(){
        CountryEntity countryEntity = countryDao.find(2L);

        CityEntity cityEntity = new CityEntity();
        cityEntity.setName("Bratislava");
        cityEntity.setCountryEntity(countryEntity);

        cityDao.create(cityEntity);

        Assert.assertNotNull("Expected not null value.", cityDao.find(cityEntity.getId()));
    }

    @Test
    public void update_ExistingNameSameCountry_ExceptionThrown(){
        exception.expect(ConstraintViolationException.class);

        CityEntity cityEntity = cityDao.find(2L);
        cityEntity.setName("Bratislava");

        cityDao.update(cityEntity);
        cityDao.flush();
    }

    @Test
    public void update_ExistingNameDifferentCountry_Updated(){
        CityEntity cityEntity = cityDao.find(3L);
        cityEntity.setName("Bratislava");

        cityDao.update(cityEntity);

        Assert.assertEquals("Expected different value.", "Bratislava", cityDao.find(3L).getName());
    }

    @Test
    public void delete_NotUsed_Deleted() {
        CityEntity cityEntity = cityDao.find(4L);

        cityDao.delete(cityEntity);

        Assert.assertNull("Expected null value.", cityDao.find(cityEntity.getId()));
    }

    @Test
    public void delete_Used_ExceptionThrown(){
        exception.expect(ConstraintViolationException.class);

        CityEntity cityEntity = cityDao.find(1L);

        cityDao.delete(cityEntity);
        cityDao.flush();
    }
}

Question: Is there anything you could improve in the test?

EDIT:

To make test conditions more clear:

There are separated configurations, one is specifically for testing purposes.
There is database script which prepopulates the test database with test data before tests actually start.
Data are the same for each test, because there is a rollback after each test.
Test data are not prepopulated in each test class, but they are prepopulated in separate SQL file, which is executed before tests actually start.

External data

Most of your test cases are expected that some records already exist. The details of these records are not visible in the class, which makes them an external dependency. It also makes the test cases harder to understand.

A simple fix is to add the necessary test data in the test cases, or in the @Before method.

Make assumptions explicit

Some of the test cases are hard to understand because they make assumptions that are not exactly obvious, for example:

@Test
public void create_ExistingNameDifferentCountry_Created(){
    CountryEntity countryEntity = countryDao.find(2L);

    CityEntity cityEntity = new CityEntity();
    cityEntity.setName("Bratislava");
    cityEntity.setCountryEntity(countryEntity);

    cityDao.create(cityEntity);

    Assert.assertNotNull("Expected not null value.", cityDao.find(cityEntity.getId()));
}

Here, I suppose you are testing that you can create a city with the same name in a different country. This test case seems to make some assumptions:

There is no city named Bratislava in the Country with id=2
There is a city name Bratislava in some other Country

It's better to make these assumptions part of the code, for example:

private CountryEntity createNewCountry() {
    // TODO: create a new unique country (different from all existing)
}

@Test
public void create_ExistingNameDifferentCountry_Created(){
    CountryEntity someCountry = createNewCountry();
    createCity("Bratislava", someCountry);

    CountryEntity anotherCountry = createNewCountry();

    CityEntity cityEntity = new CityEntity();
    cityEntity.setName("Bratislava");
    cityEntity.setCountryEntity(anotherCountry);

    cityDao.create(cityEntity);

    Assert.assertNotNull("Expected not null value.", cityDao.find(cityEntity.getId()));
}

There are no more meaningless numbers (such as 2L) in this test case, and the assumptions are loud and clear.

Another similar example:

@Test
public void update_ExistingNameSameCountry_ExceptionThrown(){
    exception.expect(ConstraintViolationException.class);

    CityEntity cityEntity = cityDao.find(2L);
    cityEntity.setName("Bratislava");

    cityDao.update(cityEntity);
    cityDao.flush();
}

This test case seems to assume that the city with id=2 is named Bratislava. Consider this instead:

@Test
public void update_ExistingNameSameCountry_ExceptionThrown(){
    exception.expect(ConstraintViolationException.class);

    CityEntity cityEntity = cityDao.findSomeCity();
    cityEntity.setName(cityEntity.getName());

    cityDao.update(cityEntity);
    cityDao.flush();
}

No more hidden assumptions and invisible external data. The city can be any city, if you try to create a new city with the same name as the sample city, the method should throw.

Many of your other methods suffer from the same problem. Review them and ask yourself if there are any assumptions that are not written inside the method itself, and make them explicit.

Covering all corners

Some of your test cases could be more strict, for example:

In create_Created, in addition to checking that you can load the new entry that was created, you could check that:

the number of entries in the database got increased by 1
Assert.assertEquals(cityEntity, cityDao.find(cityEntity.getId()))

Similarly in create_ExistingNameDifferentCountry_Created

Expected exceptions

Have you considered this instead of the @Rule for expected exceptions:

@Test(expected=ConstraintViolationException.class)
public void create_NoCountryAssociation_ExceptionThrown(){
    // ...
}

Personally I find this more readable. @Rule is more powerful, because it can match exception messages too, but you're not using that feature anyway. This may be a matter of taste.

Naming

I think your test case names could be more intuitive, for example:

create_city_with_country_works instead of create_Created
create_city_without_country_throws instead of NoCountryAssociation_ExceptionThrown
...

As for camelCase vs underscores vs mixed vs something else, I think it doesn't matter. You can use what you like best. The general naming rules probably don't apply to the test cases the same way as to regular code. Test case names should be specific, identify what is being tested, and as such they tend to be very long.

For example, underscores are very similar to spaces, so create_city_without_country_throws is just a little bit harder to read than a sentence. In  createCityWithoutCountryThrows there is no visual separation between the words, which makes it much harder to read than a sentence. At least this is my opinion.

The bottom line is, use whatever naming is agreed in your team, or else whatever naming is more readable to you.


Convert integers into binary I've made a very simple program that takes integer number arguments either with plus/minus sign or without them, and print the number in binary format.

binary.c

#include <stdio.h>

void printBinary(int);
int toInt(int*, char[]);
int handleProgram(char[]);

int main(int argc, char *argv[])
{
    return handleProgram(argv[1]);
}

int handleProgram(char param[])
{
    int number, state;

    if( toInt( &number, param ) != -1 )
    {
        printBinary(number);

        state = 0;
    }
    else
    {
        printf("\tmain()::Exiting program...\n");

        state = -1;
    }

    return state;
}

void printBinary(int number)
{
    for (int i = 31; i >= 0; i--)
    {
        if (number >> i & 1 == 1)
            putchar('1');
        else
            putchar('0');

        if (i != 0)
        {
            if (i % 4 == 0)
                putchar(' ');

            if (i % 16 == 0)
                printf(": ");
        }
    }

    printf("\n");
}

int toInt(int *num, char param[])
{
    *num = 0;
    int sign = 1;
    int i = 0;

    if(param == NULL)
    {
        printf("\ttoInt()::No parameter, please enter a valid number!\n");

        return -1;
    }

    if(param[i] == '-')
    {
        sign = -1;
        i++;
    }
    else if( param[i] == '+' )
    {
        i++;
    }

    // check that a number exist
    if(param[i] == '\0')
    {
        printf("\ttoInt()::No number detected, please enter a valid number\n");

        return -1;
    }

    for(; param[i] != '\0'; i++)
    {
        if(param[i] >= '0' && param[i] <= '9')
            *num = 10* *num + param[i] - '0';
        else
        {
            printf("\ttoInt()::Invalid parameter, please enter a valid number!\n");

            return -1;
        }
    }

    *num *= sign;

    return 0;
}

Sample output: positive and negative cases

D:\C\chapter2>gcc binary.c -o binary.exe

D:\C\chapter2>binary 3
0000 0000 0000 0000 : 0000 0000 0000 0011

D:\C\chapter2>binary +3
0000 0000 0000 0000 : 0000 0000 0000 0011

D:\C\chapter2>binary -3
1111 1111 1111 1111 : 1111 1111 1111 1101

D:\C\chapter2>binary +3s
        toInt()::Invalid parameter, please enter a valid number!
        main()::Exiting program...

D:\C\chapter2>binary -3s
        toInt()::Invalid parameter, please enter a valid number!
        main()::Exiting program...

D:\C\chapter2>binary s
        toInt()::Invalid parameter, please enter a valid number!
        main()::Exiting program...

D:\C\chapter2>binary +
        toInt()::No number detected, please enter a valid number
        main()::Exiting program...

D:\C\chapter2>binary -
        toInt()::No number detected, please enter a valid number
        main()::Exiting program...

D:\C\chapter2>binary
        toInt()::No parameter, please enter a valid number!
        main()::Exiting program...

Any ideas for a better approach (where to fix, what to do about negative cases, any more functions need)?

Functionality

Why 31?  Why not 15 or 63 or 42?  If code is to handle 32-bit integers, then use long as that type is at least 32-bit, rather than int, which can be as small as 16.  Alternatives int32_t, int_least32_t.  Even better: re-code for the largest integer type intmax_t.

// Why 31?
for (int i = 31; i >= 0; i--)

Right shifting a negative number leads to implementation defined behavior.  Consider unsigned instead.

// ... (int number)
... (unsigned number)
...
if (number >> i & 1 == 1)

Good that code allows a leading '+'.
Pedantic point.  int overflow is undefined behavior and that is the result of the following with argv[1] == "-2147483648", a string that should "work".

*num = 10* *num + param[i] - '0';

Avoid using printf(some_string).  Should some_string contain a %, maybe due to a code update, that will invoke UB as printf() expects the first arg to be a format string.

// printf(": ");
fputs(": ", stdout);
// or (2nd choice)
printf("%s", ": ");

Do not use argv[1] unless it  is valid

int main(int argc, char *argv[]) {
  if (argc > 1) return handleProgram(argv[1]);
  else ...

Prefer terminating error messages to go to stderr

// printf("\ttoInt()::No number detected, ...
fprintf(stderr, "\ttoInt()::No number detected, ...

Overflow not detected in toInt().

Style

Avoid naked magic numbers.  Consider

// for (int i = 31; i >= 0; i--)
#define INT_WIDTH  32
for (int i = INT_WIDTH - 1; i >= 0; i--)

int toInt() returns only 2 different int.  Consider bool.

Minor

See little value in excessive in vertical spacing throughout code.  Example: The need for a blank line between buys little clarity for the price of a line.

printBinary(number);

state = 0;

Consider parens ()

// if (number >> i & 1 == 1)
if ((number >> i) & 1 == 1)
// or simply
if ((number >> i) & 1)


Integrating caliban, ZIO and Akka I created a small sample project using caliban, akka-persistence and ZIO. I'm not really happy with the wiring code:

    implicit val defaultRuntime: DefaultRuntime = new DefaultRuntime {}

    val counter = context.spawn(Counter("counter"), "counter")
    val service: CounterService = defaultRuntime.unsafeRun(CounterService.make(counter, scheduler, timeout))

    val graphQl = GraphQlApi(service)
    val routes = HttpRoutes(context.system, graphQl.interpreter)

    val serverBinding: Future[Http.ServerBinding] = Http()(untypedSystem).bindAndHandle(routes.counterRoutes(ec, defaultRuntime), "localhost", port)

The CounterService is wrapping the ask-calls to the persistent actor in a zio.Task:

class CounterService(counter: ActorRef[Counter.Command], scheduler: Scheduler, timeout: Timeout) {

  implicit val s: Scheduler = scheduler
  implicit val t: Timeout = timeout

  def getCounter: Task[Counter.Count] = {
    ZIO.fromFuture { ec =>
      counter ? GetCount
    }
  }
}

object CounterService {
  def make(countManager: ActorRef[Counter.Command], scheduler: Scheduler, timeout: Timeout): UIO[CounterService] = {
    for {
      manager <- ZIO.succeed(countManager)
    } yield new CounterService(manager, scheduler, timeout)
  }
}

For creating the Routes I need to pass the GraphQLInterpreter, the ExecutionContext and the zio.Runtime:

case class HttpRoutes(system: ActorSystem[Nothing], interpreter: GraphQLInterpreter[zio.ZEnv, _]) {

  def counterRoutes(ec: ExecutionContext, runtime: Runtime[zio.ZEnv]): Route = {
    path("graphql") {
      AkkaHttpAdapter.makeHttpService(interpreter)(ec, runtime)
    }
  }

}

The project compiles and I can execute graphql requests just fine. But I'm not satisfied (nor experienced) with wiring these libraries together. To me it feels like there is space for improvement on how to wire up these libraries but I'm kinda stuck.

Does anyone has some input on this vague question? Any other advice/feedback to my code is much appreciated as well :)

Full project source code can be found here: link to github project

I think you did a pretty good job overall.

You can simplify your code by making CounterService.make not return an effect since you only call ZIO.succeed in it. make can return directly a CounterService and that way no need to call unsafeRun in your main app.

I also think that the HttpRoutes class is not really necessary since it only has a single method counterRoutes that you call once. You could just put this function inside an object and ditch the intermediate class. The values that are already implicit (execution context, runtime) can be passed implicitly as well.

def counterRoutes(interpreter: GraphQLInterpreter[zio.ZEnv, _])(
  implicit ec: ExecutionContext, runtime: Runtime[zio.ZEnv]): Route = {
    path("graphql") {
      AkkaHttpAdapter.makeHttpService(interpreter)
    }
  }

routes.counterRoutes(graphQl.interpreter)


UIGraphicsImageContext Memory Spike - Reducing Footprint I have a UIImage Category for iOS Objective-C which tints an image based on a given UIColor value. You can take a look at the method below:

- (UIImage *)tintImageWithTint:(UIColor *)color withIntensity:(float)alpha {
    CGSize size = self.size;

    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale); // MEMORY SPIKE
    CGContextRef context = UIGraphicsGetCurrentContext();

    [self drawAtPoint:CGPointZero blendMode:kCGBlendModeNormal alpha:1.0]; // MEMORY SPIKE

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextSetBlendMode(context, kCGBlendModeOverlay);
    CGContextSetAlpha(context, alpha);

    CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(CGPointZero.x, CGPointZero.y, self.size.width, self.size.height));

    // Get the resized image from the context and a UIImage
    CGImageRef newImageRef = CGBitmapContextCreateImage(context); // MEMORY SPIKE
    UIImage *tintedImage = [UIImage imageWithCGImage:newImageRef];

    CGImageRelease(newImageRef);
    UIGraphicsEndImageContext();

    return tintedImage;
}

I've been testing this method with Xcode's Instruments app and found that it takes up more than 96.0 % of all bytes used during the life cycle of the app. That's crazy! It allocates more than 5 MB very quickly, which causes a level one memory warning and begins to terminate other running processes.

The image that I'm tinting is only a 111 KB, so I can't see how this code could possibly allocate more than 5 MB so quickly.

How can I improve the performance of this code and reduce its memory impact? I'm not very familiar with CoreGraphics, so any help would be appreciated.

your image might have 111 KB compressed as an jpg or a png. But for image processing it needs to be decompressed. It will be loaded into memory with 8 or 16 bit for each color channel. With RGB it would be up to 48 bit per pixel and 8 bit for the alpha cannel in case of png. So 5MB would represent roughly 1.25 million pixel, or something like 1000*1250 pixel.


FizzBuzz up to 99 in Haskell This code solves the problem of FizzBuzz. Is it possible in any way to improve it?

main = main' 1 where
main' n = do
    (putStrLn . choose) (show n, "Fizz", "Buzz", "FizzBuzz", n)
    if n < 100 then main' (succ n) else putStrLn "End!"
    where
        choose (n0, n3, n5, n15, n)
            | mod n 3 == 0 && mod n 5 == 0 = n15
            | mod n 5 == 0 = n5
            | mod n 3 == 0 = n3
            | True = n0

You could separate your I/O from the pure code:

fizzBuzz :: Int -> String
fizzBuzz n | mod n 3 == 0 && mod n 5 == 0 = "FizzBuzz"
           | mod n 5 == 0                 = "Buzz"
           | mod n 3 == 0                 = "Fizz"
           | otherwise                    = show n

main = mapM print (map fizzBuzz [0..100])


Using await to break long-running processes I have a Node.js app / Web API that runs on an Azure app service with a single CPU.

One of the functions needs to run for a long time, perhaps tens of seconds, while the server should continue to process other requests, i.e. the function should not be blocking.

My idea is to use await new Promise(resolve => setTimeout(resolve, 0)); at the end of each loop cycle to requeue the microtask at the end of the queue, giving other users a chance to receive the response too.

The code is processing data using the node-tfidf package like this:

const Tfidf = require('node-tfidf');
const tfidf = new Tfidf();

for (let document of documents) {
  tfidf.addDocument(document);

  // Break the blocking code:
  await new Promise(resolve => setTimeout(resolve, 0));
}

for (let keyword of keywords) {
  tfidf.tfidfs(keyword, function(i, measure) {
      results.add({keyword, i, measure});
  });

  // Break the blocking code:
  await new Promise(resolve => setTimeout(resolve, 0));
}

I want to get your comments about whether using Promise + setTimeout is a sensible way to break long-running tasks and whether there is a big performance drawback (perhaps break it every 10 loop cycles?).

Room to improve.
There is an overhead associated with interrupting the execution flow with await though it is relatively minor.
As represented in the question there is a little room for improvement.
Problems with your implementation.
Heaping closure
The way you have implemented it can be improved
await new Promise(resolve => setTimeout(resolve, 0));

You create a new function each iteration. This means there is also a new closure created for each iteration that takes heap space, an unneeded overhead, which can be avoided by pre-defining the function (see suggested improvements below).
No zero timeout
V8 (and other browsers) throttle the timeout, it is never 0ms. What it is for V8 on the version of node you are using I don't know as the throttling value has gone through changes, and may well do again.
So if you iterate 100 times and the timeout minimum is 1ms the timeout will add 100ms to the total time to complete the iteration.
The ratio of the iteration time to the timeout time needs to be controlled. If the function takes 1ms and the timeout adds 1ms you double the time to do the function. If however the function takes 100ms to do a single iteration then the timeout adds only 1% to the time to complete.
As you suggest doing the await every so many iterations will improve the ratio. But without knowing the time per iteration you can not be sure of a reasonable count.
A suggested improvement.
The await can be improved using a object to handle the promises based on time rather than iteration count.
Inside the loop you use await as follows
await idler.idle();

Which returns a promise or not depending on the idler settings. If the time since last idle context is greater than idler.interval a promise is returned and execution context is set to idle (allowing events). If the time is less than idler.interval then undefined is returned and execution continues without interrupt.
The following is a general purpose interrupt to allow for pending events to be processed. Ill call it idler for want of a better name.
// idler.interval is min time between idle execution context in ms
// idler.start() sets the timer to now (not really needed for small values
// of idler.interval. Should not be called inside a process
// idler.idle()  Request idle promise. Returns promise if time since last idle
// is greater than idler.interval. Else returns undefined.
export const idler = (() => {
    var lastIdle = 0;
    var interval = 3;  // ms
    function timeout(ready) { setTimeout(ready, 0) }
    return {
        idle() {
            var now = performance.now();
            if (now - lastIdle > interval) {
                lastIdle = now;
                return new Promise(timeout);
            }
        },
        start() { lastIdle = performance.now() },
        set interval(val) { interval = val >= 1 ? val : 1 },
        get interval() { return interval },
    };
})();

The interface provides a way to control how often (time) to idle the execution context to allow for pending events to execute. The idle time can not be directly controlled (you can create 0 latency timeout using the message event but this has some problems)
Using the above is simple and can work over concurrent iterators. See example code below on how it can be used.
This is only a suggestion as your specific circumstance are unknown to me.
Testing concurrency
The following example uses a controllable load workLoad(time) that blocks execution context for a fixed time.
It runs several concurrent iterators that call workLoad a fixed number of times. The iterators run concurrently (time share) and illustrate how idler can manage execution context switching giving you some stats regarding the overhead.
There is also a ticker that provides additional events.
The purpose is to play with the settings to match your expected environment and workloads. You can then find the optimal settings for your needs.

const iterations = 100;  // process iteration count
const load = 10;         // in ms Blocking load per iteration
const processes = 6;     // Number of iteration concurrent processes
const tickTime = 1000;   // ms between tick calls
const idlerInterval = 20;// ms Min interval between idle execution context
const ids = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

/* for stats */
var tickerStart;
var totalTime = 0;
var processCount = 0;
var expectedTime = 0;
var tickCpuTime = 0;

const idler = (()=>{
    var lastIdle = 0;
    var interval = 3;  // ms
    function timeout(ready) { setTimeout(ready,0) }
    const API = {
        idle(){
            var now = performance.now();
            if(now - lastIdle > interval){
                lastIdle = now;
                return new Promise(timeout);
            }
        },
        start() { lastIdle = performance.now() },
        set interval(val) { interval = val >= 1 ? val : 1 },
        get interval() { return interval },
    }
    return API;
})();

// The work function
async function longFunction(cycles = 100, load = 10, id){
    processCount += 1;
    expectedTime += cycles * load;
    const now = performance.now();
    while(cycles--){
        workLoad(load);
        await idler.idle();
    }
    const time = performance.now() - now;
    processCount -= 1;
    results(time, id);
}

function ticker(){
   const now = performance.now();
   if(processCount > 0){
       log("Tick " + (performance.now()-tickStart).toFixed(0) + " ms ");
       setTimeout(ticker, tickTime)
   }
   tickCpuTime += performance.now() - now;
}

log(`Starting ${processes} iterators with ${iterations*load}ms workload each.`);
idler.interval = idlerInterval;
log(`Idler interval ${idlerInterval}ms.`);
idler.start();
var tickStart = performance.now();
for(let i = 0; i < processes; i++){
    longFunction(iterations, load, ids[i]);
}
ticker();

/*========================================================================
  helper functions not related to answer
  ========================================================================*/

function log(data){
   datalog.innerHTML = `<div>${data}</div>`+datalog.innerHTML;
}
function results(time,id){
    log("Id '" + id + "' took : "+(time.toFixed(3))+"ms to complete.");
    if(processCount === 0) {
        var totalTime = (performance.now() - tickStart) - tickCpuTime;
        log("===================================================");
        log("Expected time : " + (expectedTime).toFixed(0) + "ms");
        log("Actual time : " + (totalTime).toFixed(0) + "ms");
        log("Idler total overhead : " + (totalTime - expectedTime).toFixed(3) + "ms")
        const overhead = (totalTime - expectedTime)/(processes * iterations);
        log("Idler per iteration overhead : " + (overhead).toFixed(3) + "ms " + (overhead / load * 100).toFixed(2) + "% of iteration time");
        log("Ticker took : " + tickCpuTime.toFixed(3) +"ms");
        log("===================================================");
    }
}
function workLoad(time = 1){  // blocks for time in ms
    if(!isNaN(time)){
        var till = performance.now() + Number(time);
        while(performance.now() < till);
    }
}
#datalog {
   font-family : consola;
   font-size : 12px;
   color : #0F0;
}
body {
   background : black;
}

Notes:

You should cut and past into a clean environment. Running on this page adds unknown additional executing context's.

The log function is slow (uses markup insertion) and its time has been mostly ignored. The results will therefor be slightly higher than actual.


Hangman game implemented in Python I'd like to know how to improve this code because I think that the main_func is too big and I can not split it into other functions or classes.
Also, I want to know if I can or should use classes to make it cleaner.
import random
import string

def starting():
    print('HANGMAN')
    print('Set game mode:')
    print('0. To exit')
    print('1. Easy')
    print('2. Medium')
    print('3. Hard')
    difficult = int(input('Your choice: '))
    if difficult == 1:
        difficult_easy()
    elif difficult == 2:
        difficult_medium()
    elif difficult == 3:
        difficult_hard()

    else:
        exit('Exiting...')

def main_func(word_lst, guesses_given):

    secret_word = random.choice(word_lst)
    output = []
    guessed_letters = []
    alphabet = string.ascii_letters
    length = len(secret_word)
    print(f'Your word has {len(secret_word)} characters ')

    for i in range(len(secret_word)):
        output.append('_')

    while '_' in output:

        letter = input('Enter a letter: ')

        if letter not in alphabet:
            print('You should enter only one letter!\n ')
        elif len(letter) != 1:
            print('You can only display 1 letter at a time\n')
        else:
            if letter not in guessed_letters:
                guessed_letters.append(letter)

                if letter in secret_word:
                    for n in range(length):
                        if secret_word[n] == letter:
                            output[n] = letter.upper()
                    print(*output, sep=' ')
                    if '_' not in output:
                        print('You won!')

                if letter not in secret_word:
                    guesses_given -= 1
                    print(f"This letter is not in the secret word. REMAINING TRIES: {guesses_given}\n")
                    if guesses_given == 0:
                        print(f"You lost. The secret word was '{secret_word.upper()}'")
                        break

            else:
                print('You have already guessed this letter!\n\n')

    print('GAMEOVER')
    play_again()

def play_again():
    again = input('Play again? (y/n)\n')
    if again.lower() == 'yes' or again.lower() == 'y':
        starting()
    else:
        exit('Exiting...')

def difficult_easy():
    main_func(['hall', 'exam', 'road', 'gate', 'debt', 'poet', 'sir', 'girl', 'food'], 14)

def difficult_medium():
    main_func(['customer', 'baseball', 'language', 'stranger', 'quantity',
               'judgment', 'republic', 'proposal', 'magazine'], 12)

def difficult_hard():
    main_func(['assumption', 'impression', 'restaurant', 'indication', 'excitement',
               'depression', 'government', 'inspection', 'protection', 'investment'], 10)

if __name__ == '__main__':
    starting()

For me, it looks garbage, but I did my best to make it simple and short at the same time. I want to use classes to make it more simple, but I still hadn't figured out... The last thing I want to ask is about the if __name__ == '__main__':, am I using it correctly?
I posted it on Stack Overflow but people said that the site is only for specific problems in your code, so they told me to go here.

Whitespace Following Code Blocks
According to the Python style guide, you should use whitespace sparingly. Try aiming for one single line between functions and code blocks.
Unclear Function Naming
main_func() is not a very clear function name. As a developer reading the code, I am unsure as to what this function contains.
For a solution to this problem, read the next section:
Single-Responsibility Principle
Instead of grouping all of the main game code into main_func(), figure out blocks of code that have a single responsibility, and refactor them into their own function.
For example, the start of main_func() contains code to choose a word. You could refactor this into a choose_word() function that takes the list of words. From this point, you might choose to not pass word_lst into main_func, but instead the chosen word as a result of the choose_word() function.
As another example, further into your main_func() function, you may choose to refactor the "check" code (to see if the player has correctly guessed the word) into a check_guess() function.
Parameter Naming
I am not sure if this is just a typo or a stylistic choice, but you should rename word_lst to word_list. In this example, other developers (and possibly yourself in future) will be able to figure out that lst == list, but some words may not be so obvious. Try not to shorten words when naming variables parameters.


Depth First Search Using Stack in Python I have implemented a depth first search using a stack (in a separate class). Any suggestions please on improvements for the below code:
class Stack:
    """(LIFO) queuing policy implemented using python list."""

    def __init__(self):
        self.list = []

    def push(self, item):
        """Push 'item' onto the stack."""
        self.list.append(item)

    def pop(self):
        """Pop the most recently pushed item from the stack."""
        return self.list.pop()

    def top(self):
        """Return the last element."""
        return self.list[-1]

    def is_empty(self):
        """Returns true if the stack is empty."""
        return len(self.list) == 0

def depth_first_search(graph, start):
    stack = Stack()
    stack.push(start)
    path = []

    while not stack.is_empty():
        vertex = stack.pop()
        if vertex in path:
            continue
        path.append(vertex)
        for neighbor in graph[vertex]:
            stack.push(neighbor)

    return path

def main():
    adjacency_matrix = {
        1: [2, 3],
        2: [4, 5],
        3: [5],
        4: [6],
        5: [6],
        6: [7],
        7: []
    }
    dfs_path = depth_first_search(adjacency_matrix, 1)
    print(dfs_path)

if __name__ == '__main__':
    main()

Lists in Python are already stacks. It would be better if you used a raw list as people are more familiar with lists then a custom Stack class.
When using a plain Python list the while loop can take advantage of lists being truthy if they have items. This allows you to do while stack: instead.
I would prefer this to be a generator function as we likely won't need the entire DFS path. path can then be a set for \$O(1)\$ lookup rather than a list with \$O(n)\$ lookup. ("if vertex in path:")
def depth_first_search(graph, start):
    stack = [start]
    visited = set()
    while stack:
        vertex = stack.pop()
        if vertex in visited:
            continue
        yield vertex
        visited.add(vertex)
        for neighbor in graph[vertex]:
            stack.append(neighbor)


How to optimize/refactor this method? Here is my method:

public JsonResult ValidateAll(string toys)
{
    Dictionary<string, object> res = new Dictionary<string, object>();
    List<string> result_check = new List<string>();

    string[] lines = toys.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

    foreach (string line in lines)
    {
         string toyName = line;

         string toy_tmp = toyName.Trim();
         string toy_tmp2 = HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(toyName)).Replace("&#228;", "&auml;").Trim();
         string toy_tmp3 = toyName.Replace("\u00a0", " ").Trim();
         string toy_tmp4 = HttpUtility.HtmlDecode(toyName.Trim());
         string toy_tmp5 = HttpUtility.HtmlDecode(toyName.Replace("\u00a0", " ").Replace(" ", " ").Trim());

         string tableInDatabase = "";

         //Check if the toy is a doll
         tblDoll doll = (from x in db.tblDoll
                                  where (x.doll_name == toy_tmp || x.doll_name == toy_tmp2 || x.doll_name == toy_tmp3 || x.doll_name == toy_tmp4 || x.doll_name == itoy_tmp5)// || x.doll_name == toy_tmp6)
                            select x)
                            .FirstOrDefault();

         if (doll != null)
         {
             table = "doll";
             result_check.Add("1");
             continue;
         }

         if (table == "")
         {
             var car = (from x in db.tblCar
                       where (x.car_name == toy_tmp || x.car_name == toy_tmp2 || x.car_name == toy_tmp3 || x.car_name == toy_tmp4)
                       select y).FirstOrDefault();
             if (car != null)
             {
                 table = "car";
                 result_check.Add("1");
                 continue;
              }

          }

         //Do the same as for Car and Doll, do it for Plane and Boat too
    }
    res.Add("ok", result_check);
    return Json(res, JsonRequestBehavior.AllowGet);

}

What I'm trying to do is this: the input string is a name of a toy. I have four tables for toys in my db: Car, Doll, Plane, Boat. I need to find in which table is the toy (the input string).

Here's a crack at a bit of code.  It's probably worth mentioning though that I don't think your code could even compile or if it does your missing variables i.e. itoy_tmp5...

Either way, like Robert said I looked for some patterns that seemed to be repeating and started from there.  I extracted the first part to a method and then extracted again etc etc

Here's the code anyway if it helps.

    private string[] GetPossibleNames(string toyName)
    {
        return new []
            {
                toyName,
                HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(toyName)).Replace("&#228;", "&auml;"),
                toyName.Replace("\u00a0", " "),
                HttpUtility.HtmlDecode(toyName),
                HttpUtility.HtmlDecode(toyName.Replace("\u00a0", " "))
            };
    }

    private bool IsToyFor<T>(Table<T> table, string[] possibleToyNames, Func<T,string> getName)
    {
        return table.Any(p => possibleToyNames.Contains(getName(p)));
    }

    private bool HasInterestingToy(string[] possibleToyNames)
    {
        return IsToyFor(db.tblDoll, possibleToyNames, p => p.doll_name) ||
               IsToyFor(db.tblDoll, possibleToyNames, p => p.car_name);
               //Do the same as for Car and Doll, do it for Plane and Boat too
    }

    public JsonResult ValidateAll(string toys)
    {
        Dictionary<string, object> res = new Dictionary<string, object>();
        var resultCheck = new List<string>();

        string[] lines = toys.Split(new [] {"\n"}, StringSplitOptions.RemoveEmptyEntries);

        foreach (string line in lines)
        {
            string[] possibleToyNames = GetPossibleNames(line.Trim());

            if (HasInterestingToy(possibleToyNames)) resultCheck.Add("1");
        }

        res.Add("ok", resultCheck);
        return Json(res, JsonRequestBehavior.AllowGet);
    }


Find Intervals with Most Overlaps Given a list of time intervals, I want to return the intervals with the most overlaps (i.e. most people free). My solution runs in \$O(n \log n)\$, but I made a bunch of "tracker" variables. How can I avoid creating all these variables?

Interval class:

public class Interval {
    int start;
    int finish;

    public Interval(int start, int finish) {
        this.start = start;
        this.finish = finish;
    }
}

Point class (used in my algorithm):

public class Point implements Comparable<Point> {
    int time;
    TimeType type;

    public Point(int time, TimeType type) {
        this.time = time;
        this.type = type;
    }

    public int compareTo(Point p) {
        if (time == p.time) {
            if (!type.equals(p.type)) {
                if (type == TimeType.Finish) {
                    return -1;
                }
                return 1;
            }
            return 0;
        }
        return time - p.time;
    }
}

TimeType enum:

public enum TimeType {
    Start, Finish
}

The method that returns overlapping intervals:

public List<Interval> getOverlappingIntervals(List<Interval> intervals) {
        List<Point> sortedTimes = new ArrayList<Point>();
        Map<Point, Interval> map = new HashMap<Point, Interval>();
        Map<Point, Point> pointMap = new HashMap<Point, Point>();
        List<Interval> res = new ArrayList<Interval>();
        List<Point> currPartial = new LinkedList<Point>();
        List<Point> bestPartial = new LinkedList<Point>();
        int overallBest = 0;
        int currBest = 0;

        for (Interval i : intervals) {
            Point startPoint = new Point(i.start, TimeType.Start);
            Point endPoint = new Point(i.finish, TimeType.Finish);
            sortedTimes.add(startPoint);
            sortedTimes.add(endPoint);
            map.put(startPoint, i);
            pointMap.put(endPoint, startPoint);
        }

        Collections.sort(sortedTimes);

        for (int i = 0; i < sortedTimes.size(); i++) {
            Point curr = sortedTimes.get(i);
            if (curr.type.equals(TimeType.Start)) {
                currBest++;
                currPartial.add(sortedTimes.get(i));
            } else {
                currBest--;
                if (currBest == 0) {
                    currPartial.clear();
                } else {
                    currPartial.remove(pointMap.get(sortedTimes.get(i)));
                }
            }
            if (currBest > overallBest) {
                overallBest = currBest;
                bestPartial = new LinkedList<Point>(currPartial);
            }
        }

        for (Point p : bestPartial) {
            res.add(map.get(p));
        }

        return res;
    }

Is it really \$O(n\log n)\$?

Inside your main loop, you have this line:

            currPartial.remove(pointMap.get(sortedTimes.get(i)));

which removes a Point object from a linked list.  This takes \$O(n)\$ time, so your whole algorithm takes \$O(n^2)\$ time.

Not only that, but this line which copies the best list so far is also \$O(n)\$ time:

           bestPartial = new LinkedList<Point>(currPartial);

Possible fixes

You could fix the first problem by using a data structure other than a LinkedList.  For example, you could use a HashSet or LinkedHashSet.

You could fix the second problem by not making a copy of the best solution.  Instead, remember the index i of the best solution.  Then when you want to print the best solution, make another pass through the sorted times doing exactly what the first pass did.  This time, however, you stop at the best index and print the contents of currPartial at that index.


Build a local cache of all streams from Twitch.TV API I am trying to cache the entirety of streams from Twitch.TV public API with the following code. It is successful but takes almost a full minute to execute so I am wondering if it's my code or just the speed of the API delivery. In any case, because it is my first PHP script (and really, I'm new in general), I am certain there are logical missteps and performance crushing flows and I would appreciate some review!

The function buildPages() is mainly what is in question for this post.

The data is always returned as json and I dump it all to disk for local testing. Suggestions on how to implement an accelerator for this collection are welcomed since I've never played with one before. APC or Memcache(d)? I have a lot of reading to do..

Also, I am not certain why the lines

$length = count($page->streams);
$length = count($page['streams']);

had to be written as such. stdClass Object versus ArrayAccess? I don't really understand why I would get errors when trying to use the same accessor in the case of my code. Is $page not always an associative array created from the JSON data?

<?php

$base = 'https://api.twitch.tv/kraken/';

$thatlist = array(
    'games'=> array(
        'url'=>'games/top',
        'params'=> array(
            'limit'=>100,
            'offset'=>0
        )
    ),
    'featured'=>array(
        'url'=>'streams/featured',
        'params'=>array(
            'limit'=>100,
            'offset'=>0
        )
    ),
    'summary'=>array(
        'url'=>'streams/summary',
        'params'=>array(
            'limit'=>100,
            'offset'=>0
        )
    ),
    'teams'=>array(
        'url'=>'teams',
        'params'=>array(
            'limit'=>100,
            'offset'=>0
        )
    )
);

foreach($thatlist as $key => $val) {

    $fullurl = $base . $val['url'];

    foreach($val['params'] as $foo => $bar){

        $fullurl .= '?' . $foo . '=' . $bar;

    }

    $quicklist[$key] = json_decode(file_get_contents($fullurl), true);

}

function buildPages() {

    $streams = array();
    $offset = 0;

    $page = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams?offset=".$offset."&limit=100", true));

    $length = count($page->streams);

    array_push($streams, $page);

    // request always returns 100 items unless at the end of live data
    while($length = 100) {

        $index = count($streams);
        $offset = $index * 100;

        $page = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams?offset=".$offset.'&limit=100'), true);

        $length = count($page['streams']);

        echo "Index: ".$index."
";
        echo "Length: ".$length."
";

        array_push($streams, $page);

    }

    var_dump($streams);
    $sd = fopen('streams-dump.json', 'w');
    fwrite($sd, json_encode($streams));
    fclose($sd);

}

$qld= fopen('quicklist-dump.json', 'w');
fwrite($qld, json_encode($quicklist));
fclose($qld);

buildPages();

?>

At a glance I'd be almost certain that the network requests are your bottleneck here.

If you think of the difference between some code interpreted and run locally vs instantiating a network connection, sending the request, waiting for their servers to run their code and the network latency to respond I think it's safe to say the network time is going to be the bottleneck. Particularly when you consider you're doing hundreds of network connections.

To speed this up I'd say Memcached is your best option. APC is also pretty useful, but not specifically for this. The general idea would be to check if you have cached results and if not generate the data you need and stick it in memcached and return the data. Then, in separate code, take that data and format it as required.

Roughly speaking:

if (Cache->check('key-to-your-data'))
{
    $twitchTvData = Cache->get('key-to-your-data');
}
else
{
    $twitchTvScraper = new TwitchTvScraper();
    $twitchTvData = $twitchTvScraper->scrape();
    Cache->set('key-to-your-data', $twitchTvData);
}

echo PageBuilder->buildFoo($twitchTvData);

In this example I've split out the caching, scraping of content and building of pages into separate classes. Having these all in the one place is a recipe for disaster/embarrassingly silly bugs.

Also, it's worth noting that hitting someone's API repeatedly like this is usually considered bad form and if they're monitoring for such activity you could get blocked. It might be worth looking into a package that can scrape pages with a rate limit. I'm sure there are a few out there. If you don't need the data refreshed often you could just use wget and read the files from a directory locally.

Finally; it's fine to stick some html together when you're learning a new language but in practice it isn't the way to go. Typically you use an off the shelf framework that can build HTML from templates. Something like, Zend, Laravel etc. (http://www.phpframeworks.com/ for more).

Having said all that, if you're just learning to code, don't take this all on at once! Take it piece by piece and save early, save often.


Passing a string, around quotation marks into another string, all in a mutli line string the title might sound confusing but i have a multi line string which is my source code to be compiled. Inside that string i have a messagebox that will display another string, inside that string i want to pass a string. It got very confusing with all the quotation marks but i finally got it working:

        string source = @"
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Threading.Tasks;
        using System.Windows.Forms;

        namespace Compiler
            {
                static class Program
                {
                    static void Main()
                    {
                        MessageBox.Show(""this is my message: "" + """ + txtMessage.Text + @"""" + @");
                    }
                }
            }";

This returns: MessageBox.Show("this is my message: " + "Hello"); providing the value in txtMessage = Hello

So this works but is very messy, also if i pass something like "hi, into txtMessage that will mess it up because of the quotation mark, kinda like a sql injection. Would there be a better way to do this?

No matter how you do it, it'll be always messy. Instead of hardcoding the strings use resource files instead. You can embed *.txt files inside the exe/dll and easily read them without having to escape anything.

See this question on Stack Overflow: How to read embedded resource text file
. You'll find everything you need there.

To insert the message use the {0} placeholder with

string.Format(stringFromResource, txtMessage.Text);


ADT Stack with a doubly circular linked list I have managed to implement an ADTStack with a circular doubly linked list. I would like to know whether there are things I could have done better or, I should improve.

public class QueueCircularDLL<T> implements ADTQueue<T> {
    private ListElement<T> head;
    private ListElement<T> tail;

    public QueueCircularDLL(){
        head=null;
        tail=null;
    }

    public void enq (T element){
        ListElement<T>newElement=new ListElement<T>(element);
        if (empty()){
            head= newElement;
            tail= head;
        }

        tail.setNextElement(newElement);
        newElement.setPrevElement(tail);
        tail=tail.getNextElement();
        tail.setNextElement(head);
        head.setPrevElement(tail);

    }

    public void deq(){
        if (empty()){
            throw new RuntimeException("queue is empty");
        }

        if (head==tail){
            //head=null;
            head=null;
            tail=null;

        }
        else{
        head=head.getNextElement();
        head.setPrevElement(tail);
        tail.setNextElement(head);
        }

    }

    public T front(){
        if(empty()){
            return null;
        }
        return head.getElement();
    }

    public boolean empty(){
        return (head==null);
    }

    private static class ListElement<T>{
        private T element = null;
        private ListElement<T> nextElement = null;
        private ListElement<T> prevElement = null;

        public ListElement(T element) {
            this.element = element;
        }

        public T getElement() {
            return element;
        }

        public ListElement<T> getNextElement() {
            return nextElement;
        }

        public void setNextElement(ListElement<T> element) {
            this.nextElement = element;
        }
        //für zirkuläre doppelt verkettete liste
        public ListElement<T>getPrevElement(){
            return prevElement;
        }
        // für zirkuläre doppelt verkette liste
        public void setPrevElement(ListElement<T> element){
            this.prevElement=element;
        }

    }

    public static void main(String[] args) {
        QueueCircularDLL<Integer> queue = new QueueCircularDLL<Integer>();

        for (int i = 0; i < 10; ++i) {
            queue.enq(i);
        }

        while (!queue.empty()) {
            System.out.println(queue.front());
            queue.deq();
        }
    }
}

The class doesn't expose a method that let's users benefit from the circular property.
The enq, deq, front, empty methods could work just fine without the circular property.
As such, it's an unnecessary complexity.
If you want to use a circular linked list,
then expose some methods that need or benefit from the circular property.

The class QueueCircularDLL<T> implements the ADTQueue<T> interface,
but it's not clear which methods belong to the interface.
It's strongly recommended to make that clear using the @Override annotation.

In front, instead of returning null when the list is empty,
a more common practice is to throw java.util.NoSuchElementException,
as done by the various linked list and queue implementations in the JDK.


Async file writer in .Net 3.5 I'm curious what people think about this little bit of logging code.  It seems to work ok.  Is there anything I'm missing?

public static class Logger
{
    private static readonly object Locker = new object();
    private static readonly StreamWriter Writer =
                        new StreamWriter("c:\\temp\\logtester.log", true) ;

    public static void Log(string message)
    {
        Action<string> action = MessageWriter;
        action.BeginInvoke(message, null, null);
    }

    private static void MessageWriter(string message)
    {
        lock(Locker)
        {
            Writer.WriteLine(message);
        }
    }
}

Using Jesse's code, but with QueueUserWorkItem instead of BeginInvoke.

public sealed class Logger : IDisposable
{
    private static readonly object Locker = new object();
    private static readonly StreamWriter Writer = new StreamWriter("c:\\temp\\logtester.log", true);
    private static bool _disposed;

    public static void Log(string message)
    {
        ThreadPool.QueueUserWorkItem(MessageWriter, message);
    }

    private static void MessageWriter(object message)
    {
        if (!(message is string)) return;
        lock (Locker)
        {
            Writer.WriteLine(message);
        }
    }

    ~Logger()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        lock (Locker)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                if (Writer != null)
                    Writer.Dispose();
            }

            _disposed = true;
        }
    }
}

Here's a slightly different version. It implements IDisposable so that the StreamWriter can eventually be closed and disposed properly and also uses a typed delegate for asynchronous invocation and properly calls EndInvoke upon completion.

public sealed class Logger : IDisposable
{
    private delegate void WriteMessage(string message);
    private static readonly Logger Instance = new Logger("c:\\temp\\logtester.log");
    private readonly object Locker = new object();
    private readonly StreamWriter Writer;
    private bool Disposed;

    private Logger(string logFileName)
    {
        Writer = new StreamWriter(logFileName, true);
    }

    ~Logger()
    {
        Dispose(false);
    }

    public static void Log(string message)
    {
        WriteMessage action = Instance.MessageWriter;
        action.BeginInvoke(message, MessageWriteComplete, action);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private static void MessageWriteComplete(IAsyncResult iar)
    {
        ((WriteMessage)iar.AsyncState).EndInvoke(iar);
    }

    private void Dispose(bool disposing)
    {
        lock (Locker)
        {
            if (Disposed)
            {
                return;
            }

            if (disposing)
            {
                if (Writer != null)
                {
                    Writer.Dispose();
                }
            }

            Disposed = true;
        }
    }

    private void MessageWriter(string message)
    {
        lock (Locker)
        {
            if (!Disposed && (Writer != null))
            {
                Writer.WriteLine(message);
            }
        }
    }
}


Simple Sudoku solver in Rust This is my little Sudoku solver in Rust. It iterates through empty cells and checks which numbers are absent from the corresponding row, column, and square. If there is one possible candidate, it fills in the answer and moves on to the next empty cell.

Clearly I should be reading from an input rather than hard-coding the puzzle. What other ways can I improve the readability and make it more idiomatic?

type Cell = (usize, usize);

struct Grid {
    data: [[u8; 9]; 9],
    current: Cell,
}

impl Grid {
    // Search possible candidates for a given cell.
    // If one candidate exists, return it.
    fn check(&mut self, cell: Cell) -> Option<u8> {
        let mut candidates = [true; 9];
        for i in 1..10 {
            candidates[i-1] &= self.check_row(cell, i as u8);
            candidates[i-1] &= self.check_column(cell, i as u8);
            candidates[i-1] &= self.check_square(cell, i as u8);
        }

        if candidates.iter().fold(0, |acc, &x| acc + x as i32) == 1 {
            return Some(candidates.iter()
                                  .position(|&x| x == true)
                                  .unwrap() as u8 + 1);
        }
        None
    }
    fn check_row(&self, cell: Cell, num: u8) -> bool {
        let row = self.data[cell.0];
        for i in row.iter() {
            if *i == num { return false; }
        }
        true
    }
    fn check_column(&self, cell: Cell, num: u8) -> bool {
        for row in self.data.iter() {
            if row[cell.1] == num { return false; }
        }
        true
    }
    fn check_square(&self, cell: Cell, num: u8) -> bool {
        let mut square: (usize, usize) = (cell.0 / 3, cell.1 / 3);

        square.0 *= 3;
        square.1 *= 3;

        for row in (square.0)..(square.0 + 3) {
            for column in (square.1)..(square.1 + 3) {
                if self.data[row][column] == num { return false; }
            }
        }
        true
    }
}

// Iterate through empty cells.
impl Iterator for Grid {
    type Item = Cell;

    fn next(&mut self) -> Option<Self::Item> {
        let starting_point = (self.current.0, self.current.1);
        loop {
            self.current.0 = (self.current.0 + 1)%9;
            if self.current.0 == 0 {
                self.current.1 = (self.current.1 + 1)%9;
            }
            if (self.current.0, self.current.1) == starting_point {
                return None;
            }
            if self.data[self.current.0][self.current.1] == 0 { break }
        }
        Some(self.current)
    }
}

fn main () {
    let mut grid = Grid {
        data: [ [1,6,4,0,0,0,0,0,2],
                [2,0,0,4,0,3,9,1,0],
                [0,0,5,0,8,0,4,0,7],
                [0,9,0,0,0,6,5,0,0],
                [5,0,0,1,0,2,0,0,8],
                [0,0,8,9,0,0,0,3,0],
                [8,0,9,0,4,0,2,0,0],
                [0,7,3,5,0,9,0,0,1],
                [4,0,0,0,0,0,6,7,9] ],
        current: (0, 0),
    };

    loop {
        if let None = grid.next() { break; }
        let empty_cell = grid.current;
        match grid.check(empty_cell) {
            Some(i) => {
                grid.data[empty_cell.0][empty_cell.1] = i;
            },
            None => continue,
        }
    }

    for row in grid.data.iter() {
        println!("{:?}", row);
    }
}

General

Run clippy. It will automatically tell you such things as:

equality checks against true are unnecessary

  --> src/main.rs:20:57
   |
20 |             return Some(candidates.iter().position(|&x| x == true).unwrap() as u8 + 1);
   |                                                         ^^^^^^^^^

it is more idiomatic to loop over references to containers instead of using explicit iteration methods

  --> src/main.rs:26:18
   |
26 |         for i in row.iter() {
   |                  ^^^^^^^^^^ help: to write this more concisely, try: `&row`

redundant pattern matching, consider using is_none()

  --> src/main.rs:97:16
   |
97 |         if let None = grid.next() {
   |         -------^^^^-------------- help: try this: `if grid.next().is_none()`

Cell is a name of a type in the standard library, so I was a bit confused to start with. Not sure of a better name.

main

Use while or while let instead of a loop.
The continue is not useful, it's at the end of the block. Switch to an if let instead.
Why isn't the return value of your iterator used? Why don't you use that instead of getting grid.current?
Why is grid.current even part of the grid in the first place?

Grid

If you want to document a function, use ///, not //.
Don't cast booleans as a number. I'm honestly surprised this even compiles. Instead, count the true values
Memorize all the available Iterator methods. In this case, any and all are valuable.

Grid::check_square

There's no need to specify the type of square.
I don't think it's useful to cram the square data into a tuple. Instead, whip up a little closure to perform the same work.
I like Itertools. Here, I use its cartesian_product.

extern crate itertools;

use itertools::Itertools;

type Cell = (usize, usize);

struct Grid {
    data: [[u8; 9]; 9],
    current: Cell,
}

impl Grid {
    /// Search possible candidates for a given cell.
    /// If one candidate exists, return it.
    fn check(&mut self, cell: Cell) -> Option<u8> {
        let mut candidates = [true; 9];
        for i in 1..10 {
            candidates[i - 1] &= self.check_row(cell, i as u8);
            candidates[i - 1] &= self.check_column(cell, i as u8);
            candidates[i - 1] &= self.check_square(cell, i as u8);
        }

        if candidates.iter().filter(|&&x| x).count() == 1 {
            return Some(candidates.iter().position(|&x| x).unwrap() as u8 + 1);
        }
        None
    }

    fn check_row(&self, cell: Cell, num: u8) -> bool {
        self.data[cell.0].iter().all(|&i| i != num)
    }

    fn check_column(&self, cell: Cell, num: u8) -> bool {
        self.data.iter().all(|row| row[cell.1] != num)
    }

    fn check_square(&self, cell: Cell, num: u8) -> bool {
        let truncated_range_of_3 = |x| {
            let start = (x / 3) * 3;
            start..start + 3
        };

        let rows = truncated_range_of_3(cell.0);
        let cols = truncated_range_of_3(cell.1);

        rows.cartesian_product(cols).all(|(row, col)| self.data[row][col] != num)
    }
}

/// Iterate through empty cells.
impl Iterator for Grid {
    type Item = Cell;

    fn next(&mut self) -> Option<Self::Item> {
        let starting_point = (self.current.0, self.current.1);
        loop {
            self.current.0 = (self.current.0 + 1) % 9;
            if self.current.0 == 0 {
                self.current.1 = (self.current.1 + 1) % 9;
            }
            if (self.current.0, self.current.1) == starting_point {
                return None;
            }
            if self.data[self.current.0][self.current.1] == 0 {
                break;
            }
        }
        Some(self.current)
    }
}

fn main() {
    let mut grid = Grid {
        data: [
            [1, 6, 4, 0, 0, 0, 0, 0, 2],
            [2, 0, 0, 4, 0, 3, 9, 1, 0],
            [0, 0, 5, 0, 8, 0, 4, 0, 7],
            [0, 9, 0, 0, 0, 6, 5, 0, 0],
            [5, 0, 0, 1, 0, 2, 0, 0, 8],
            [0, 0, 8, 9, 0, 0, 0, 3, 0],
            [8, 0, 9, 0, 4, 0, 2, 0, 0],
            [0, 7, 3, 5, 0, 9, 0, 0, 1],
            [4, 0, 0, 0, 0, 0, 6, 7, 9],
        ],
        current: (0, 0),
    };

    while let Some(_) = grid.next() {
        let empty_cell = grid.current;

        if let Some(i) = grid.check(empty_cell) {
            grid.data[empty_cell.0][empty_cell.1] = i;
        }
    }

    for row in &grid.data {
        println!("{:?}", row);
    }
}

That unwrap bothers me, but I'm not sure that this is really clearer:

let mut x = candidates.iter().enumerate().filter_map(|(pos, &check)| {
    if check { Some(pos as u8 + 1) } else { None }
}).fuse();

match (x.next(), x.next()) {
    (Some(pos), None) => Some(pos),
    _ => None,
}

It can be made much nicer by abandoning the array at all. This saves (a tiny bit of) stack space but also probably speeds up the program (by a tiny amount) — the function exits as soon as a second possibility is found:

fn check(&mut self, cell: Cell) -> Option<u8> {
    let mut possibilities = (1..10)
        .filter(|&i| self.check_row(cell, i))
        .filter(|&i| self.check_column(cell, i))
        .filter(|&i| self.check_square(cell, i))
        .fuse();

    match (possibilities.next(), possibilities.next()) {
        (Some(pos), None) => Some(pos),
        _ => None,
    }
}

Good news! My version of the code passes every single test case you provided!


MVC - Control Module - Version 2 All models are in the model namespace and follow a naming convention.  This makes it easy to consolidate control into cType() as shown below.

All control passes through cTYpe() which calls the correct model.  It does this by way of the type parameter which is set by the call back function for the specified event.

Calls to Model

model[type].pre()

model[type].post()

Controller and Model

var model = {};
model.user_try =
{
    pre : function()
    {
    },
    post : function( text )
    {
    }
};
function cType( type, param )
{
    var m_response = model[type].pre();
    if( m_response )
    {
         cServer( param, function( text, type ){ model[type].post( text ); }, type );
         return true;
    }
    else
    {
         return m_response;
    }
}

PostScript

Because this is a small prototype/app I have preferences or things I will consider when I will have a working prototype, they are - testing, try/catch/throw handling of errors, advanced abstractions / design patterns, defensive coding against programmer error / malicious users.  Will add these later if the project matures.

Disclaimer: I'm here at behest of the OP. I'm not all that proficient at JS, just enough to do some basic things, but I am fairly well versed in PHP. That being said, the knowledge should be fairly universal and I said I'd lend my point of view on the subject. Please feel free to point out my mistakes. I'd love to know more myself.

Edit: You can't have structure without syntax, so I ignored that bit. But I did edit my answer per your request for no comments on your naming scheme. I do still think its relevant so I left it, however I hid it so you may skip over it if you wish.

Descriptive Code (Naming Scheme)

  I'll be honest, I'm not sure what exactly is going on here. Mostly because your function names are not very descriptive. More descriptive function names would be nice, or at the very least, more documentation. Especially documentation about where some of these other functions are coming from. Because JS is so loose with its scope control these could be coming from anywhere and it would be nice to know where they SHOULD be coming from and what they SHOULD be doing/returning.

Nesting Functions

There are a couple of problems with nesting functions. The first is that those "inner" functions are only available within the scope of the "outer" function and are recreated every time that outter function is called. Second is that it is generally considered bad practice. Not all nested functions, just most. But that is because most are not created properly. I've already said I'm not an expert on this, that's why I gave you the link so you can make your own opinions. I will mention that I don't think what you have here is a good example of nested functions. Mostly because I can't figure out how cIO() is supposed to work if it never calls in().

Switch Statements

You are defining your switch statements wrong. The colon ":" should come after the case argument, not before.

case 'user_try':

This is one of those rare instances where I would say you should look at case dropping. Not sure if that's the right term, but it sounds cool. What I mean by that is instead of retyping the same statements for similar cases, you can write it once, and prepend all the cases that use it above that statement, excluding any breaks so that they "drop" down to the next.

case 'user_new':
case 'user_exist':
//etc...
case 'tweet_add':
    out( cPreHold( 'model=' + type, cPost( type, text ) ) );
    break;

Magic Numbers

You have some magic numbers going on here. Not really sure how you should fix them, but I think there has to be some way. If someone could recommend an example as an edit, I will accept it.

array_pair[0].appendChild( array_pair[1] )

Miscellaneous

I'm confused as to what cPreHold() is supposed to be doing. You have it set up a response variable, check if it has a "true" value, which if it does, you do nothing with it, but then if it doesn't it returns the response variable, which is false... Why not just return false? Why use response variable at all?

if( mPre( type ) ) {}

I do not think that switch statements are necessary in cPre() and cPost() unless you are planning on extending their functionality. It would be better written as an if/else statement.

UPDATE

I can't really say much about your structure. As I mentioned, I only use JS for very basic applications. More or less, your structure looks the same as how I'd write mine, except for all those lamda functions and nested functions. I can catch some syntax errors, and provide some logic suggestions, but I'm not the best one to turn to for advanced topics such as structure.

BTW: Here's a function I find I use a lot. Seems like you could use it too.

function eID( id ) { return document.getElementById( id ); }

Hope this helps!


Freeing allocated memory: am I missing something? If this question should be on stackoverflow instead, please point it out. I'll put it up there.

 struct {
      FILE * fd;
      hdr_t file_header;
      body_t file_body;
 } fileinfo;

The above is an approximate recreation of a structure that I have in my code. There is a separate function we use for thread cleanup. A pointer to the above structure is a parameter to this function.

 void cleanup(void * args)
 {
      struct fileinfo *file_ptr = (struct fileinfo *) args;

      if(file_ptr->fd > 0)
      {
           fclose(file_ptr->fd);
      }
      free(file_ptr);
  }

Does the free() - as called above - actually free all the memory allocated to file_ptr? Should there not be a free for the hdr_t and body_t as well?

The basic logic is that you only free dynamically allocated resources. Those that were created with malloc.

Hdr_t and body_t are automatically allocated and must therefore not be freed.

The most important point is that you might under no circumstances free a pointer without checking if it is not pointing to 0.

This following fragment will core:

void * ptr = 0;
free (ptr);

Therefore always do something like this:

if (ptr != 0)
    free(ptr)


Getting input from user about 2×2×2 Rubik's Cube state I was wondering if there was a way I could shorten this code that gets input from the user about the state of their 2×2×2 Rubik's Cube to solve it. I want it to still be informative so any user knows what to do, the thing is the method is pretty long.

static public int[][] scanCube(){

    int counter0 = 0;
    Scanner in = new Scanner(System.in);

    int[][] input = new int [6][4];

    System.out.println("Welcome to the 2x2x2 cube solver :)\n \n"
            + "Please enter your cube");
    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the TOP side\n");

    while(counter0 < 4){
        input[0][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the LEFT side");

    //reset the counter
    counter0 = 0;
    while(counter0 < 4){
        input[1][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the FRONT side");
    //reset the counter
    counter0 = 0;
    while(counter0 < 4){
        input[2][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the RIGHT side");
    //reset the counter
    counter0 = 0;
    while(counter0 < 4){
        input[3][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the BACK SIDE");
    //reset the counter
    counter0 = 0;
    while(counter0 < 4){
        input[4][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    System.out.println("NOTE: Rotate cube back to starting position before rotating the cube\n"
            + "for the bottom side input\n");

    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the BOTTOM side");
    //reset the counter
    counter0 = 0;
    while(counter0 < 4){
        input[5][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    return input;
}

You can store the sides on an array and loop over that, something roughly like this:

import java.util.Scanner;

public class scanCube {

    public static void main(String[] args) {
        String[] sides = { "TOP", "LEFT", "FRONT", "RIGHT", "BACK", "BOTTOM" };
        int side_index = 0;
        Scanner in = new Scanner(System.in);

        int[][] input = new int [6][4];
        System.out.println("Welcome to the 2x2x2 cube solver :)\n \n"
                + "Please enter your cube");

        for (String side: sides) {
            System.out.println("Enter the colors for the " + side + " side");
            System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
            int counter = 0;
            while(counter < 4){
                input[side_index][counter] = Integer.parseInt(in.nextLine());
                counter++;
            }
            side_index++;
        }
    }
}

I would personally add a String.split so that the user can input the numbers for a single side on a single line, without having to hit enter every time.

If you want to have an alternative approach, with this the user can enter something like 0312 and it will be split and assigned to the array.

Keep in mind that this is just the general idea, not complete / nice code.

import java.util.Scanner;

public class scanCube {
    public static void main(String[] args) {
        String[] sides = { "TOP", "LEFT", "FRONT", "RIGHT", "BACK", "BOTTOM" };
        int side_index = 0;
        int max_colors_per_side = 4;
        Scanner in = new Scanner(System.in);

        int[][] input = new int [sides.length][max_colors_per_side];
        System.out.println("Welcome to the 2x2x2 cube solver :)\n \n"
                + "Please enter your cube");

        while (side_index < sides.length) {
            System.out.println("Enter the colors for the " + sides[side_index] + " side");
            System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
            String[] side_colors = in.nextLine().toString().split("");

            if (side_colors.length != max_colors_per_side+1) { // Account for CR/LF
                System.out.println("Invalid input!");
            } else {
                for (int i = 1; i <= max_colors_per_side; i++) {
                    // You should check here also that the input is valid (0..3)
                    input[side_index][i-1] = Integer.parseInt(side_colors[i]);
                }
                side_index++;
            }
        }
    }
}

You should also check that the user didn't input something presumably wrong like a cube with 10 white squares, because the amount of squares should be the same for every color.


Trying to map JSON to different classes in web API I have a controller action that takes JSON bodies. I know, that the JSON is either of type A or B, where both classes are of interface IModel.

    [HttpPost]
    [Route("api/post/")]
    public IHttpActionResult MyPost([ModelBinder(typeof(MyModelBinder))]IModel viewModel)
    {
        doSomething(viewModel);
        return Ok("ok");
    }

In order to map the JSON, I created my own model binder, like this one

public class MyModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var content = actionContext.Request.Content;
        string json = content.ReadAsStringAsync().Result;

        try
        {
            var DTO = JsonConvert.DeserializeObject<A>(json);
            IModel viewModel = new A()
            {
                // mapping here
            };
            bindingContext.Model = viewModel;
            return true;
        }
        catch(Exception e)
        {

        }
        try
        {
            var DTO = JsonConvert.DeserializeObject<B>(json);
            IModel viewModel = new B()
            {
                // mapping here
            };
            bindingContext.Model = viewModel;
            return true;
        }
        catch (Exception e)
        {

        }
        return false;
    }
}

Edit: It doesn't work, because Newtonsoft Json can apparently always deserialize, so it never jumps out of the first try block. I was wondering, how to improve the code. Right now I have only 2 possible types (A and B), but in the near future I expect to get much more possible types...

The first thing to do is to remove duplicated code. If you do not need further processing DeserializeObject<T>() returns T and you do not need any mapping, you simply can return its result. That code is also shared between A and B then you can simply introduce a separate function:

private static bool TryDeserializeObject<T>(string json, out T result)
    where T : IModel
{
    result = default(T);

    try
    {
        result = JsonConvert.DeserializeObject<T>(json);
        return true;
    }
    catch (JsonReaderException)
    {
        return false;
    }
}

Note that I'm not catching Exception but a more specific one. OutOfMemoryException (for example) it's not intended to signal that I'm trying to deserialize the wrong type. This code is, however, sub-optimal because calling point is like this:

if (TryDeserializeObject<A>(json, out var a))
    bindingContext.Model = a;
else if (TryDeserializeObject<B>(json, out var b))
    bindingContext.Model = b;
else
    return false;

return true;

It does not scale well if I have more than few types. For that I'd love to write this:

private static bool TryDeserializeObject(string json, Type type, out IModel result)
{
    result = null;

    try
    {
        result = (IModel)JsonConvert.DeserializeObject(json, type);
        return true;
    }
    catch (JsonReaderException)
    {
        return false;
    }
}

We can now introduce another function:

private static IModel DeserializeObjectOrNull(string json, params Type[] types)
{
    foreach (var type in types)
    {
        if (TryDeserializeObject(json, type, out var model))
            return model;
    }

    return null;
}

Now calling point might be (it may be more terse but I try to keep it clear):

var model = DeserializeObjectOrNull(json, typeof(A), typeof(B));
if (model == null)
    return false;

bindingContext.Model = model;

return true;

List may be specified here or come from configuration or an hard-coded list somewhere else. This will scale much better.

We have another issue to solve: how to detect we're trying to deserialize the wrong type? Newtonsoft JSON by default simply ignores unknown members then we'll always get an object with only the known property correctly initialised. You need to use an overload which accepts JsonSerializerSettings where you specified MissingMemberHandling.Error for JSonSerializerSettings.MissingMemberHandling property.

Is there a better way? If you can change your JSON then you may add a _type property (for example, also consider the @A and @B variants). If not then you may consider to deserialize to dynamic and to check for well-known properties (using OOM mapper to copy properties). I'd do this only if performance hit is significant enough because it'll make your code much more convoluted.

Solved our problem with JSON we may take a look to the first lines...getting the result of an async method with .Result is seldom what you want. Just refer to MSDN for details and differences but probably what you want is .GetAwaiter().GetResult(). Even better you should make your method async and take advantage of it (there are alternatives ModelBinder implementation which supports async):

public async Task<bool> BindModel(HttpActionContext actionContext,
    ModelBindingContext bindingContext)
{
    var content = actionContext.Request.Content;
    string json = await content.ReadAsStringAsync();

    // ...
}


Improving function that compares two strings I'm learning C and have made this very simple function to compare two strings. I would like to know how it can be improved:

int match(char* string1, char* string2)
{
    size_t i = 0;

    while (string1[i] != '\0' || string2[i] != '\0') {
        if (string1[i] != string2[i]) {
            return 0;
        }
        ++i;
    }

    return 1;
}

I figured it will only do 2 comparisons per iteration, and 3 in the last iteration. Also, I believe it won't go beyond the end of any array because it will return before iterating beyond the null terminator.

Your parameters should be const and your loop need only to check one string for the terminator.  For example in the following loop, if *s1 is 0 the loop stops because of the first condition. If *s1 is not 0 but *s2 is 0,  the loop stops because of the 2nd condition.

int match(const char *s1, const char *s2)
{
    while (*s1 && (*s1++ == *s2++)) {
         // nothing
    }
    return *s1 - *s2;
}