First attempt at making a user class I've just begun creating my first user class. First, I need some clarifications.

Am I using try and catch correctly?

To clarify, the way I would be instantiating this object is like so:

try{
    $loggedInUser = new LoggedIn/User($email,$password,$useragent);
    $_SESSION['user'] = $loggedInUser;//now session holds user object
    die(json_encode('type'=>'success'=>'message'=>'account_fetch_view'));
}
catch(Exception $e) {
    unset($_SESSION['user']);
    die(json_encode(['type'=>'error','message'=>$e]));
}

Looking at my class, will I be able to do this as I've anticipated? If not, should I just construct it as I used to do (i.e. manually from the login processing script)?

namespace LoggedIn;
class User {
    public $email      = NULL;
    public $hash       = NULL;
    public $user_id    = NULL;
    public $user_agent = NULL;
    public $sign_in    = NULL;
    public $csrf_token = NULL;
    public $btc_addr   = NULL;
    public $throttle   = NULL;
    public $last_ajax  = NULL;
    public $verified   = NULL;
    public $reputation = NULL;

    function __construct($e_mail,$p_word,$u_agent)
    {
        if($this->check_pass($p_word) === true && $this->check_email($e_mail) === true)
        {
            $result = $this->fetch_details($e_mail,$p_word);
            if($result !== false && is_array($result) === true)
            {
                $this->email      = $result['u_email'];
                $this->hash       = $result['u_pass'];
                $this->user_id    = $result['u_id'];
                $this->user_agent = $u_agent;
                $this->sign_in    = time();
                $this->csrf_token = $this->csrf_create($this->sign_in,$this->hash);
                $this->btc_addr   = $result['u_addr'];
                $this->throttle   = 0;
                $this->last_ajax  = ($this->sign_in - 5);
                $this->verified   = $result['u_verified'];
                $this->reputation = $this->fetch_rep($this->user_id);
            }else{
                throw new Exception('Invalid Username or Password');
            }
        }
    }

    private function csrf_create($timestamp,$hash)
    {
            return hash('sha256', str_shuffle(openssl_random_pseudo_bytes(4) . $hash . $timestamp));
    }
    private function fetch_details($e_mail,$p_word)
    {

    }
    private function check_email($e_mail)
    {

    }
    private function check_pass($p_word)
    {

    }

    public function log_out()
    {

    }

    public function bid($amount,$auction)
    {

    }

    public function buy_now($amount,$auction)
    {

    }

    private function fetch_rep($u_id)
    {

    }
}

Here on Code Review, it's common to not receive some sort of feedback for a few hours. We all try our best to be on and answering!

I'm having a hard time deciding what you mean in your question. It's hard to understand... As of now, your class seems to be indescribably complex for such little functionality. You constructor is doing way to much work. It should really only be setting up the class that's being called! Login and authentication should either happen in separate methods, or even separate classes.

Have you not tested your class to see if $this works as it should? To the best of my knowledge, it shouldn't. And it seems unnecessary since you already made your variables public. Which they shouldn't be.

I'd also avoid throwing an exception from the constructor. It's uncommon and wouldn't really be expected.

This code because it seems jumbled and crammed. If the User class had less functionality (currently it's handling authentication, authorization, log outs, application functionality, and more) then it'd be easier for you to piece together the code. Let the code breathe, having different classes isn't a bad thing!

On a good note, the aesthetics of the code are very nice. Only a couple notes on the formatting:

Consistency is key. I noticed you have $useragent, $user_agent, and $u_agent. Which is it? Choose one and stick to it!
You've used die... Please don't use die. Handle the errors in a fashionable sense and give some proper error reporting to the user.
LoggedIn is not such a good namespace. More namespace info here.
Typically, class variables aren't all public. Using encapsulation is a good way to keep uniformity and conciseness.
Variables should give the reader some details about what the variable is meant for. What data type is $sign_in? What exactly is $btc_addr? $last_ajax of what, last Ajax call? $result is very ambiguous.
You could switch your conditionals around so you can simplify to the following code:

Notice I take out the false check, if it's an array, it won't be false.

$result = $this->fetch_details($e_mail,$p_word);
if (!is_array($result)) {
    throw new Exception('Invalid Username or Password');
}
$this->email      = $result['u_email'];
$this->hash       = $result['u_pass'];
$this->user_id    = $result['u_id'];
$this->user_agent = $u_agent;
$this->sign_in    = time();
$this->csrf_token = $this->csrf_create($this->sign_in,$this->hash);
$this->btc_addr   = $result['u_addr'];
$this->throttle   = 0;
$this->last_ajax  = ($this->sign_in - 5);
$this->verified   = $result['u_verified'];
$this->reputation = $this->fetch_rep($this->user_id);

Updates

When I say it has too much responsibility, I'm saying that the class is doing to many things unrelated to each other. Setting a bid is completely different than logging out. I'm saying that these things should be separated. The S in SOLID stands for Single responsibility (highly recommended read). You want your code to adhere to these principles. A class of User shouldn't be handling CSRF creation, and authentication, and data retrieval, and application business (i.e. bidding).
OWASP has graciously given some sample PHP CSRF information. They're using mt_rand, however, I'd have to agree with you that openssl_random_pseudo_bytes is a better choice. I can't see the benefit in infusing the timestamp and password into the string, but I also cannot see the downfalls.


Dependency injecting or manually instantiating structs in others with go I am coming from PHP OOP background so just want to find out if what I do with Go is common/acceptable practise or not (I am newbie in Go). It is to do with Dependency Injection.

In OOP it is ideal to Dependency Inject object X into object Y rather than directly instantiating object X in object Y. I won't list the reasons because I believe most of you know general OOP practises etc. Given that Go is not an OOP language and I've seen both versions being used, which version below wins over another an why?

api/internal/config/config.go

package config

type Config struct
{
   Locale string
}

func NewConfig() Config {
   return Config{"en"}
}

VER 1

api/internal/app/app.go

package app

func Start(c config.Config) {
   fmt.Println(c.Locale)
}

cmd/main.go

package main

import (
    "api/internal/app"
    "api/internal/config"
)

func main() {
    c := config.NewConfig()

    app.Start(c)
}

VER 2

api/internal/app/app.go

package app

import (
   "fmt"
   "api/internal/config"
)

func Start() {
   c := config.NewConfig()

   fmt.Println(c.Locale)
}

cmd/main.go

package main

import "api/internal/app"

func main() {
    app.Start()
}

Version 1 wins hands down.

Because, as you say yourself, go isn't an OO language, you kind of have to treat your entry point (e.g. main func) as your injection point. The main function loads up the global config (usually from flags and/or environment variables), and then passes them on the the various components you'll use (or packages if you like).

Go is a great language to write tests in quickly. If I see code like the second snippet:

func Start() {
    c := config.New()
    // do stuff with c
}

I will rewrite it. The config value is created in that function, so it's safe to assume that this function will need to check the config values. How am I going to reliably unit-test the package, if I can't pass in all possible combinations of config?

Sure, I could write a ton of code setting/unsetting environment variables, and call this Start function over and over again, but am I really unit-testing the code then? Surely, if the config package is broken, then all other tests become unreliable to say the least. What about a change to the config package? How awful it'd be to rewrite all the tests just to make sure the changes to the config are reflected there, too? It's going to be a PITA, and an enormous waste of time and resources.

PS: code like config.NewConfig() will also get rewritten by a lot of gophers. This is referred to as stuttering code (read this).

I now I'm getting config, because I'm using the config package. The function name New is enough information, surely. config.NewConfig reads like "from config, get me new config" as opposed to "hey, config, give me a new value".
This might be personal preference, but I generally find it better to use the function Get for config, rather than New. Config is, IMO, an immutable set of data, not something that does something, not something that needs constructing, it needs to be fetched/loaded. For that reason, I'd write config.Get() and that func would looks something like this:

package config

// Conf - global config struct
type Conf struct {
    App // config per package
}

// App - config specific to the App package
type App struct {
    Locale string
}

func Get() (*Conf, error) {
    // get values, return...
}


Grade calculator for a project with four aspects I have a program that will ask the user to input their grades for 4 different sections of a project, then tell them what their total mark is, what grade they got and how many marks away they were from the next grade. I managed to make a single loop for all inputs rather than having a loop for each individual one, but there are still quite a lot of if statements to determine what grade they got and how far away they were from the next one, and I can't figure out how to optimise it since I'm still very new to Java.

import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;

public class PortfolioGrade {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] words = new String[]{"Analysis", "Design", "Implementation", "Evaluation"};
        int[] marks = new int[words.length];
        for(int counter = 1; counter <= words.length; counter++) {
            System.out.println("Enter your mark for the '" + words[counter - 1] + "' part of the project: ");
            while(true) {
                try {
                    Scanner reader = new Scanner(System.in);
                    marks[counter - 1] = reader.nextInt();
                    if(marks[counter - 1] < 0 || marks[counter - 1] > 25) {
                        System.out.println("Please input a number between 0 and 25.");
                        continue;
                    }
                    break;
                } catch(InputMismatchException e) {
                    System.out.println("Please input a valid integer.");
                }
            }
        }

        int totalmark = Arrays.stream(marks).sum();
        String grade = null;
        String nextgrade = null;
        Integer marksaway = null;

        if(totalmark < 2) {
            grade = "U";
            marksaway = 2 - totalmark;
            nextgrade = "1";
        } else if(totalmark >= 2 && totalmark < 4) {
            grade = "1";
            marksaway = 4 - totalmark;
            nextgrade = "2";
        } else if(totalmark >= 4 && totalmark < 13) {
            grade = "2";
            marksaway = 13 - totalmark;
            nextgrade = "3";
        } else if(totalmark >= 13 && totalmark < 22) {
            grade = "3";
            marksaway = 22 - totalmark;
            nextgrade = "4";
        } else if(totalmark >= 22 && totalmark < 31) {
            grade = "4";
            marksaway = 31 - totalmark;
            nextgrade = "5";
        } else if(totalmark >= 31 && totalmark < 41) {
            grade = "5";
            marksaway = 41 - totalmark;
            nextgrade = "6";
        } else if(totalmark >= 41 && totalmark < 54) {
            grade = "6";
            marksaway = 54 - totalmark;
            nextgrade = "7";
        } else if(totalmark >= 54 && totalmark < 67) {
            grade = "7";
            marksaway = 67 - totalmark;
            nextgrade = "8";
        } else if(totalmark >= 67 && totalmark < 80) {
            grade = "8";
            marksaway = 80 - totalmark;
            nextgrade = "9";
        } else if(totalmark >= 80) {
            grade = "9";
        }

        System.out.println("Your total mark was " + totalmark + ".");
        System.out.println("You got a Grade " + grade + ".");
        if(grade == "9") {
            System.out.println("You achieved the highest grade!");
        } else if(marksaway == 1) {
            System.out.println("You were " + marksaway + " mark away from a Grade " + nextgrade + ".");
        } else {
            System.out.println("You were " + marksaway + " marks away from a Grade " + nextgrade + ".");
        }
    }
}

Because there are no holes you can simply have an array of "breakpoints".

int [] steps = new int[] { 2, 4, 13, 22, 31, 41, 54, 67, 80 };
int i;

for(i=0; i<steps.length && totalmark>=steps[i]; i++);
grade = i==0 ? "U" : ""+i;
if(i<steps.length) marksaway=steps[i]-totalmark;
nextgrade=""+(i+1);


HTML parser written in JavaScript that takes in strings and output a DOM tree object I wrote an HTML parser in JavaScript, where it takes an a string that represents the HTML
const html =
`

foo

bar

`

And it should output an object like this
{
    children: [
      { children: ['foo'], value: 'div' },
      { children: ['bar'], value: 'div' },
    ],
    value: 'div',
  }

here is my attempt
function parser(html) {
  const tokens = html.split('\n')
  const stack = []
  tokens.forEach((token) => {
    if (token === '
') {
      const children = []
      while (stack[stack.length - 1] !== '
') {
        children.unshift(stack.pop())
      }
      stack.pop()
      stack.push({
        children,
        value: 'div',
      })
    } else {
      stack.push(token)
    }
  })
  return stack.pop()
}

const html =
`

foo

bar

`

function parser(html) {
  const tokens = html.split('\n')
  const stack = []
  tokens.forEach((token) => {
    if (token === '
') {
      const children = []
      while (stack[stack.length - 1] !== '
') {
        children.unshift(stack.pop())
      }
      stack.pop()
      stack.push({
        children,
        value: 'div',
      })
    } else {
      stack.push(token)
    }
  })
  return stack.pop()
}

console.log(parser(html))

My questions are:

How can I modify the code so it can become easily expandable for other HTML tag body, div, span etc.
Right now the HTML string it takes has to be valid. How can I modify the code so it can detect invalid HTML
Right now the HTML string it takes doesn't have any indentation. How can I modify the code so it can allow indentations in the input strings?

General review points

Use semicolons
Try to avoid Array iterator functions in favor of for of. Generally use array iterators when you want the iteration to be an expression.

Apart from that the code looks good and is an elegant solution to parsing simple markup. It can be used as a base to provide the additional functionality you mention.
Questions

"Right now the HTML string it takes doesn't have any indentation. How can I modify the code so it can allow indentations in the input strings?"

After you split the markup string you can remove white spaces using String.trim
In the example parser (bottom of answer), the first expression uses Array.map and Array.filter to trim white spaces and then remove empty lines.
If you want to only remove white spaces using the same rules as HTML then you can use a RegExp and  String.replace to remove white spaces.
Token validator

"How can I modify the code so it can become easily expandable for other HTML tag body, div, span etc."

"Right now the HTML string it takes has to be valid. How can I modify the code so it can detect invalid HTML"

For the other questions you will need to create an object that can validate tokens. The validators role is to recognize, valid tags, invalid tags, and content.
It does this

by keeping a Set of tag names
providing a function to check a token. If the token is a valid closing tag it returns the token representing the opening tag.
keeps the state of the token tested. If the token is unknown or a tag the semaphore are set appropriately.

Your function has been modified to use the validator and check for various problems related to invalid markup.
The function will return a simple error object containing the error description if the markup is invalid
If the token validator checks a token that is unknown (not in name list and starts or ends with < or >) unknown is set true.
If the token validator checks a known opening tag the semaphore tag is set true.
The semaphore are reset on each token checked.
The Validator
Add the tags you wish to recognize to the names Set.
Call tokenValidator.token to validate a token.
It will return the opening tag as a token or undefined.
If undefined the check the semaphores  tokenValidator.tag and / or tokenValidator.unknown to determine what to do with the current token.
const tokenValidator = (() => {
    const names = new Set(["div", "span", "p"]);
    var unknown = false, tag = false;
    return {
        get unknown() { return unknown },
        get tag() { return tag },
        token(token) {
            tag = unknown = false;
            const hasEnd = token.endsWith(">");
            if (token.startsWith("<")) {
                if (token.startsWith("</") && hasEnd) {
                    const tokenName = token.slice(2,-1);
                    if (names.has(tokenName)) { return "<" + tokenName + ">" }
                    tag = unknown = true;
                } else if (hasEnd) {
                    const tokenName = token.slice(1,-1);
                    unknown = !names.has(tokenName);
                    tag = true;
                    return;
                }
                unknown = true;
            } else if (hasEnd) { tag = unknown = true }
        },
    };
})();

The Parser
The parses is based on your original code.
It will either return the parsed markup or an error.
Usage example
const result = parser(HTML);
if (result.error) { console.log(result.message) }
else { console.log(result) }

To check for hanging tags (eg missing closing tags) the function counts up on opening tags and down on closing tag. The countOpen must be 0 when done or there is an error.
Example Code
function parser(html) {
    const tokens = html.split('\n').map(token => token.trim()).filter(token => token !== "");
    const error = message => ({error: true, message: "Invalid HTML. " + message});
    const stack = [];
    var countOpen = 0;
    for (const token of tokens) {
        const openToken = tokenValidator.token(token);
        if (tokenValidator.unknown) { return error("Unknown tag: " + token) }
        if (openToken) {
            const children = [];
            let stackToken = stack.pop();
            while (stackToken?.value !== openToken) {
                if (!stackToken) { return error("Tag order: " + token) }
                children.unshift(stackToken);
                stackToken = stack.pop();
            }
            stack.push({value: openToken.slice(1, -1), children});
            countOpen--;
        } else if (tokenValidator.tag) {
            stack.push({value: token});
            countOpen ++;
        } else { stack.push(token) }
    }
    return countOpen ? error("Missing tag") : stack.pop();
}

Note that the code does not cover all invalid markup. It is just an example intended to demonstrate how validation can be addressed.


is this future map scala syntax good? I'm new to scala and have been working to understand the syntax so that I can be more efficient.  How does this look in terms of functional syntax and scala idioms?

In particular, I'd like to know if this is a good way of handling futures.  I'm aware of onComplete, onSuccess, etc..., matching but I had trouble getting a return value back out.  map seemed like the right approach here.

object Application extends Controller with securesocial.core.SecureSocial {

  val inboxSlurper = Akka.system.actorOf(Props[InboxSlurper], name = "inboxSlurper")

  def index = SecuredAction.async {
    implicit request =>
      implicit val timeout = Timeout(10 seconds)
      val user: User = request.user.asInstanceOf[User]

      val f = inboxSlurper.ask(
        OauthIdentity(
          user.email.get,
          user.oAuth2Info.get.accessToken))

      f flatMap { reply =>
        val emailFeed = reply.asInstanceOf[Enumerator[Message]]
        val iter = Iteratee.fold[Message, String]("")((result, msg) => result + msg.getSubject())
        emailFeed |>>> iter
      } map { str =>
        Logger.debug(str);
        val subj = "Subject: %s".format(str)
        Ok(views.html.index(subj))
      }

  }

}

Future "callbacks" can be simplified by using the for comprehension to compose futures. More information can be found here http://docs.scala-lang.org/overviews/core/futures.html#functional_composition_and_forcomprehensions

I'm not a Scala expert, but this is how i would replace the flatMap and map with a for

object Application extends Controller with securesocial.core.SecureSocial {

  val inboxSlurper = Akka.system.actorOf(Props[InboxSlurper], name = "inboxSlurper")

  def index = SecuredAction.async { implicit request =>
    implicit val timeout = Timeout(10 seconds)
    val user = request.user.asInstanceOf[User]

    for {
      emailFeed <- (inboxSlurper ? OauthIdentity(user.email.get, user.oAuth2Info.get.accessToken))).mapTo[Enumerator[Message]]
      str <- emailFeed |>>> Iteratee.fold[Message, String]("")((result, msg) => result + msg.getSubject())
    } yield Ok(views.html.index("Subject: %s".format(str)))
  }

}

The example demonstrates the sequential composition of futures, str will be calculated when emailFeed has retrieved the data for the inboxSlurper actor. After all futures have been completed then a result can be returned with yield.

Because everything is a expression in Scala for {} yield Ok() will be returned as result for the Action, which is a Future[SimpleResult].


Remap value of range input element I have following input range (slider), values allowed are from 0 to 100.
I need to map values from the slider to a input text, with the following rules:

      range => text
          0 => 2000
        100 =>  200

With the value in between accordingly.
Currently I am using the following script, which works, but I would like to know if there is a better way to do it.

var slider = document.querySelector('#slider');
var result = document.querySelector('#result');
slider.addEventListener('change', function(event) {
  var sliderValue = event.target.value;
  var maxValue = 2000;
  var coef = 18;
  var calc;
  calc = maxValue - (sliderValue * coef);
  result.value = calc;
});
<input id="slider" type="range" name="points" min="0" max="100" value=0>
<input id="result" type="text" name="result">

First, I would move out that equation to its own function. It takes an input number (your value), and returns a result (the text). Doing it this way makes easily testable functions a habit.

function getTextFromRangeValue(value){
  return maxValue - (value * coef);
}

With this comes separation of your DOM handler logic. This allows your logic (the calculation code) to be very reusable as it is now detached from the DOM-handling code.

slider.addEventListener('change', function(event) {
  result.value = getTextFromRangeValue(event.target.value);
});

maxValue and coef are constants, fixed values. It's a programming convention to name constants with uppercase characters separated with underscores. Additionally, lift them out the handler scope so they're not recreated on every call. They should be named in full, avoid abbreviations.

var slider = document.querySelector('#slider');
var result = document.querySelector('#result');
var MAX_VALUE = 2000;
var COEFFICIENT = 18;

If I were to rewrite this code, here's how I'd do it.

const slider = document.querySelector('#slider');
const result = document.querySelector('#result');
const MAXIMUM_VALUE = 2000;
const COEFFICIENT = 18;

function getTextFromRangeValue(value){
  return MAXIMUM_VALUE - (value * COEFFICIENT);
}

slider.addEventListener('change', function(event) {
  result.value = getTextFromRangeValue(event.target.value);
});

Lastly, as mentioned in the comments, if this code isn't in a module or in its own scope, consider wrapping in an IIFE to avoid cloberring and being clobbered in the global scope.


In n circle size removing k th person every time until 1 remains In one site there was one practice question which ask you to make one program:

  Tapas and Meghana are appointed as the one responsible for interviews
  of AXIS Core committee '17 ! In order to decide upon the order in
  which to call the aspirants for the interview, they have come up with
  a brilliant game. It goes like: the core game is divided into \$N\$
  phases; and \$N\$ aspirants, successively numbered from \$1\$ to \$N\$, are moving
  round a circle one after another, i.e. the first follows the second,
  the second follows the third, ..., the \$(N-1)\$th follows the \$N\$th, and
  the \$N\$th follows the first. At each phase, a single aspirant is made
  to leave the circle and is taken up for interview. While the others
  continue to move. At some phase, the circle is left by an aspirant,
  who is marching \$K\$ positions before the one, who left the circle at the
  previous phase. An aspirant, whose number is \$K\$, leaves the circle at
  the first phase.

  Input The only line contains the integer numbers \$N\$, and \$K\$.

  Output You should output the order in which in the aspirants give
  their interviews. The numbers should be separated by single spaces.

  Constraints \$1\le N\le 100000\$; \$1\le K\le N\$.

According to my understanding this question is related to queue.

My program:

a,b = raw_input().split()
a = int(a)
b = int(b)
c = []
d = []
for i in range(a, 0, -1):
    c.append(i)
while len(c) != 0:
    for i in range(1, b):
        f = c.pop()
        c.insert(0, f)
    print c.pop(),

This code was working fine but on some input cases it was showing time limit exceed. So I was wondering that if there is any algorithm which can work better than this or is there any problem with my code which I don't know ?

1. Review

If all the code is at the top level of the module, and reads from standard input, it is hard to test it or measure its performance. It's better to organize the code into functions so that they can be easily tested.
The values in the problem have the names \$N\$ and \$K\$ but in the code they have the names a and b. This makes it hard to check the code against the problem. It would be better to be consistent.
The code initializes the list c by repeatedly calling its append method:

c = []
for i in range(a, 0, -1):
    c.append(i)

Instead, just call list:

c = list(range(a, 0, -1))

The variable d is not used and could be omitted.
Instead of testing len(c) != 0, just test c.
The loop index i is not used; it's conventional to name an unused variable _.
Instead of:

f = c.pop()
c.insert(0, f)

you could save a line and write:

c.insert(0, c.pop())

2. Revised code

def josephus(n, k):
    """Yield the order in which people are removed from the circle in the
    Josephus problem starting with n people and removing every k'th
    person.

    """
    c = list(range(n, 0, -1))
    while c:
        for _ in range(1, k):
            c.insert(0, c.pop())
        yield c.pop()

def main():
    n, k = map(int, raw_input().split())
    print(' '.join(josephus()))

3. Performance analysis

The while c: loop executes \$N\$ times, each for loop executes \$K-1\$ times, and inserting an item at the start of a list takes time proportional to the length of the list (see the time complexity page on the Python wiki). So the overall runtime is \$Θ(N^2K)\$.

4. Performance improvement

We can avoid one of the factors of \$N\$ in the runtime by using a collections.deque instead of a list and calling the rotate method:

from collections import deque

def josephus(n, k):
    """Yield the order in which people are removed from the circle in the
    Josephus problem starting with n people and removing every k'th
    person.

    """
    c = deque(range(n, 0, -1))
    while c:
        c.rotate(k - 1)
        yield c.pop()

This brings the runtime down to \$Θ(NK)\$ which might be acceptable, but since you didn't give us the link, I can't check whether that's the case.


How can I make my solution for Chef and Digits run faster? Problem Statement

  Given \$n\$ digits and \$m\$ indices \$x\$ from \$1. \ldots,n\$, calculate the
  difference \$b_y = a_x - a_y\$ for all indices \$y \; (y < x)\$. Then, calculate \$B1\$,
  the sum of all \$b_y\$ which are greater than \$0\$ and \$B2\$,
  the sum of all \$b_y\$ which are less than \$0\$. The answer for this step is \$B1 - B2\$.

  Input

  The first line contains two integers \$n, m\$ denoting the number of
  digits and number of steps. The second line contains \$n\$ digits (without
  spaces) \$a_1, a_2, ..., a_n\$. Each of next \$m\$ lines contains single integer
  \$x\$ denoting the index for current step.
  (ADIGIT: Chef and Digits from CodeChef)

My Issue

I've tried quite hard to optimize the following solution, but online judge always shows Time Limit Exceeded.

My Question

Is it possible to optimize this code further to bring time down less than 1 second, or should I change my approach or perhaps shift to C?

import sys
final=[]
z,y=[int(x) for x in sys.stdin.readline().split()]
stra=sys.stdin.readline()
for i in xrange(y):
    b1=b2=0
    curr=int(input())-1
    for x in stra[:curr]:
        mu=int(stra[curr])-int(x)
        if(mu>0):
            b1+=mu
        else:
            b2+=mu
    final.append(str(b1-b2))
print("\n".join(final))

Issues with your code

You didn't put any effort into choosing good names. Given a code challenge, either stick to the variable names used in the problem statement (n, m, ...) or, preferably, choose explicit and descriptive names such as steps, digits and indices rather than z, y, etc.

Why should you bother with this? Because good names reveal intent, and knowing what the code is supposed to do makes it possible for you and others to understand and improve it easily.

Your algorithm uses a naive, brute-force approach. This is fine as a starting point!
But when you get a time limit exceeded message, you need to think about smarter solutions.

Rene's answer gives you some good advice: He suggests that you employ caching, separate I/O from the calculation, and add up all the absolute values of by, thus skipping the calculation of B1 and B2. This is a good start but you can go much further.
Janne's answer tells you the essence of what's wrong with your algorithm: you need to avoid looping over the previous digits for every step. Why? Because there will be up to 105 (one hundred thousand) digits and up to 105 steps. However, it is unnecessary to make a sorted copy of the indices — see below.

How?

Start by separating your concerns.  Python has functions, so use them to group relevant parts of your code together, while keeping different levels of abstraction separate. Start at the most general level:

def main():
    print(*solve(sys.stdin), sep='\n')

We are saying: print each line of the result of solving the problem with the input from sys.stdin.
Our next concern is to parse the input:

def solve(lines):
    _, digits, *indices = lines
    return calculate_answer(as_ints(digits.rstrip()), as_ints(indices))

We discard the first line _ because we can deduce the length of the digits and the number of steps from the rest of the input, so there is no need to waste cycles parsing them.  We then store the digits which are given in the second line, as well as the indices from the following lines.

To get rid of the redundancies in your integer-conversion code, we extract a function:

def as_ints(iterable):
    return [int(x) for x in iterable]

We can pass the digits (stripping the newline character at the end) and the indices to this function to obtain usable values which we can use to calculate_answer(digits, indices). Since we have already parsed the input, this function can be focused on our algorithm to solve the problem.

def calculate_answer(digits, indices):

Store the indices in a dictionary, which allows them to be looked up in constant time.

result = dict.fromkeys(indices)

Set up another dictionary to count the number of occurrences of each unique digit, which will help us avoid iterating over all previous digits on every step.

counts = defaultdict(int)

Iterate over the digits and keep track of each digit's index, starting with 1

for index, digit in enumerate(digits, start=1):

If the current index is in result and we have not calculated a value for it yet:
Assign to the current index the sum of all the absolute values of the differences between the current digit and each unique previous digit d multiplied by its occurrences n.

    if index in result and result[index] is None:
        result[index] = sum(n * abs(digit - d) for d, n in counts.items())

Increment the number of occurrences of the digit we just encountered:

    counts[digit] += 1

In the order of the given indices, retrieve each calculated value from  result.

return (result[i] for i in indices)

Result

The end result is fast enough to be accepted by CodeChef. As you didn't specify a language version, this is in Python 3, which you should use as well. If you insist on sticking with Python 2.x, you will need to make the necessary adjustments.

import sys
from collections import defaultdict

def main():
    print(*solve(sys.stdin), sep='\n')

def solve(lines):
    _, digits, *indices = lines
    return calculate_answer(as_ints(digits.rstrip()), as_ints(indices))

def calculate_answer(digits, indices):
    result = dict.fromkeys(indices)
    counts = defaultdict(int)
    for index, digit in enumerate(digits, start=1):
        if index in result and result[index] is None:
            result[index] = sum(n * abs(digit - d) for d, n in counts.items())
        counts[digit] += 1
    return (result[i] for i in indices)

def as_ints(iterable):
    return [int(x) for x in iterable]

if __name__ == '__main__':
    main()


Generating new random items from a list class text_generator
 {
   public int getWordIndex(List<string> source, Random value)
    {
      return value.Next(0, source.Count - 1);
    }
      public bool checkListLength(List<string> source)
    {
      return source.Count == 0;
    }
   public string getText(List<string> source, List<string> backup_source, Random value)
    {
      if (checkListLength(source))
      {
        source.AddRange(backup_source);
      }
      ;
      int index = getWordIndex(source, value);
      string result = source[index];
      source.RemoveAt(index);
      return result;
  }
}

Then I open a main list and an empty list.

text_generator textix = new text_generator();
List<string> hi = new List<string> { "Hi", "Howdy", "Hey", "etc" };
List<string> work_hi = new List<string>();

And... Generate. They will always be different until all elements will be used.

Random rand = new Random();
Console.WriteLine(textix.getText(work_hi, hi, rand));

My question is: While this code works fine, it seems a bit long. Is it possible to make the same with just one method? Is it possible NOT to open one more list? How can I do it?

There is lots that can be improved here. I won't repeat the great points that others have already made. Some thoughts:

Why are all these methods public?  Do you intend that CheckListLength is going to be called by code external to this class?  Only make things public that are part of the public surface of the class.
Why are any of these methods instance methods?  There is no instance data. They could all be static.
The contract of the primary method is bizarre. Summing up: you require that the user pass in two lists. If the first is empty, it becomes a copy of the second. The second list is then never touched again. Random items are chosen from the first list, and removed.  Think about how many ways there are for that to go horribly wrong. What if the user passes in two completely different lists? What if they pass in two references to the same list?  This is a disaster waiting to happen.
Consider the cost.  Suppose the method is used as it is supposed to be: we pass in an empty list and a list with N items. We wish to get out the N items in a random order. Now, I will tell you this crucial fact: the cost of removing an item from a list at random is on average proportional to the number of items in the list.  That's because lists are packed. If you have a million items in a list and you remove item number 123, then item 124 has to be moved into slot 123, item 125 has to be moved into slot 124, and so on up to item 1000000 being moved into slot 999999.  You are performing that operation N times, and the cost each time is proportional to N. If you work out the math you'll find that on average, if you use this method to fully randomize a list, then you are performing about N2/2 operations.  That's nothing if N is 4, but it is a trillion if N is a million; you will wait a long time to get your list randomized.
Your goal of producing a random sequence without modifying the original list is a really good one.  There are two far easier ways to do that, and I encourage you to try both of them.  They are:

First: make a method with this signature:

public static List<T> ProduceShuffle<T>(this IList<T> original)

You can have the method take a Random if you like as well.

the action of the method is:

Make a copy of the original list.
Loop from the end of the list to the beginning of the list
Each time through the loop, choose a random number less than or equal to the current index. This is key; you must not choose a random number covering the entire size of the list, otherwise the shuffle is biased.
Swap the element at the current index with the element at the randomly chosen index.

This is the Knuth Shuffle, also called the Fischer-Yates shuffle, and it is very efficient. Can you implement the code from my description? Can you produce an argument that this shuffle is both efficient and unbiased?

The second way to do it is much shorter but slightly less efficient.

public static List<T> ProduceShuffle<T>(this IEnumerable<T> original, Random random)
{
    return original.OrderBy(x => random.NextDouble()).ToList();
}

That is: generate a random fraction associated with each element. Produce a sorted sequence -- without modifying the original sequence -- that is sorted by that random element. Then turn that thing into a list and return it.

I note that some people on StackOverflow will tell you to sort by a new guid rather than by a random number because guids are random. This is a bad idea. Guids are unique; that guids happen to gain their uniqueness through randomness is an implementation detail subject to change. Use guids as a source of uniqueness, not as a source of randomness.


Parsing numbers and ranges from a string in Javascript I would like to convert a string like "1 2 3-5" to an array of numbers [1, 2, 3, 4, 5].

Following the robustness principle, the list doesn't need to be separated by spaces, comma on any other separator is accepted. The only mandatory syntax is A-B to represent range from A to B (inclusive). Also, it's ok to ignore malformed input (like 1-3-5), it can be considered "undefined behavior" as long as it doesn't raise an exception.

My current code is a follow:

function parse(string) {
    let numbers = [];
    for (let match of string.match(/[0-9]+(?:\-[0-9]+)?/g)) {
        if (match.includes("-")) {
            let [begin, end] = match.split("-");
            for (let num = parseInt(begin); num <= parseInt(end); num++) {
                numbers.push(num);
            }
        } else {
            numbers.push(parseInt(match));
        }
    }
    return numbers;
}

This seems quite convoluted for such a simple task. Is there any alternative more straightforward using "modern" Javascript (I'm targeting ES6)?

On modern environments that support it (which is pretty much all of them except Safari), you can make it a bit nicer by using matchAll instead of match, and use capture groups to capture the digits immediately, rather than having to use an .includes check and split afterwards:

function parse(string) {
    const numbers = [];
    for (const [, beginStr, endStr] of string.matchAll(/(\d+)(?:-(\d+))?/g)) {
        const [begin, end] = [beginStr, endStr].map(Number);
        numbers.push(begin);
        if (endStr !== undefined) {
            for (let num = begin + 1; num <= end; num++) {
              numbers.push(num);
          }
        }
    }
    return numbers;
}

console.log(parse('11 14-16 18-20'));

(For older environments, you'll need a polyfill)

Also note that you should always use const to declare variables whenever possible - only use let when you need to warn readers of the code that you may have to reassign the variable in the future.


Prevent Double Form Submit within X seconds I want to prevent double form submissions within a small window, then allow the form to be submitted again.

I wrote this script after looking at several examples, but the global variable is bugging me. I'd welcome any suggestions on improving it.

var aLockedForms=   [];
jQuery.fn.preventDoubleSubmit=  function() {

    jQuery( this ).submit( function() {
        if ( this.beenSubmitted )
            return false;

        this.beenSubmitted= true;

        aLockedForms.push( this );

        setTimeout( function() {
                        var domTarget=  aLockedForms.shift();
                            domTarget.beenSubmitted=    false;

                    } ,
                    1984 );

    });

};

After the DOM is loaded, I run the following:

$( "form" ).preventDoubleSubmit();

Regarding the global variable, you're already using jQuery so why not just attach an attribute or class to the form?

jQuery.fn.preventDoubleSubmit=function(duration) {
    duration = duration || 1984;
    jQuery( this ).submit( function() {
        if ( this.hasClass("locked") ) return false;
        jQuery(this).addClass("locked");
        that = this;
        setTimeout(function() {
            jQuery(that).removeClass("locked");
        }
        , duration );
    });
};

You may want to change the class name to something a little more unique, but that should work.


HTML/JavaScript temperature converter with rounding I am looking to improve the performance of my code through best practices and cleaner code.
My goal here is just to perform a conversion whenever there is a keyup.
But I noticed that my code looks very repetitive. In your view, what should I do to simplify it?

window.oninput = function(event) {
  var campo = event.target.id;

  // DECIMALS
  var i = document.getElementById("decimalTemp").value;
    ºC.value = (ºC.value * 1).toFixed(i);
    ºK.value = (ºK.value * 1).toFixed(i);
    ºF.value = (ºF.value * 1).toFixed(i);
    ºRa.value = (ºRa.value * 1).toFixed(i);
  // TEMPERATURE
  if (campo == "ºC") {
    ºK.value = (ºC.value * 1 + 273.15).toFixed(i);
    ºF.value = (ºC.value * 1.8 + 32).toFixed(i);
    ºRa.value = ((ºC.value * 1 + 273.15) * 1.8).toFixed(i);
  } else if (campo == "ºK") {
    ºC.value = (ºK.value * 1 - 273.15).toFixed(i);
    ºF.value = (ºK.value * 1.8 - 459.889).toFixed(i);
    ºRa.value = (ºK.value * 1.8).toFixed(i);
  } else if (campo == "ºF") {
    ºC.value = ((ºF.value * 1 - 32) / 1.8).toFixed(i);
    ºK.value = ((ºF.value * 1 + 459.67) / 1.8).toFixed(i);
    ºRa.value = (ºF.value * 1 + 459.67).toFixed(i);
  } else if (campo == "ºRa") {
    ºC.value = (ºRa.value / 1.8 - 273.15).toFixed(i);
    ºK.value = (ºRa.value / 1.8).toFixed(i);
    ºF.value = (ºRa.value * 1 - 459.67).toFixed(i);
  }

};

Temperature <input type="number" min="0" max="12" value="0" id="decimalTemp" name="decimal" placeholder="Decimal"> Decimals

Celsius (ºC) <input id="ºC" type="number" min="-273.15" value="20">

 Kelvin (K) <input id="ºK" type="number" min="0" value="293">

 Farenheit (ºF) <input id="ºF" type="number" min="-459.67" value="68">

 Rankine (ºRa) <input id="ºRa" type="number" min="0" value="528">

Complete code on JSFiddle

Keep it simple
Your code is overly complex as you are doing too many conversions C <=> F, C <=> Ra, and Ra <=> F can all be avoided.
When doing any type of unit conversion select a base unit and then only convert between the base unit and other units.
By using a base unit you can do all the conversions with only 6 formulas, rather than the 12 you are currently using.
General review
HTML
It is important for the content of a web page to have machine readable information that is unambiguous and semantically meaningful. Many people need assistance to interact with web pages, if the machine can not understand the content these people can not use the page.
Also bots (such as search engines use to rank pages) can not accurately assess a page's content if it does not understand what the page contains.
I am not HTML expert so these are just the basic points. See rewrite for more info

Use appropriate elements

Use the Labels to label inputs
The different units temperatures are a list, use an unordered list to hold the inputs and labels.

Related data
Do NOT! use id to store semantic information. That does not mean you should not use meaningful id names, rather you should add the semantic information using more appropriate attributes and or elements.
For example you use the event.target.id to determine which unit is being changed. Rather than use the id store the input elements unit type as a dataset attribute. See rewrite

JavaScript

window
Your use of window is redundant as window is the global this (scope).
window.oninput = function(event) { is identical to  oninput = function(event) {

Add listeners don`t set listeners
You should avoid assigning event listeners directly as they can be overwritten, by you accidentally, or by 3rd party content. E.G. adverts.
Use addEventListener as it adds listeners
E.G. oninput = function(event) { /*... code ... */ } should be addEventListener("input", function(event) { /*... code ... */ });
NOTE: The event name when using addEventListener does not include the on prefix. "oninput" becomes "input"

Constants
For variables that do not change declare them as constants. eg const campo = event.target.id;

Indentation
Watch your indentation, the four lines below var i = document.ge... are incorrectly indented.

Use standard keyboard characters
The use of º via the keyboard dance LEFT ALT 167 is unnecessary as it adds nothing to the quality or readability of the code.

Magic Numbers
Numbers seldom have meaning on there own. They are also easy to get wrong it you have a lot of them. Give numbers names by defining them as constants.
1.8 could mean anything... so remove the guess work with const RANKINE_SCALE = 1.8

Problem
Inputs can get stuck because the input step and min values are not set or incorrect
Changing the number of decimal points means you must change the step value for each input. E.G. Decimal 0 step 1, Decimal 1 step 0.1, 2 step 0.01, and so on.
To control the step position you can not set the min attribute to be a value that is not divisible by step.  For all by Kelvin and Rankine the min value is problematic.
But using Kelvin as a the base unit we need only define its min attribute and in JS make sure its >= 0 so that the other units don't go out of bounds.
Rewrite
The rewrite add some CSS, a lot of HTML and splits the JS into many parts.

Only the Kelvin input value is defined with a min and step and value. The other values are set when the JavaScript first runs by calling decimalEvent

Each temperature input uses data-unit="" to name the unit used. This name is used to lookup the correct conversion function in the object toKelvin.

Temperature and decimal input events are split. The decimal listener will call the Temperature listener which will use the default target kelvin if called without an event

const F_SCALE = 1.8, F_OFFSET = 459.67;
const C_OFFSET = 273.15;
const toKelvin = {
    Celsius:   t => t + C_OFFSET,
    Farenheit: t => (t + F_OFFSET) / F_SCALE,
    Rankine:   t => t / F_SCALE,
    Kelvin:    t => t,
};
const fromKelvin = {
    Celsius:   k => celsiusIn.value =   round(k - C_OFFSET),
    Farenheit: k => farenheitIn.value = round(k * F_SCALE - F_OFFSET),
    Rankine:   k => rankineIn.value =   round(k * F_SCALE),
    Kelvin:    k => kelvinIn.value =    round(k),
};
const round = val => Math.round(val * round.scale) / round.scale;

decimalIn.addEventListener("input", decimalEvent);
temperatureList.addEventListener("input", temperatureEvent);
decimalEvent();

function decimalEvent() {
    const step = 1 / (round.scale = 10 ** decimalIn.value);
    celsiusIn.step = step;
    kelvinIn.step = step;
    farenheitIn.step = step;
    rankineIn.step = step;
    temperatureEvent();
}
function temperatureEvent({target = kelvinIn} = {}) {
    if (target.value !== "") {
        const unit = target.dataset.units;
        const kelvin = Math.max(0, toKelvin[unit](round(Number(target.value))));
        for (const convert of Object.values(fromKelvin)) { convert(kelvin) }
    }
}
label {
    font-size: large;
}
input {
    width: 3em;
}
ul {
    width: 220px;
    display: flex;
    flex-direction: column;
    list-style-type: none;
    padding-inline-start: 0px;
}
li input {
    float: right;
    width: 7em;
}

Temperature unit converter

 <input type="number" min="0" max="5" value="0" step="1" id="decimalIn">
Decimals

    Celsius (ºC)
    <input id="celsiusIn" type="number"  data-units ="Celsius">

    Kelvin (K)
    <input id="kelvinIn" type="number" min="0" value="293" step="1" data-units="Kelvin">

    Farenheit (ºF)
    <input id="farenheitIn" type="number" data-units="Farenheit">

    Rankine (ºRa)
    <input id="rankineIn" type="number"  data-units="Rankine">

Update
The original rewrite had a few problems.

Could not type negative values in some situations
Was converting digits past the decimal count
Was displaying trailing zeros. Eg 0.000 should be just 0

The code has been changed to ignore partial inputs. E.G. the negative sign '-' before the numbers are added.
Using Math.round rather than Number.toFixed to set the number of decimal places.
Round the decimals before converting to base unit (kelvin) to stop fractions past the number of decimal making changes to other units.


show/hide components The following code is used to show/hide components in an AngularJS app:

var vm = this;

var hideComponents = function()
{
   vm.showRegions = false;
   vm.showAccounts = false;
   vm.showOrders = false;
   vm.showInvoices = false;
   vm.showWarehouses = false;
}

vm.showComponent = function(componentName)
{
   hideComponents();
   switch (componentName) {
      case "Regions":
         vm.showRegions = true;
         break;
      case "Accounts":
         vm.showAccounts = true;
         break;
      case "Orders":
         vm.showOrders = true;
         break;
      case "Invoices":
         vm.showInvoices = true;
         break;
      case "Warehouses":
         vm.showWarehouses = true;
         break;
      default:
   }
}

Is there a more concise way to achieve this functionality?

I was thinking something along these lines:

var setComponentVisibility = function (componentName = null)
{
   var bool = false;
   var map = {
       'Regions': vm.showRegions = bool,
       'Accounts': vm.showAccounts = bool,
       'Orders': vm.showOrders = bool,
       'Invoices': vm.showInvoices = bool,
       'Warehouses': vm.showWarehouses = bool
   }
   if (componentName != null)
   {
      // code to set bool to true only for that componentName in map
      // is this even possible?
      // if so, how?
   }
}

However, being new to AngularJS, I'm not sure the above is possible.

You can use Bracket Notation to have custom object key by ['text'+variable].

vm.showComponent = function(componentName)
{
   hideComponents();
   vm['show' + componentName]=true;
}


Set a font for a UITextView if the font is nil or not equal to desired font Main question
I am setting a font for a UITextView that is a subview in a custom view. I only set it if the user didn't specify the font size in the Interface Builder.
I have the following working code
if self.view.font == nil || self.view.font!.fontName != mongolFontName {

        view.font = UIFont(name: mongolFontName, size: defaultFontSize)

}

but the if line seems more verbose than it needs to be. Is there a more concise way of getting the same result?
Extra background info
This is a continuation in the same vane of a previous question. After making changes based on advice from the answers there (though still more to do), the code I have now is
import UIKit

@IBDesignable class UIMongolTextView: UIView {

    // ********* Unique to TextView *********
    private let view = UITextView()
    let mongolFontName = "ChimeeWhiteMirrored"
    let defaultFontSize: CGFloat = 17

    @IBInspectable var text: String {
        get {
            return view.text
        }
        set {
            view.text = newValue
        }
    }

    @IBInspectable var fontSize: CGFloat {
        get {
            if let font = view.font {
                return font.pointSize
            } else {
                return 0.0
            }
        }
        set {
            view.font = UIFont(name: mongolFontName, size: newValue)
        }
    }

    func setup() {

        view.backgroundColor = UIColor.clearColor()

        // set font if user didn't specify size in IB
        if self.view.font == nil || self.view.font!.fontName != mongolFontName {

            view.font = UIFont(name: mongolFontName, size: defaultFontSize)
        }

    }

    // *******************************************
    // ****** General code for Mongol views ******
    // *******************************************

    private var oldWidth: CGFloat = 0
    private var oldHeight: CGFloat = 0

    // This method gets called if you create the view in the Interface Builder
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    // This method gets called if you create the view in code
    override init(frame: CGRect){
        super.init(frame: frame)
        self.setup()
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        self.setup()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // layoutSubviews gets called multiple times, only need it once
        if self.frame.height == oldHeight && self.frame.width == oldWidth {
            return
        } else {
            oldWidth = self.frame.width
            oldHeight = self.frame.height
        }

        // Remove the old rotation view
        if self.subviews.count > 0 {
            self.subviews[0].removeFromSuperview()
        }

        // setup rotationView container
        let rotationView = UIView()
        rotationView.frame = CGRect(origin: CGPointZero, size: CGSize(width: self.bounds.height, height: self.bounds.width))
        self.addSubview(rotationView)

        // transform rotationView (so that it covers the same frame as self)
        rotationView.transform = translateRotateFlip()

        // add view
        view.frame = rotationView.bounds
        rotationView.addSubview(view)

    }

    func translateRotateFlip() -> CGAffineTransform {

        var transform = CGAffineTransformIdentity

        // translate to new center
        transform = CGAffineTransformTranslate(transform, (self.bounds.width / 2)-(self.bounds.height / 2), (self.bounds.height / 2)-(self.bounds.width / 2))
        // rotate counterclockwise around center
        transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
        // flip vertically
        transform = CGAffineTransformScale(transform, -1, 1)

        return transform
    }

}

There's a much easier way of doing this.

if self.view.font?.fontName != mongolFontName {
    view.font = UIFont(name: mongolFontName, size: defaultFontSize)
}

We should always prefer optional binding and optional unwrapping (?) to forced (!).

When the value we're optionally unwrapping is nil, we just get nil back.  And of course, nil and mongolFontName aren't going to be the same (unless you've set up mongolFontName as nil), so we enter the if's body.

Consider this example from the playground:


Branch-and-bound based IP solver I've written this rather naïve branch-and-bound based IP solver.

Are there any obvious JavaScript optimisations that could speed it up?  I am not looking for asymptotically better algorithms, just simple speed optimisations effective on problem sizes with 5-6 variables and minSize values up to about 500.

/** Represents a simple 1-dimensional
 * IP (Integer Programming) problem.
 * @constructor
 * @param {Array<size: Number, cost: Number>} priceList
 *   List of costs for given sizes.
 *   Note that this list will be sorted by this constructor.
 */
function Prices (priceList) {
  this.prices = priceList;
  this.prices.sort (PriceCompare);
  this.minimise = PricesMinimise;
  this.pricesBB = PricesBB;
}

/** Solves the simple 1-dimensional IP problem:
 * Minimise Sum_i cost_i * x_i
 *    where Sum_i size_i * x_i >= minSize
 *      and cost_i, size_i are positive reals,
 *      and x_i is a nonnegative integer. (i = 0..prices.length - 1)
 *
 * cost_i = this.prices[i].cost and size_i = this.prices[i].size.
 *
 * @param {Number} minSize  The minimum size that must be supplied.
 * @return {xs: Array, cost: Number}  [x_0, x_1, ...] and total cost.
 */
function PricesMinimise (minSize) {
  this.minSize = minSize;
  this.incumbent = Number.POSITIVE_INFINITY;
  this.maxCost = Number.POSITIVE_INFINITY;
  var xsCost = this.pricesBB (0, 0, 0, 0);
  xsCost.xs.reverse ();
  return xsCost;
}

/** Solves a sub problem using only price list elements with
 * index >= i.  It uses instance fields
 * minSize: the minimum required size sum,
 * incumbent: lowest full solution cost seen so far,
 * maxCost: upper bound on full solution cost.
 * @param {Number} i        Minimum price list index.
 * @param {Number} sizeSum  Size sum already selected.
 * @param {Number} costSum  Cost sum already spent.
 * @param {Number} minCost  Lower bound on full solution cost in this
 *                          subtree.
 * @return {xs: Array, cost: Number}  A minimum candidate
 *   solution, or null if none better than the incumbent were
 *   found.
 */
function PricesBB (i, sizeSum, costSum, minCost) {
  var price = this.prices [i];
  var size = price.size;
  var cost = price.cost;
  var xReal = (this.minSize - sizeSum) / size;
  var x = Math.ceil (xReal);
  var localCostSum;
  if (size == Number.POSITIVE_INFINITY) {
    x = 1;
    size = 0; // Avoid NaN in recursive call
    localCostSum = cost;
  } else {
    localCostSum = costSum + cost * x;
    var localMinCost = costSum + cost * xReal;
    minCost = Math.max (minCost, localMinCost);
    if (localMinCost >= this.incumbent) return null;
  }
  this.maxCost = Math.min (this.maxCost, localCostSum);
  var localMin = {'xs': [x], 'cost': localCostSum};
  if (localCostSum < this.incumbent) this.incumbent = localCostSum;
  if (localCostSum == minCost) return localMin;
  if (i < this.prices.length - 1)
    for (x--; x >= 0; x--) {
      var xsCost =
        this.pricesBB (i + 1, sizeSum + size * x, costSum + cost * x, minCost);
      if (xsCost == null) continue;
      xsCost.xs.push (x);
      localMin = xsCost;
      if (localMin.cost == minCost) return localMin;
    }
  if (localMin.cost == this.incumbent)
    return localMin;
  else
    return null;
}

Nowadays we have great tools at our disposal, one of them is The Closure Compiler from Google, which is a tool for making JavaScript download and run faster.  It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.

So, the web version of Closure Compiler gave me the following recommendations for your snippet:

Example,
this.incumbent = Number.POSITIVE_INFINITY;
this.maxCost = Number.POSITIVE_INFINITY;
becomes this.maxCost = this.incumbent = Number.POSITIVE_INFINITY;
Other obvious speed enhancements that can be automated with minification:

Use parameters as a variable instead of another var:
var minSize = this.pricesBB(0, 0, 0, 0);
Reuse var's when they are longer in user in a function instead of declaring new ones
Shorten variable names (parsing speed issue)
var price = this.prices [i];
var size = price.size; becomes var price = this.prices[i], g = price.size;

The full result of the Closure Compiler for your piece Javascript:

function Prices(c) {
  this.prices = c;
  this.prices.sort(PriceCompare);
  this.minimise = PricesMinimise;
  this.pricesBB = PricesBB
}
function PricesMinimise(c) {
  this.minSize = c;
  this.maxCost = this.incumbent = Number.POSITIVE_INFINITY;
  c = this.pricesBB(0, 0, 0, 0);
  c.xs.reverse();
  return c
}
function PricesBB(c, i, h, f) {
  var e = this.prices[c], g = e.size;
  e = e.cost;
  var a = (this.minSize - i) / g, d = Math.ceil(a), b;
  if(g == Number.POSITIVE_INFINITY) {
    d = 1;
    g = 0;
    b = e
  }else {
    b = h + e * d;
    a = h + e * a;
    f = Math.max(f, a);
    if(a >= this.incumbent) {
      return null
    }
  }
  this.maxCost = Math.min(this.maxCost, b);
  a = {xs:[d], cost:b};
  if(b < this.incumbent) {
    this.incumbent = b
  }
  if(b == f) {
    return a
  }
  if(c < this.prices.length - 1) {
    for(d--;d >= 0;d--) {
      b = this.pricesBB(c + 1, i + g * d, h + e * d, f);
      if(b != null) {
        b.xs.push(d);
        a = b;
        if(a.cost == f) {
          return a
        }
      }
    }
  }
  return a.cost == this.incumbent ? a : null
}
;


Efficient way to remove duplicate strings after adding their key values How can I remove duplicate strings from a std::vector<std::pair<std::string,int>> after adding the int members of the pair and sorting them by their string members?

For example:

abc   4
abc   3
xy    1
xyzw  12
xy    4
abc   14

should produce the result:

abc   21
xyzw  12
xy    5

I have actually used std::vector<Mystruct> as the data structure, with:

struct Mystruct
{
    string s;
    int e;
};

and sorted them with respect to their string values and linearly iterated by adding the keys and removing duplicates, and again sorted according to their key values and ended up getting Time Limit Exceeded.

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
#define ull unsigned long long
struct vec
{
    string s;
    ull e;
};
bool compare(vec v1, vec v2) {
    return v1.s < v2.s;
}
bool comparenum(vec v1, vec v2) {
    return v1.e < v2.e;
}
int main() {
    int q;
    cin >> q;
    string ss;
    ull ee;
    vector<vec> v(q);
    for (int i = 0; i<q; i++) {
        cin >> ss >> ee;
        v[i].s = ss;
        v[i].e = ee;
    }
    sort(v.begin(), v.end(), compare);
    for (int i = 0; i < v.size() - 1; i++) {
        if (v[i + 1].s == v[i].s) {
            v[i].e = v[i].e + v[i + 1].e;
            v.erase(v.begin() + i + 1);
            i--;
        }
    }
    sort(v.begin(), v.end(), comparenum);
    for (vec vv : v) {
        cout << vv.s << " " << vv.e << endl;
    }
    return 0;
}

Avoid using namespace std;

Importing all names of a namespace is a bad habit to get into, and can cause surprise when names like begin and size are in the global namespace.  Get used to using the namespace prefix (std is intentionally very short), or importing just the names you need into the smallest reasonable scope.

The exceptions to this rule are namespaces explicitly intended to be imported wholesale, such as the std::literals namespaces.

Avoid preprocessor macros

If you want a shorter name for a type, it's much safer to write

using ull = unsigned long long;

Personally, I'd give it a name that reflects what I want to use it for, rather than what it (currently) is.

Improve naming

What's the significance of vec as a name?  It's confusingly similar to vector, but it's used as an element of a vector.  Similarly, its members s and e convey nothing - consider name and count, if that's what they represent.

Simplify the logic

It's a lot easier to accumulate counts if you introduce a std::map to hold the sums:

std::map<std::string,ull> accumulator;
for (auto const& element: v)
    accumulator[element.s] += element.e;

// write them back into the vector
v.clear();
for (auto const& element: accumulator)
    v.push_back(vec{element.first, element.second});


React setState function in useEffect I'm toggling a state when the browser is resized:

const [expanded, setExpanded] = useState(true)
useEffect(() => {
  const listener = () => {
    if (document.documentElement.clientWidth > 1024) return
    setExpanded(false)
  }
  window.addEventListener('resize', listener)
  return () => window.removeEventListener('resize', listener)
}, [])

I've the react-hooks/exhaustive-deps rule enabled so ESLint complains:

  React Hook useEffect has a missing dependency: 'setExpanded'. Either include it or remove the dependency array

How should I rewrite this? Or should I simply silence the ESLint warning?

Short answer:

You can include setExpanded in the dependency array.

Long answer:

The function passed to useEffect will fire only when at least one of the dependencies changes:

useEffect(() => {
  // runs
  // - on mount
  // - on every render
})

useEffect(() => {
  // runs
  // - on mount only
}, [])

useEffect(() => {
  // runs
  // - on mount
  // - on renders where varA and/or varB change
}, [varA, varB])

You should avoid passing objects as dependencies, because they may trigger unnecessary re-renders. If varA is an object created on every render, it may have the same value but it won't be the same object, so it will be treated as change and fire up the useEffect. See the example below:

const varA = { a : 1 }
const varB = { a : 1 }

varA === varB // false

However, sometimes, certain objects are guaranteed to not produce this behaviour, and this is the case of the setState() function.
According to the React Hooks API docs:

  Note: React guarantees that setState function identity is stable and won’t change on re-renders.

This means that you can include it in the useEffect dependencies with no problem.


Getting key-value from Object in Java This takes a collection of Objects from JavaScript and puts them into a Java project. How can I improve this code? What's the best solution?

// JavaScript fetch data into List ChartData

int i = 0;
int k = 0;

// output
for (Object currObj : ChartData) {

    // get all fields of Object
    for (Field field : currObj.getClass().getDeclaredFields()) {

        field.setAccessible(true);
        Object value = field.get(currObj);
         // parse only HashMap
        if ((value != null)&&value.getClass().toString().equalsIgnoreCase("class        java.util.HashMap"))) {

            //get HashMap
            HashMap hm = (HashMap)value;
            // Get a set of the entries
            Set set = hm.entrySet();
            // Get an iterator
            Iterator j = set.iterator();

            // Display elements
            while(j.hasNext()) {
               Map.Entry me = (Map.Entry)j.next();
               if ((me.getKey().toString().equalsIgnoreCase("y"))){
                 assertTrue(Long.parseLong(me.getValue().toString()) == anArrayOfObjects[i][0]); // check pairs
                 System.out.println("Actual y value - " + me.getValue().toString() + " expected value - " + anArrayOfObjects[k][0].toString());
                 i++;
               }

               if ((me.getKey().toString().equalsIgnoreCase("x"))){
                  assertTrue(Long.parseLong(me.getValue().toString()) == anArrayOfObjects[k][1]);// check pairs
                  System.out.println("Actual x value - " + me.getValue().toString() + " expected value - " + anArrayOfObjects[k][1].toString());
                  k++;
               }
            }
        }
    }
}

Naming Convention

It is common practice and part of the SUN / Oracle Code Conventions for the Java Programming Language to start variable names with lowercase.
Thus, you might want to rename ChartData to chartData.

Oh, and j is not an acceptable name for an Iterator.
A few lines down, I can no longer remember what j was.
Usually, j is an int and used because i was used already.
And in fact you already do have an int i.

In such a case, name the Iterator it or iter or even iterator but not j.

Also, the name me for Map.Entry is a bit confusing, because the abbreviation me is a valid English word at the same time.
I'd rename me to entry.

Iterating over Map entries

Your code for iterating over the map entries is too complex.

Here's the relevant part of your code:

HashMap hm = (HashMap) value; // context
Set set = hm.entrySet();
Iterator j = set.iterator();
while (j.hasNext()) {
    Map.Entry me = (Map.Entry) j.next();
    // Do something with me.
}

You can remove the cast by telling the Set and the Iterator that they are from a Map, which means they are a Set<Map.Entry> and an Iterator<Map.Entry>.
This simplifies the code as follows:

HashMap hm = (HashMap) value; // context
Set<Map.Entry> set = hm.entrySet();
Iterator<Map.Entry> j = set.iterator();
while (j.hasNext()) {
    Map.Entry me = j.next();
    // Do something with me.
}

You can further simplify this by turning this into a for-each loop:

HashMap hm = (HashMap) value; // context
for (Map.Entry me : hm.entrySet()) {
    // Do something with me.
}

Abstract datatypes

Whether your map is a HashMap or something else is probably irrelevant.
Therefore you might want to change the datatype of variable hm from HashMap to Map.

Map hm = (Map) value;

How to check types

Java has an instanceof operator.

Your type check compares the toString() result of the class.
That has a few issues.

Your comparison relies on a specific format of Class.toString() which is not guaranteed. If you must compare the name, use getName() instead of toString().
Your comparison is case-insensitive, which is definitely the wrong thing to do in a case-sensitive language. java.util.HashMap and java.util.hashmap could in theory both exist but would be separate classes. Your code would treat java.util.hashmap as if it were the same as java.util.HashMap, which is wrong.
Your comparison checks on the class, ruling out possible subclasses of HashMap as well as alternative Map implementations. In a broader sense, you're violating the LSP - Liskov Substitution Principle.

You might want to go for this code to check the type:

Object value = field.get(currObj);
if (value instanceof HashMap) // ...

or even

Object value = field.get(currObj);
if (value instanceof Map) // ...

Interlude: New source code as of now

for (Object currObj : chartData) {
    for (Field field : currObj.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        Object value = field.get(currObj);
        if (value instanceof Map) {
            Map hm = (Map) value;
            for (Map.Entry entry : hm.entrySet()) {
                if ((entry.getKey().toString().equalsIgnoreCase("y"))) {
                    assertTrue(Long.parseLong(me.getValue().toString()) == anArrayOfObjects[i][0]); // check pairs
                    System.out.println("Actual y value - " + me.getValue().toString() + " expected value - " + anArrayOfObjects[k][0].toString());
                    i++;
                }

                if ((entry.getKey().toString().equalsIgnoreCase("x"))) {
                    assertTrue(Long.parseLong(me.getValue().toString()) == anArrayOfObjects[k][1]);// check pairs
                    System.out.println("Actual x value - " + me.getValue().toString() + " expected value - " + anArrayOfObjects[k][1].toString());
                    k++;
                }
            }
        }
    }
}

Method length

This method is far too long to be even close to maintainable source code.
As software craftsmen, we say that regarding method length Java code is maintainable if (almost) all of its methods have 5 or fewer lines.
10 lines is something which I already do not accept in production code.
(Exceptions like some GUI creation code apply.)

The code should be split into several methods.
I know that you might even have tried this - and failed, due to the local variables i and k.

Let's remember what Uncle Bob said: "Long functions are where classes use to hide." and "Extract 'till you drop" (Robert C. Martin, "Clean Code")

Refactorings to apply to get smaller methods

Extract method object.
Turn local variables i and k into fields and introduce getters for them (you wouldn't increment them if you wouldn't need them later).
Refactor the constructor argument into an argument to invoke().
Rename invoke to visit.
Extract every multiline block into a separate method with a meaningful name.
Make the two branches for "x" and "y" look identical by replacing everything which is different with variables. For that piece of code which is different we use two methods implementing a functional interface Incrementor so we can store a method reference in a variable.

Here's how this looks like as a class:

private static class ChartDataVisitor {
    private int i = 0;
    private int k = 0;

    public void visit(Iterable<Object> chartData) throws IllegalAccessException {
        reset();
        visitChartData(chartData);
    }

    private void reset() {
        i = 0;
        k = 0;
    }

    private void visitChartData(Iterable<Object> chartData) throws IllegalAccessException {
        for (Object currObj : chartData) visitObject(currObj);
    }

    private void visitObject(Object currObj) throws IllegalAccessException {
        for (Field field : currObj.getClass().getDeclaredFields()) visitField(currObj, field);
    }

    private void visitField(Object currObj, Field field) throws IllegalAccessException {
        field.setAccessible(true);
        Object value = field.get(currObj);
        if (value instanceof Map) visitMap((Map) value);
    }

    private void visitMap(Map<?, ?> hm) {
        hm.entrySet().forEach(this::visitEntry);
    }

    private void visitEntry(Map.Entry<?, ?> entry) {
        visitEntryDetails(entry, "y", i, 0, this::incrementI);
        visitEntryDetails(entry, "x", k, 1, this::incrementK);
    }

    private void visitEntryDetails(Map.Entry<?, ?> entry, String string, int index1, int index2, Incrementor incrementor) {
        if ((entry.getKey().toString().equalsIgnoreCase(string)))
            visitMatchingDetails(entry, string, index1, index2, incrementor);
    }

    private void visitMatchingDetails(Map.Entry<?, ?> entry, String string, int index1, int index2, Incrementor incrementor) {
        final String valueAsString = entry.getValue().toString();
        final Long v = anArrayOfObjects[index1][index2];
        assertTrue(Long.parseLong(valueAsString) == v); // check pairs
        System.out.println("Actual " + string + " value - " + valueAsString + " expected value - " + v.toString());
        incrementor.increment();
    }

    @FunctionalInterface
    private static interface Incrementor {
        void increment();
    }

    private void incrementK() {
        k++;
    }

    private void incrementI() {
        i++;
    }
}

You might notice that not a single method contains {} inside.
That's the whole point.
{} are an opportunity to extract.
Good methods do one thing, they do it well and they do it only.
By having {} inside, you loudly declare that your method is doing more than one thing (or in case of try that the language Java is inconsistent because otherwise it would allow for a try or catch or finally without braces).

You're of course free to reformat it to bring back the removed {}, if you like or if there are militant "{}-Pros" around you (I was one of them myself once, not so long ago).
Today I tend to avoid {} to show off "Look Ma, no {}!" - I don't need them anymore.

Unit Testing

The methods in the new class do not need to be private.
They could as well be package default or public, depending on your business logic.
Because they need not be private, you can easily unit test them individually - you can now test your business logic from inside to the out.
The various layers that were already there (nested block structure in your code) have become accessible individually.
Think of an Onion or Matryoshka.

Warning

My names visit* and similar are not very meaningful. They are physical names. I couldn't come up with better names because I have no idea about what your code is doing. I don't know what the map contains.

You should change some or even all of the the visit* method names to something which communicates the intent of your business logic much better.


General FizzBuzz in Java I have this generalization of FizzBuzz in Java:

import java.util.Map;
import java.util.TreeMap;

public class GeneralFizzBuzz {

    public static void generalFizzBuzz(Map<Integer, String> map,
                                       int start,
                                       int stop) {
        String startString = String.valueOf(start);
        String stopString = String.valueOf(stop);

        // Find the width which can accommodate any line number:
        int lineNumberWidth = Math.max(startString.length(),
                                       stopString.length());

        // Create the format string for printing line numbers:
        String lineNumberFormat = "%" + lineNumberWidth + "d: ";

        for (int i = start; i <= stop; ++i) {
            // Print the line number and the colon with a space:
            System.out.printf(lineNumberFormat, i);

            for (Map.Entry<Integer, String> entry : map.entrySet()) {
                if (i % entry.getKey() == 0) {
                    System.out.print(entry.getValue());
                }
            }

            System.out.println();
        }
    }

    public static void main(String[] args) {
        Map<Integer, String> map = new TreeMap<>();

        map.put(2, "Foo");
        map.put(7, "Bar");
        map.put(11, "Baz");

        generalFizzBuzz(map, -200, 200);
    }

}

As always, please tell me whatever comes to mind.

Hmm... the generalFizzBuzz method is a mix of business logic and output, I think this should rather be separeted.

Thus, I'd rather have a business logic conversion number, which converts a given number to test to the output string:

private static String convertNumberForOutput(Map<Integer, String> numberReplacement, int num) {
    // not necessarily better than a loop, but to show a different approach
    // (attn: I have not tried to compile this ;-))
    return numberReplacement.entrySet().stream()
        .filter(e -> (num % e.getKey()) == 0)
        .map(Map.Entry::getValue)
        .collect(Collectors.joining());
}

In the generalFizzBuzz method, replace the inner loop with a call to that function.

Naming: "map" is a no-go-name. This is like calling start and stop "numberA" and "numberB". The map has a logical purpose, so you should reflect this in its naming.


SQL Permission Handling in WinForms For my application, I've opted to use Integrated Security with Windows Authentication to access the SQL database. I've created AD security groups for each role and given them GRANT permissions on the tables and views they need to do their job.

To further keep the end users from getting to the controls I'm checking the SQL permissions using HAS_PERMS_BY_NAME() and then disabling the relevant controls.

In a static class, I have defined astatic method to get a dictionary of permissions.

namespace PartDataManager
{
    public static class Globals
    {
        public static Dictionary<string,bool> GetPermissions()
        {
            Dictionary<string,bool> Permissions = new Dictionary<string,bool>();
            string query = "SELECT \r\n";
            foreach( string table in new string[]{"appearance","appearanceSpecs","cutTemplates","cutVinyl"} )
            {
                foreach( string perm in new string[]{"INSERT","UPDATE","DELETE"} )
                {
                    query += String.Format("\t{0}HAS_PERMS_BY_NAME('{1}','OBJECT','{2}') AS {1}_{2}\r\n",(query.Length>10?",":""),table,perm);
                }
            }
            try
            {
                using( SqlConnection sql = new SqlConnection(ConnectionString) )
                using( SqlCommand cmd = new SqlCommand(query,sql) )
                {
                    sql.Open();
                    using( SqlDataReader data = cmd.ExecuteReader() )
                    {
                        data.Read();
                        for( int i = 0; i < data.FieldCount; i++ )
                            Permissions.Add(data.GetName(i), data[i].Equals(1));
                    }
                }
            }
            catch
            {
                throw;
            }
            return Permissions;
        }

        // ...

    }
}

I then use the method on loading of the form to disable the relevant controls like so (wrapped in a try... catch)...

Dictionary<string, bool> Permissions = Globals.GetPermissions();
tsmiNewApprSpec.Enabled = Permissions["appearance_INSERT"];
tsmiNewCutTemplate.Enabled = Permissions["cutTemplates_INSERT"];
tsmiEditAppr.Enabled = Permissions["appearance_UPDATE"];
//...

Is this a solid approach to handling security? Is there room for improvement without increasing complexity?

Note: When I write code, I like to do things in as few lines as possible. I have a horrible memory, so when I go back and look at it, it's like I've never seen it before and I like to be able to see a significant chunk without scrolling, or matching braces, and be able to quickly tell what it does. So, any tips that reduce lines of code will definitely be appreciated and rewarded!

So, any tips that reduce lines of code..

As a start you can remove this useless try..catch because you are only rethrowing the exception which is senseless.

Using += with strings in a loop is a bad habit because each time a new string will be created so better use a StringBuilder.
Speeking about the composition of the query variable you don't need to add new lines and tabs in it. You won't show it, you only execute it as a sql query.

In its current state this method is not flexible enough. Each time you want to query different tables or need only specific permissions you need to change this method.

By passing IEnumerable<string> tables and IEnumerable<string> permissionType you can beautify your method and add a lot flexibility to it.

Let us talk about style. If it comes to style one should stick to a choosen style.

If you choose to use braces {} for loops you should always use them. Mixing styles is a bad habit, don't do it.

Method scoped variables should be named using camelCase casing. PascalCase casing is used for class-, method- and propertynames. So Dictionary<string,bool> Permissions -> Dictionary<string,bool> permissions.

EDIT Based on the great comment of @d347hm4n stating

  In the above code, in all cases, there will be a comma on the end that needs to be removed. So removing the last character from the string builder is sufficient. If the sql generated does change in the future, using a TrimEnd instead gives you the extra intelligence to not remove the comma on the end if it's not there.

I changed the former removing of the comma from

sb.Length -= 1;
string query = sb.ToString();

to

string query = sb.ToString().TrimEnd(',');

Applying the mentioned points lead to

public static Dictionary<string, bool> GetPermissions(IEnumerable<string> tables, IEnumerable<string> permissionTypes)
{
    if (!tables.Any() || !permissionTypes.Any())
    {
        return new Dictionary<string, bool>();
    }

    StringBuilder sb = new StringBuilder(1024);
    sb.Append("SELECT ");
    foreach (string table in tables)
    {
        foreach (string perm in permissionTypes)
        {
            sb.AppendFormat("HAS_PERMS_BY_NAME('{0}','OBJECT','{1}') AS {0}_{1},", table, perm);
        }
    }

    string query = sb.ToString().TrimEnd(',');

    Dictionary<string, bool> permissions = new Dictionary<string, bool>();

    using (SqlConnection sql = new SqlConnection(ConnectionString))
    using (SqlCommand cmd = new SqlCommand(query, sql))
    {
        sql.Open();
        using (SqlDataReader data = cmd.ExecuteReader())
        {
            data.Read();
            for (int i = 0; i < data.FieldCount; i++)
            {
                permissions.Add(data.GetName(i), data[i].Equals(1));
            }
        }
    }

    return permissions;
}

and can be then called like this

IEnumerable<string> tables = new string[] { "appearance", "appearanceSpecs", "cutTemplates", "cutVinyl" };
IEnumerable<string> permissionTypes = new string[] { "INSERT", "UPDATE", "DELETE" };
Dictionary<string, bool> permissions = GetPermissions(tables, permissionTypes);


Determine how many bits are in a floating point value I'm writing a program which determines how many bits are in a floating point value (this will be run on Unix).

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

void countbits(int k);

int main(){
    int input;
    // int a = (int) malloc(sizeof(int));
    printf("Please enter a number: ");
    scanf("%d",&input);
    // a = input;

    countbits(input);
}

void countbits(int k){
    int j,count;
    count = 0;
    for(j = 0; j < 31; j++){
        if(k & 0x000001 == 1){
        count++;
        }
        k >>= 1;
    }
    printf("%d has %d bits set\n",k,count);
    // count = 0;
}

Output example:

  2 has 1 bits set
  6 has 2 bits set
  32 has 1 bits set

I'll really appreciate any feedback or correction or if there is something I can do better.

You should do the output in main(), not in countbits().  Functions should have only one primary purpose, according to the Single Responsibility Principle (SRP).  In this case, countbits() should just perform the calculations and return the result.  Thus, its return type should now be of type int.

Inside of countbits(), you could just loop while k is not 0 instead of looping 32 times.  Once all the bits in k shift away and k becomes 0, there's no point in continuing.  This will also give you a result of 0 right away if the input is 0; calculating this will be a waste of time.

int main(void) {
    int input;

    // get the input...

    int count = countbits(input);

    printf("%d has %d bits set\n", input, count);
}

int countbits(int k) {
    int count = 0;

    while (k != 0) {
        // perform calculations...
    }

    return count;
}

Some notes about this and other things:

main() should have a void parameter since it isn't taking any command line arguments.
The first (unformatted) output in main() should use puts() instead of printf().
count doesn't need to be declared and then assigned to 0.  Just initialize it to 0.
j should be initialized inside the for loop statement (if you have C99).  If you don't, then declare it right before the loop.  Variables should be used as close in scope as possible.


Using temporary variables or calling a method directly Which of these approaches for a button click is better/faster/more efficient, and why?

Approach One:

Button button = (Button) findViewById(R.id.button_english_splash);

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Toast.makeText(v.getContext(), "Clicked!", Toast.LENGTH_SHORT)
                .show();
    }
});

Approach Two:

((Button) findViewById(R.id.button_english_splash))
        .setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Toast.makeText(v.getContext(), "Clicked!",
                        Toast.LENGTH_SHORT).show();

            }
        });

Regarding speed and memory, both are completely equivalent.

The only thing this boils down to is readability. In which case the first option has an advantage.

By storing the Button button = (Button) findViewById(R.id.button_english_splash); in a temporary variable, you have the opportunity to give it a good variable name, in case the R.id identifier is not good enough.

Also, method calls like ((Button) findViewById(R.id.button_english_splash)).someMethod are often not very readable as there are several parenthesis that are added.

I would recommend sticking to the first option. Perhaps not always, but mostly.

Other comments:

Remove // TODO Auto-generated method stub comments from your code
It is good that the onClick method has been marked with @Override.
Declare the onClick method inside the XML instead


Variables, references and pointers - Write the function set (…) so that the following code works correctly I have following homework exercise from lecture "Variables, references and pointers":

Write the function set (...) so that the following code works
correctly:
int x = 3;
set(x) = 3;
cout << x << endl;  // writes 0
set(x) = 4;
cout << x << endl;  // writes 3
set(x) = 5;
cout << x << endl;  // writes 4

This is my solution:
#include <iostream>

using namespace std;

int & set(int & num);

int main(void) {
    int x = 3;
    set(x) = 3;
    cout << x << endl;  // wypisze 0
    set(x) = 4;
    cout << x << endl;  // wypisze 3
    set(x) = 5;
    cout << x << endl;  // wypisze 4
    return 0;
}

int & set(int & num) {
    static int tmp;
    int & ret = tmp;
    num = ret;
    return ret;
}

What do you think about it?

You have too many variables. The ret is not needed.

Also, for testing I would like to see some actual testing, rather than just printing to the console and letting the user do it:

#include <cassert>

void test_set() {
    int x = 3;
    set(x) = 3;
    assert(x == 0);
    set(x) = 4;
    assert(x == 3);
    // etc.
}

(Or, you could use an actual unit testing framework. But assert works for this simple case.)


Get default value from query params + repeating code The main goal of this task is to take values from the query parameter and put it in inputu. The first problem is that I don't know much about how to do it so that the code doesn't repeat itself and I don't know how specifically I could improve the code so that multiple things don't happen again.
Next, the function should contain a simple validation of min max to prevent them from entering silliness from the query parameter.
getFromQuery = props => {
    const { limitValues } = props;
    const parsed = queryString.parse(location.search);

    const validation = (value, min, max) => {
        if (value < min) {
            return min;
        } else if (value > max) {
            return max;
        }
        return value;
    };

    if (parsed.price) {
        const defautPrice = limitValues.find(item => item.sliderType === 'PRICE');
        props.inputs.PRICE = validation(parsed.price, defautPrice.minValue, defautPrice.maxValue);
    }

    if (parsed.savings) {
        const defautSavings = limitValues.find(item => item.sliderType === 'SAVINGS');
        props.inputs.SAVINGS = validation(parsed.savings, defautSavings.minValue, defautSavings.maxValue);
    }

    if (parsed.maturity) {
        const defautMaturity = limitValues.find(item => item.sliderType === 'MATURITY');
        props.inputs.MATURITY = validation(parsed.maturity, defautMaturity.minValue, defautMaturity.maxValue);
    }
};

The validation function:
const validation = (value, min, max) => {
    if (value < min) {
        return min;
    } else if (value > max) {
        return max;
    }
    return value;
};

Bounds the value between some minimum and maximum, can can be simplified to the following:
const validation = (value, min, max) => Math.max(min, Math.min(value, max));

For the rest, each "case" abstractly searches the limitValues array for a matching object by slider type, and then bounds the input value for that case. A general purpose utility could look like the following:
const processField = (key, fieldValue) => {
  const val = limitValues.find(({ sliderType }) => sliderType === key);
  props.inputs[key] = val
    ? validation(fieldValue, val.minValue, val.maxValue)
    : fieldValue;
};

Since Array.prototype.find can potentially return undefined for no matches, you should guard check this. the second line uses a ternary to check if a defined value was returned from the find and returns the bounded field value otherwise returns the unbounded field value.
Here is your updated example code:
const validation = (value, min, max) => Math.max(min, Math.min(value, max));

...

getFromQuery = (props) => {
  const { limitValues } = props;
  const parsed = queryString.parse(location.search);

  const processField = (key, fieldValue) => {
    const val = limitValues.find(({ sliderType }) => sliderType === key);
    // Mutates props object
    props.inputs[key] = val
      ? validation(fieldValue, val.minValue, val.maxValue)
      : fieldValue;
  };

  if (parsed.price) {
    processField("PRICE", parsed.price);
  }

  if (parsed.savings) {
    processField("SAVINGS", parsed.savings);
  }

  if (parsed.maturity) {
    processField("MATURITY", parsed.maturity);
  }
};


C# version of C++ shared_ptr I need something akin to C++'s shared_ptr. Essentially I need an IDisposable item that I can ensure is cleaned up as soon as possible once all references have been removed, but this resource will be shared between many classes.

I don't allow passing in of a an already existing object as it's an easy way to know that the item I'm using isn't being hasn't already been disposed.

Unfortunately I can't think of a way to prevent the user of Item from disposing the underlying item, but as this is to go into my own program I'm not too concerned about that because it intuitively makes sense to not dispose something within a wrapper, provided every class that needs the item uses the wrapper and not just the contained item.

I simply want to know if anyone can see any potential issues with this solution besides what's mentioned.

public class SharedDisposable<T> : IDisposable where T : class, IDisposable {
    static SharedDisposable(){
        instances = new Dictionary<T, List<SharedDisposable<T>>>();
    }

    public SharedDisposable(SharedDisposable<T> share) {
        Item = share.Item;
        instances[Item].Add(this);
    }
    public SharedDisposable(object[] ctorArgs = null) {
        if(ctorArgs == null)
            ctorArgs = new object[] { };

        var ctor = typeof(SharedDisposable<T>).GetConstructor(ctorArgs.Select(a => a.GetType()).ToArray());
        Item = (T)ctor.Invoke(ctorArgs);
        instances[Item] = new List<SharedDisposable<T>>() { this };
    }
    public SharedDisposable(KeyValuePair<Type, object>[] ctorArgs) {
        var ctor = typeof(SharedDisposable<T>).GetConstructor(ctorArgs.Select(a => a.Key).ToArray());
        Item = (T)ctor.Invoke(ctorArgs.Select(a => a.Value).ToArray());
        instances[Item] = new List<SharedDisposable<T>>() { this };
    }

    public void Dispose() {
        var instanceList = instances[Item];
        instanceList.Remove(this);
        if(instances.Count == 0) {
            instances.Remove(Item);
            Item.Dispose();
        }
    }

    public T Item { get; }
    static Dictionary<T, List<SharedDisposable<T>>> instances;
}

Example usage:

class MainForm : Form {
    public MainForm(){
        InitializeComponent();

        Port = new SharedDisposable<SerialPort>("COM5", 9600);
    }
    public MainForm(SharedDisposable<SerialPort> share){
        InitializeComponent();

        if(share == null)
            throw new ArgumentNullException(nameof(share))
        Port = new SharedDisposable<SerialPort>(share);
    }

    public void BtnDevice1Info_Click(object sender, EventArgs e){
        new Device1InfoForm(Port).Show();
    }
    public void BtnDevice2Info_Click(object sender, EventArgs e){
        new Device2InfoForm(Port).Show();
    }

    override Dispose(bool disposing){
        if(disposing){
            Port.Dispose();
        }
        base.Dispose(disposing);
    }

    private SharedDisposable<SerialPort> Port { get; }
}

In my application I actually have a Modbus interface instead of serial port but I just realised the way the constructor is setup won't allow me to use the Modbus API because the Modbus API uses factories instead of constructors, so I'll need to adjust it for that.
But that API should be able to queue messages to be sent out one at a time, preventing any conflicts on the serial port while also allowing multiple forms or even applications to use the same serial port. In order to make this happen I need multiple forms to be able to share a disposable resource, but none of them to clean it up unless they're the last holder of that resource.

public SharedDisposable(object[] ctorArgs = null)
{
  if (ctorArgs == null)
      ctorArgs = new object[] { };

  var ctor = typeof(SharedDisposable<T>).GetConstructor(ctorArgs.Select(a => a.GetType()).ToArray());
  Item = (T)ctor.Invoke(ctorArgs);
  instances[Item] = new List<SharedDisposable<T>>() { this };
}

This constructor is not a very good idea because the use needs to exactly know the signature of the constructor in order to create T.

A much better way would be to let him specify a factory lambda. Then all it will be left is:

public SharedDisposable(Func<T> create)
{
    Item = create();
    instances[Item] = new List<SharedDisposable<T>>() { this };
}

so now he can call it in a much easier fashion like:

Port = new SharedDisposable<SerialPort>(() => new SerialPort("COM5", 9600));

The other constructor using KeyValuePairs is now obsolete.

public SharedDisposable(object[] ctorArgs = null)
{
  if (ctorArgs == null)
      ctorArgs = new object[] { };
  ...
}

Btw. you can make this look cleaner with the coalesce operator: ??

ctorArgs = ctorArgs ?? new object[] { };

Objects like this one usully use the name Value for what you chose Item.

Its usage might be easier in certain scenarios if you added an implicit cast operator to T:

public static implicit operator T(SharedDisposable<T> share) => share.Value;

If you replaced the List by a HashSet the Dispose method could be simplified to:

public void Dispose()
{
    if (instances[Value].Remove(this) && instances[Value].Count == 0)
    {
        instances.Remove(Value);
        Value.Dispose();
    }
}