Q:

Rearrange rows in data frame

I have a data frame in R which looks like this with two columns:
ID     phone_number
Mark     866458
Paul     986564
Jack     987543
Mary     523422

I would like to have this kind of output where I only have one single column
Mark
866458
Paul
986564
Jack
987543
Mary
523422

Anybody knows which R code could I use to obtain the output?

Data for reproducibility:
structure(list(ID = c("Mark", "Paul", "Jack", "Mary"), phone_number = c(866458,
                                                                        986564, 987543, 523422)), row.names = c(NA, -4L), class = c("tbl_df", "data.frame"))

A:

We can transpose the dataframe and then create one vector of values
data.frame(new_col = c(t(df)))

#  new_col
#1    Mark
#2  866458
#3    Paul
#4  986564
#5    Jack
#6  987543
#7    Mary
#8  523422

Another base R option using mapply
data.frame(new_col = c(mapply(c, df$ID, df$phone_number)))


Q:

ISNULL Date month

I have two dropdownlists, one with months and the other one with year. The user selects the submit month and year  for the items they want to retrieve. In database the date is entered in full eg. 01/12/2009. There is an option for "All years" and "All months" in the dropdown lists but when users choose either they get null results. Many thanks. This is my query:
SELECT ItemID, YEAR(Submit) AS SubmitYear, MONTH(Submit) AS SubmitMonth
FROM Items
WHERE (YEAR(Submit) LIKE ISNULL(@YearPay, ''))
 AND (MONTH(Submit) LIKE ISNULL(@MonthPay, ''))

My parameter are:
<asp:ControlParameter ControlID="DropDownList1" DefaultValue="" Name="YearPay" PropertyName="SelectedValue" />
<asp:ControlParameter ControlID="DropDownList2" DefaultValue="" Name="MonthPay" PropertyName="SelectedValue" />

A:

Here's one way to solve the problem:
 SELECT ItemID, YEAR(Submit) AS SubmitYear, MONTH(Submit) AS SubmitMonth
 FROM Items
 WHERE (YEAR(Submit) = @YearPay OR @YearPay IS NULL)
 AND (MONTH(Submit) = @MonthPay OR @MonthPay IS NULL)

That way, if you pass in NULL for either variable, that part of the WHERE clause will return true.


Q:

MongoDB: not all the results are returned from a query, using $geoNear

I got this query :
 exports.search = (req, res) => {

  let lat1 = req.body.lat;
  let lon1 = req.body.lng;
  let page = req.body.page || 1;
  let perPage = req.body.perPage || 10;
  let radius = req.body.radius || 100000; // This is not causing the issue, i can remove it and the issue is still here

  var options = { page: page, limit: perPage, sortBy: { updatedDate: -1 } }

  let match = {}

  var aggregate = null;

  if (lat1 && lon1) {

    aggregate = Tutor.aggregate([
      {
        "$geoNear": {
          "near": {
            "type": "Point",
            "coordinates": [lon1, lat1]
          },
          "distanceField": "distance", // this calculated distance will be compared in next section
          "distanceMultiplier": 0.001,
          "spherical": true,
          "key": "loc",
          "maxDistance": radius
        }
      },
      {
        $match: match
      },
      { "$addFields": { "islt": { "$cond": [{ "$lt": ["$distance", "$range"] }, true, false] } } },
      { "$match": { "islt": true } },
      { "$project": { "islt": 0 } }
    ])
    // .allowDiskUse(true);
  } else {
    aggregate = Tutor.aggregate([
      {
        $match: match
      }
    ]);
  }

  Tutor
    .aggregatePaginate(aggregate, options, function (err, result, pageCount, count) {

      if (err) {
        console.log(err)
        return res.status(400).send(err);
      }
      else {

        var opts = [
          { path: 'levels', select: 'name' },
          { path: 'subjects', select: 'name' },
          { path: 'assos', select: 'name' }
        ];
        Tutor
          .populate(result, opts)
          .then(result2 => {
            return res.send({
              page: page,
              perPage: perPage,
              pageCount: pageCount,
              documentCount: count,
              tutors: result2
            });
          })
          .catch(err => {
            return res.status(400).send(err);
          });
      }
    })
};

The query is supposed to retrieve all the tutors in a given range (which is a field from the tutor model, an integer in km, indicating how far the tutor is willing to move) around a certain location. (lat1, lon1).
The issue is that all the documents are not returned. After many tests, I have noticed that only tutors that are less than approximatively 7.5km away from the location are returned and not the others. Even if the tutor is 10km away and has a range of 15km, he won't be returned as he is farer than 7.5km.
I have tried switching location between two tutors (one that is returned and one that is not but should be) to see if this is the only thing causing the issue and it is. After I switched their location (lng and loc), the one that was returned before is no longer and vice versa.
I really don't get why this is happening.
Also, I know the result size is less than 16MB since I don't get all the results, even with allowDiskUse:true.
If you have any other idea about why I'm not getting all the results, don't hesitate !
Thank you !
PS : this is a part of the tutor model with the concerned fields (loc):
import mongoose from 'mongoose';
import validate from 'mongoose-validator';
import { User } from './user';
import mongooseAggregatePaginate from 'mongoose-aggregate-paginate';

var ObjectId = mongoose.Schema.Types.ObjectId;

var rangeValidator = [
    validate({
        validator: (v) => {
            v.isInteger && v >= 0 && v <= 100;
        },
        message: '{VALUE} is a wrong value for range'
    })
];

var tutorSchema = mongoose.Schema({
    fullName: {
        type: String,
        trim: true,
        minlength: [1, 'Full name can not be empty'],
        required: [true, 'Full name is required']
    },
    location: {
        address_components: [
            {
                long_name: String,
                short_name: String,
                types: String
            }
        ],
        description: String,
        lat: Number,
        lng: Number

    },
    loc: {
        type: { type: String },
        coordinates: []
    },

});

tutorSchema.plugin(mongooseAggregatePaginate);
tutorSchema.index({ "loc": "2dsphere" });
var Tutor = User.discriminator('Tutor', tutorSchema);

module.exports = {
    Tutor
};

The user model is using two indexes. The ID and this one ;
db['system.indexes'].find() Raw Output
{
  "v": 2,
  "key": {
    "loc": "2dsphere"
  },
  "name": "loc_2dsphere",
  "background": true,
  "2dsphereIndexVersion": 3,
  "ns": "verygoodprof.users"
}

A:

I also have some similar kind of problem, in my case there is problem with limit
https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/
by default limit is 100 (Optional. The maximum number of documents to return. The default value is 100).
If you want you can increase the limit. Hope it help


Q:

Orika: Map from String to a List of SomeObjects

Consider the following situation:
public class A {
    private String stringA;

    public String getStringA() {
        return stringA;
    }

    public void setStringA(String stringA) {
        this.stringA = stringA;
    }

}

public class B {

    List<SomeObject> someObjects;

    public List<SomeObject> getSomeObjects() {
        if (someObjects == null) {
            someObjects = new ArrayList<SomeObject>();
        }
        return someObjects;
    }

}

public class SomeObject {
    private String stringSomeObject;

    public String getStringSomeObject() {
        return stringSomeObject;
    }

    public void setStringSomeObject(String stringSomeObject) {
        this.stringSomeObject = stringSomeObject;
    }

}

I want to map from A to B. Whilst mapping these, stringA needs to be  mapped to stringSomeObject in SomeObject. I tried to write a Orika-Mapper for this:
public class MyMapper extends ConfigurableMapper {

    @Override
    protected void configure(MapperFactory factory) {
        ConverterFactory converterFactory = factory.getConverterFactory();
        converterFactory.registerConverter(new StringToSomeObjectConverter());

        factory.classMap(A.class, B.class) //
                .field("stringA", "someObjects") //
                .byDefault() //
                .register();
    }

}

It maps class A to B and whenever it encounters a conversion from String to List<SomeObject> it calls a custom-converter:
public class StringToSomeObjectConverter extends CustomConverter<String, List<SomeObject>> {

    private static final String BORROWER_PARTY_TYP_CODE = "147";

    @Override
    public List<SomeObject> convert(String source, Type<? extends List<SomeObject>> destinationType) {
        SomeObject someObject = new SomeObject();
        someObject.setStringSomeObject(source);
        return Arrays.asList(someObject);
    }

}

I wrote an unit-test to ensure that this works:
@Test
public void testMap() throws Exception {
    A a = new A();
    a.setStringA("a");

    B outcome = new MyMapper().map(a, B.class);

    assertThat(outcome.getSomeObjects.size(), is(1));
}

Sadly this test fails with:
java.lang.AssertionError:
Expected: is <1>
   but: was <0>

It seems like the Converter is never executed so I tried to debug it. And indeed: The debugger never reaches the converter. Am I doing something wrong? It seems like. I know there are more methods which one could go with like: mapAToB e.g...
Ok I found a solut...nah! It's not a solution, it's just a workaround. I defined the stringA as List<String> as well and defined a converter extending CustomConverter<String, LoanContrReqERPCrteReqLoanContrBrrwrPty>.
Because this feels a little "hacky", I am still interested in a nice solution. (Though I am just thinking that this solution might be fine: Now the datastructure of both objects is more equal than before. The problem is, that object B is coming from an external service, I can't modify it.)

A:

You mapping doesn't work because you don't have setter for someObjects.
When Orika tries to generate code for mapper, it checks all fieldMaps in classMap for sourceProperty is readable and destinationProperty is assignable. If this checks passed, generator puts field conversion into generated mapper. If check failed, Orika just skip this field conversion.
Few options you can use to solve a problem:

You can add setter for someObjects field in class B:
public static class B {

    List<SomeObject> someObjects;

    public List<SomeObject> getSomeObjects() {
        if (someObjects == null) {
            someObjects = new ArrayList<SomeObject>();
        }
        return someObjects;
    }

    public void setSomeObjects(List<SomeObject> someObjects) {
        this.someObjects = someObjects;
    }
}

Use custom mapper instead of converter:
    factory.classMap(A.class, B.class)
            .customize(
                    new CustomMapper<A, B>() {
                        @Override
                        public void mapAtoB(A a, B b, MappingContext context) {
                            SomeObject someObject = new SomeObject();
                            someObject.setStringSomeObject(a.getStringA());
                            b.getSomeObjects().add(someObject);
                        }
                    }
            )
            .byDefault()
            .register();

Orika will put invocation customMapper after resolving of field maps.
Generated mapper will looks like:
    b.setOtherField(a.getOtherField());
    if (customMapper != null) {
        customMapper.map(source, destination); <-- Your mapper invocation
    }

Use follow syntax for fields:
    factory.classMap(A.class, B.class)
            .field("stringA", "someObjects[0].stringSomeObject")
            .byDefault()
            .register();

Generated mapper will looks like:
    if (source.getStringA() != null) {
        if (((((java.util.List) destination.getSomeObjects()).size() <= 0 || ((List) destination.getSomeObjects()).get(0) == null))) {
            ((java.util.List) destination.getSomeObjects()).add(0, ((BoundMapperFacade) usedMapperFacades[0]).newObject(((String) source.getStringA()), mappingContext));
        }
    }

    if (!(((java.lang.String) source.getStringA()) == null)) {
        (((java.util.List) destination.getSomeObjects()).get(0)).setStringSomeObject(source.getStringA());
    } else if (!(((java.util.List) destination.getSomeObjects()) == null) && !((((java.util.List) destination.getSomeObjects()).size() <= 0 || ((List) destination.getSomeObjects()).get(0) == null))) {
        ( ((java.util.List) destination.getSomeObjects()).get(0)).setStringSomeObject(null);
    }

Also there was a bug in Orika to map from single property to property of collection using syntax .field("stringA", "elements{stringB}") ( Incorrect mapper code generated for mapping from a single property to property of collection element). Bug closed at 31 Dec 2016 here: Fix for bug


Q:

Can't convert memory address to value

thanks for visiting my question! Currently, when I run this code (an implementation of the Set data structure in c++), the memory address of each element in the set is printed instead of the values in the set. To help with debugging, here's my code:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cassert>

#define PB push_back
typedef std::vector<int> vint;

class SetBase
{
public:
  SetBase() {}
  ~SetBase() {}

  void insert(int x)
  {
    if (!this->isInSet(x))
    {
      this->set.PB(x);
    }
  }

  int size()
  {
    return this->set.size();
  }

  bool empty()
  {
    return this->size() == 0;
  }

  int operator[](int index)
  {
    if (index >= 0 && index < this->size())
    {
      return this->set[index];
    }
    else
    {
      return -1;
    }
  }

  bool find(int target)
  {
    sort(this->set.begin(), this->set.end());

    int low = 0, high = this->size();

    while (low <= high)
    {
      long long mid = low + (high - low) / 2;
      long long guess = this->set[mid];

      if (guess == target)
        return true;
      else if (guess < target)
        low = mid + 1;
      else
        high = mid - 1;
    }

    return false;
  }

  int count(int target)
  {
    int counter = 0;

    for (int i = 0; i < this->set.size(); i++)
    {
      if (this->set[i] == target)
        counter++;
    }

    return counter;
  }

  bool operator=(SetBase &other)
  {
    if (other.size() != this->size())
      return false;

    for (int i = 0; i < other.size(); i++)
    {
      if (other[i] != this->set[i])
        return false;
    }

    return true;
  }

private:
  vint set;

  bool isInSet(int target)
  {
    for (int i = 0; i < this->size(); i++)
    {
      if (set[i] == target)
      {
        return true;
      }
    }

    return false;
  }
};

class Set : public SetBase
{
public:
  void set_union(Set *set1, Set *set2, Set &back_insertor)
  {
    for (int i = 0; i < set1->size(); i++)
    {
      if (this->isInSet(back_insertor, i))
      {
        back_insertor.insert(i);
      }
    }
  }

  void set_difference(Set set1, Set set2, Set &back_insertor)
  {
    // set_difference = set1 - set2
  }

  void set_intersection(Set set1, Set set2, Set &back_insertor)
  {
    // set_difference = set1 U set2
    for (int i = 0; i < set1.size(); i++)
    {
      for (int j = 0; j < set2.size(); j++)
      {
        if (set1[i] == set2[j])
        {
          back_insertor.insert(set1[i]);
        }
      }
    }
  }

  void printSet(Set *in)
  {
    for (int i = 0; i < in->size(); i++)
    {
      std::cout << &in[i] << "\n";
    }
  }

private:
  bool isInSet(SetBase set1, int target)
  {
    for (int i = 0; i < set1.size(); i++)
    {
      if (target == set1[i])
      {
        return true;
      }
    }

    return false;
  }
};

int main()
{
  Set *set_1 = new Set();
  Set *set_2 = new Set();
  Set *back = new Set();

  for (int i = 1; i <= 10; i++)
    set_1->insert(i);

  for (int i = 1; i <= 10; i++)
    set_2->insert(i);

  set_2->insert(11);

  set_1->set_union(set_1, set_2, *back);
  set_1->printSet(set_1);

  delete set_1;
  delete set_2;
  delete back;
}

When running the set_1->printSet(set_1); line, here's what I get:
0x7fb498c05a20
0x7fb498c05a38
0x7fb498c05a50
0x7fb498c05a68
0x7fb498c05a80
0x7fb498c05a98
0x7fb498c05ab0
0x7fb498c05ac8
0x7fb498c05ae0
0x7fb498c05af8

Even though this works, I would like to print out the values (integer) instead. Any help would be appreciated! Thanks! :)

A:

Inside printSet(), you use &in[i] to print each element.
The & operator returns the address of the object you are referencing. So, instead of getting the value, you are getting its address.  You should remove it, eg:
void printSet(Set *in)
{
    for (int i = 0; i < in->size(); i++)
    {
        std::cout << (*in)[i] << "\n";
    }
}


Q:

mvc - show/hide stuff based on what view it is for a user control

Im using asp.net mvc. I have a create and edit form which are very similar so im using a user control for the form.
and placing that in each view.
the form is very slightly different on the edit form eg it has some extra text and a link.
how can i show/hide that based on the view im in?

A:

I would either put it in the model (i.e. an "IsEditMode" or "IsAddMode" parameter) or, better yet, pass it in via the ViewData:
<%
ViewData["IsEditMode"] = true;
Html.RenderPartial("FormView", Model);
%>

Then just check for the IsEditMode value in the ViewData


Q:

with Ansible and apt, how do I update bash to for the remotely exploitable security vulnerability CVE-2014-6271?

Given bash's remote code execution vulnerability announced on Sept 24 2014, how can I update my apt-based systems using Ansible?

A:

Here's my preferred solution in a fairly homogenous environment. The advantage of this is the update won't take a lot of time in the future, unlike the version=latest pattern others are using.
- name: update apt cache if not done today
  apt: update_cache=yes cache_valid_time=86400

# http://seclists.org/oss-sec/2014/q3/650
- name: ensure secure ansible, ubuntu 1204 edition
  apt: pkg=bash=4.2-2ubuntu2.5 state=present
  when: ansible_distribution=='Ubuntu' and ansible_distribution_version=='12.04'

- name: ensure secure ansible, ubuntu 1404 edition
  apt: pkg=bash=4.3-7ubuntu1.3 state=present
  when: ansible_distribution=='Ubuntu' and ansible_distribution_version=='14.04'

# based on the following gist and comments below. there have been several exploits, this covers them well.
# https://gist.github.com/kacy/2b9408af04c71fab686e
- name: ensure bash is not vulnerable to 201409 problem
  shell: "foo='() { echo not patched; }' bash -c foo"
  register: command_result
  ignore_errors: yes
  failed_when: "'command not found' not in command_result.stderr"

Explanation: updating the apt-cache is expensive if done many times per day. The cache time can be adjusted. The code actually tests to make sure the vulnerability is fixed- tests are good. This will highlight any hosts that aren't covered by the distributions/versions coded.
SO user @jarv posted a great solution too. Instead of always updating apt, it only does so if the problem hasn't been fixed. This is the fastest solution possible (in this answer, at least). jarv has also added a distribution test in the linked repo, useful for heterogeneous environments.
- name: Check if we are vulnerable
  shell: executable=/bin/bash env x='() { :;}; echo vulnerable'  bash -c "echo this is a test"
  register: test_vuln

- name: Apply bash security update if we are vulnerable
  apt: name=bash state=latest update_cache=true
  when: "'vulnerable' in test_vuln.stdout"

- name: Check again and fail if we are still vulnerable
  shell: executable=/bin/bash env x='() { :;}; echo vulnerable'  bash -c "echo this is a test"
  when: "'vulnerable' in test_vuln.stdout"
  register: test_vuln
  failed_when: "'vulnerable' in test_vuln.stdout"

There are other ways. Michael DeHaan, creator of Ansible, and the official @ansible account tweeted a few solutions:
Here's a one-liner:
ansible all -m apt -a 'update_cache=yes name=bash state=latest'

Here's a update-and-check solution:
- name: update apt
  command: apt-get update

- name: update bash
  command: apt-get --only-upgrade install bash

- name: check bash fix
  command: env x='() { :;}; echo vulnerable' bash -c "echo this is a test"
  register: command_result
  failed_when: "'error' not in command_result.stderr"


Q:

Can pip (python2) and pip3 (python3) coexist?

I always thought that pip was for Python 2 and pip3 was for Python 3.  To install the different versions of pip I have done the following:
sudo apt-get install python-pip
sudo apt-get install python3-pip

then I get the following as one would expect:
$ pip --version
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
$ pip3 --version
pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)

Those are old versions, though, so I do the following:
$ sudo pip install pip --upgrade

and I get this:
$ pip --version
pip 19.0.3 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7)
$ pip3 --version
pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)

and when I do a pip3 install for some package, I get the following message:
You are using pip version 8.1.1, however version 19.0.3 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

Well, I already ran that, so I try this:
$ sudo pip3 install pip --upgrade
Installing collected packages: pip
  Found existing installation: pip 8.1.1
    Not uninstalling pip at /usr/lib/python3/dist-packages, outside environment /usr
Successfully installed pip-19.0.3

But now I get this:
$ pip --version
pip 19.0.3 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)
$ pip3 --version
pip 19.0.3 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)

Is that correct?  Does this matter?  Does a pip version from Python 3.5 work for installing Python 2 packages?
UPDATE
Based on the answer provided by @furas, these are all the commands I run to get updated versions of pip and pip3 installed correctly:
sudo apt-get install python-pip --yes
sudo apt-get install python3-pip --yes
sudo python3 -m pip install pip --upgrade
sudo python -m pip install pip --upgrade --force # this line fixes the pip install to point to the python2 version instead of the python3 version

and that yields the following:
$ pip --version
pip 19.0.3 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7)
$ pip3 --version
pip 19.0.3 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)

A:

Every Python should have own pip because every Python may use different version of the same module and every Python installs modules in different folder.
You can use Python2 to install pip for Python2 and it should create correct file pip
python -m pip install -U --force pip

You should also have pip, pip2, pip2.7, pip3, pip3.5. You can even have pip3.6, pip3.7 at the same time.
Write in console pip and press tab and it should shows you all programs which starts with pip
You can find full path for pip with
which pip

and see it is python's script.
Different pip has different first line #!/usr/bin/python or #!/usr/bin/python3.5. Rest code should be the same for all versions.


Q:

Pass by value faster than pass by reference

I made a simple program in c++ to compare performance between two approaches - pass by value and pass by reference. Actually pass by value performed better than pass by reference.
The conclusion should be that passing by value require fewer clock-cycles (instructions)
I would be really glad if someone could explain in detail why pass by value require fewer clock-cycles.
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

void function(int *ptr);
void function2(int val);

int main() {

   int nmbr = 5;

   clock_t start, stop;
   start = clock();
   for (long i = 0; i < 1000000000; i++) {
       function(&nmbr);
       //function2(nmbr);
   }
   stop = clock();

   cout << "time: " << stop - start;

   return 0;
}

/**
* pass by reference
*/
void function(int *ptr) {
    *ptr *= 5;
}

/**
* pass by value
*/
void function2(int val) {
   val *= 5;
}

A:

A good way to find out why there are any differences is to check the disassembly. Here are the results I got on my machine with Visual Studio 2012.
With optimization flags, both functions generate the same code:
009D1270 57                   push        edi
009D1271 FF 15 D4 30 9D 00    call        dword ptr ds:[9D30D4h]
009D1277 8B F8                mov         edi,eax
009D1279 FF 15 D4 30 9D 00    call        dword ptr ds:[9D30D4h]
009D127F 8B 0D 48 30 9D 00    mov         ecx,dword ptr ds:[9D3048h]
009D1285 2B C7                sub         eax,edi
009D1287 50                   push        eax
009D1288 E8 A3 04 00 00       call        std::operator<<<std::char_traits<char> > (09D1730h)
009D128D 8B C8                mov         ecx,eax
009D128F FF 15 2C 30 9D 00    call        dword ptr ds:[9D302Ch]
009D1295 33 C0                xor         eax,eax
009D1297 5F                   pop         edi
009D1298 C3                   ret

This is basically equivalent to:
int main ()
{
    clock_t start, stop ;
    start = clock () ;
    stop = clock () ;
    cout << "time: " << stop - start ;
    return 0 ;
}

Without optimization flags, you will probably get different results.
function (no optimizations):
00114890 55                   push        ebp
00114891 8B EC                mov         ebp,esp
00114893 81 EC C0 00 00 00    sub         esp,0C0h
00114899 53                   push        ebx
0011489A 56                   push        esi
0011489B 57                   push        edi
0011489C 8D BD 40 FF FF FF    lea         edi,[ebp-0C0h]
001148A2 B9 30 00 00 00       mov         ecx,30h
001148A7 B8 CC CC CC CC       mov         eax,0CCCCCCCCh
001148AC F3 AB                rep stos    dword ptr es:[edi]
001148AE 8B 45 08             mov         eax,dword ptr [ptr]
001148B1 8B 08                mov         ecx,dword ptr [eax]
001148B3 6B C9 05             imul        ecx,ecx,5
001148B6 8B 55 08             mov         edx,dword ptr [ptr]
001148B9 89 0A                mov         dword ptr [edx],ecx
001148BB 5F                   pop         edi
001148BC 5E                   pop         esi
001148BD 5B                   pop         ebx
001148BE 8B E5                mov         esp,ebp
001148C0 5D                   pop         ebp
001148C1 C3                   ret

function2 (no optimizations)
00FF4850 55                   push        ebp
00FF4851 8B EC                mov         ebp,esp
00FF4853 81 EC C0 00 00 00    sub         esp,0C0h
00FF4859 53                   push        ebx
00FF485A 56                   push        esi
00FF485B 57                   push        edi
00FF485C 8D BD 40 FF FF FF    lea         edi,[ebp-0C0h]
00FF4862 B9 30 00 00 00       mov         ecx,30h
00FF4867 B8 CC CC CC CC       mov         eax,0CCCCCCCCh
00FF486C F3 AB                rep stos    dword ptr es:[edi]
00FF486E 8B 45 08             mov         eax,dword ptr [val]
00FF4871 6B C0 05             imul        eax,eax,5
00FF4874 89 45 08             mov         dword ptr [val],eax
00FF4877 5F                   pop         edi
00FF4878 5E                   pop         esi
00FF4879 5B                   pop         ebx
00FF487A 8B E5                mov         esp,ebp
00FF487C 5D                   pop         ebp
00FF487D C3                   ret

Why is pass by value faster (in the no optimization case)?
Well, function() has two extra mov operations. Let's take a look at the first extra mov operation:
001148AE 8B 45 08             mov         eax,dword ptr [ptr]
001148B1 8B 08                mov         ecx,dword ptr [eax]
001148B3 6B C9 05             imul        ecx,ecx,5

Here we are dereferencing the pointer. In function2 (), we already have the value, so we avoid this step. We first move the address of the pointer into register eax. Then we move the value of the pointer into register ecx. Finally, we multiply the value by five.
Let's look at the second extra mov operation:
001148B3 6B C9 05             imul        ecx,ecx,5
001148B6 8B 55 08             mov         edx,dword ptr [ptr]
001148B9 89 0A                mov         dword ptr [edx],ecx

Now we are moving backwards. We have just finished multiplying the value by 5, and we need to place the value back into the memory address.
Because function2 () does not have to deal with referencing and dereferencing a pointer, it gets to skip these two extra mov operations.

A:

Overhead with passing by reference:

each access needs a dereference, i.e., there is one more memory read

Overhead with passing by value:

the value needs to be copied on stack or into registers

For small objects, such as an integer, passing by value will be faster. For bigger objects (for example a large structure), the copying would create too much overhead so passing by reference will be faster.

A:

Imagine you walk into a function and you're supposed to come in with an int value. The code in the function wants to do stuff with that int value.
Pass by value is like walking into the function and when someone asks for the int foo value, you just give it to them.
Pass by reference is walking into the function with the address of the int foo value. Now whenever someone needs the value of foo they have to go and look it up. Everyone's gonna complain about having to dereference foo all the freaking time. I've been in this function for 2 milliseconds now and I must have looked up foo a thousand times! Why didn't you just give me the value in the first place? Why didn't you pass by value?
This analogy helped me see why passing by value is often the fastest choice.


Q:

Handling multiple forms in React

I'm trying to make two simple forms with a Save button to work in React, but it appears that the Save button component is unable to see the two forms.

My Form component is as follows:
import React from "react";
import { Field, reduxForm } from "redux-form";

const validate = values => {
  const errors = {};
  if (!values.name) {
    errors.name = "Required";
  }

  if (!values.age) {
    errors.age = "Required";
  }

  return errors;
};

const renderField = ({
  input,
  label,
  type,
  value,
  meta: { touched, error, warning }
}) => (

    {label}

      <input {...input} placeholder={label} type={type} />
      {touched && (error && {error})}

);

const Form1 = props => {
  const { handleSubmit } = props;
  return (

      <form onSubmit={handleSubmit}>
        <Field name="name" component={renderField} type="text" label="Name" />
        <Field name="age" component={renderField} type="text" label="Age" />
        <button type="submit">Submit</button>
      </form>

  );
};

export default reduxForm({
  form: "step1", // a unique identifier for this form
  validate
})(Form1);

And my SaveButton is as follows:
import React, { Component } from "react";

export default class SaveButton extends Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.submit = this.submit.bind(this);
  }

  submit() {
    console.log(this.props);
    const { dispatch, forms } = this.props;

    forms.forEach(({ formName, isValid, values, errors }) => {
      if (isValid) {
        console.log(values);
      } else {
        //        dispatch(touch(formName, ...Object.keys(errors)));
      }
    });
  }

  render() {
    return (
      <button type="button" onClick={this.submit}>
        Save
      </button>
    );
  }
}

Sandbox example

Clicking Save gives Cannot read property 'forEach' of undefined because forms is undefined and this.props is empty. Anyone know why the forms can't be seen from SaveButton?

A:

This is because your Save button is not the part of the form element. So to get the value you have to do it manually. Here is how I do it,
I will pass a handleSave function as a prop from App.js like,
import React, { Component } from "react";
import "./App.css";
import Form1 from "./components/form1/Form";
import Form2 from "./components/form2/Form";
import SaveButton from "./components/SaveButton";
import { connect } from "react-redux";
import {
  submit,
  isValid,
  getFormNames,
  getFormValues,
  getFormSyncErrors,
  touch
} from "redux-form";

class App extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (

Welcome to React

          Form 1:
          <Form1 onSubmit={this.step1} />

          Form : 2
          <Form2 onSubmit={this.step2} />

          <SaveButton handleSave={this.handleSave} />

    );
  }

  step1(values) {
    console.log(values);
  }

  step2(values) {
    console.log(values);
  }
  handleSave = () => {
    const { dispatch, forms } = this.props;
    console.log(forms);

     forms.forEach(({ formName, isValid, values, errors }) => {
       if (isValid) {
         console.log(values);
       } else {
         //        dispatch(touch(formName, ...Object.keys(errors)));
       }
     });
  }
}

const mapStateToProps = state => {
  return {
    forms: getFormNames()(state).map(formName => ({
      formName,
      isValid: isValid(formName)(state),
      values: getFormValues(formName)(state),
      errors: getFormSyncErrors(formName)(state)
    }))
  };
};

export default connect(mapStateToProps)(App);`

and in SaveButton.js, I will simply call that function,
import React, { Component } from "react";

export default class SaveButton extends Component {
  constructor(props) {
    super(props);
    this.props = props;
  }

  submit = () => {
    this.props.handleSave();
  };

  render() {
    return (
      <button type="button" onClick={this.submit}>
        Save
      </button>
    );
  }
}


Q:

Moving function outside a loop

I have read the solution on the following page but still don't understand how to apply it to my loop and function. How do I move the following function outside the loop?
How to move functions outside a loop
var i;
    var chap = '.nav__chapter-';
        for (i = 0; i < 7; i++) {
        var precedingZero = (i<10) ? '0' : '';
            (function(i) {
                $( chap + precedingZero + i ).addClass('toggleAria');
            })(i);
        }

I have a few like this so once I understand it I can apply to all. Sorry for being so dense.

A:

You don't need your IIFE (immediately invoked function expression) in the loop at all.  You can change to just this:
var chap = '.nav__chapter-', precedingZero;
for (var i = 0; i < 7; i++) {
    precedingZero = (i < 10) ? '0' : '';
    $(chap + precedingZero + i).addClass('toggleAria');
}

An IIFE might be used inside a loop if you have async operations and you need to "save" a loop value for later use in an async callback.  But, that is not happening at all here so the IIFE is simply not needed.


Q:

SMS Receiver as a Service

I have created SMS Receiver app... but i want to create it as an service, it should run in the background (i.e no separate UI for this app, want to work like alarm app) and even if mobile restarts it automatically starts... could any one help on this?
My previous SMS Receiver app code was here
Unable to instantiate activity ComponentInfo in Android Receive Sms App

A:

it should run in the background

Your existing BroadcastReceiver for the (undocumented) android.provider.Telephony.SMS_RECEIVED already runs in the background.

and even if mobile restarts it automatically starts

Your existing BroadcastReceiver for the (undocumented) android.provider.Telephony.SMS_RECEIVED already is available after the device reboots.


Q:

How to orchestrate a clustered Quartz job

Say I have a BackendApp that deploys as a WAR and is deployed to multiple nodes. I deploy it to multiple nodes for high availability. The app uses Quartz to schedule certain jobs being kicked off. Let's say one of these jobs should only be ran once a day.
If I have the app deployed to 5 nodes, it will get ran 5 times a day, once on each node.
Do any mechanisms exist to orchestrate certain jobs things that should only run once in a distributed/clustered environment, and not by each app instance in the cluster?
I did find this article but it seems to be a solution that is limited to one node:

Never run clustering on separate machines, unless their clocks are synchronized using some form of time-sync service...

A:

You can use a JDBC store and set clustered to true, make sure all the nodes are on the same database and make sure all the machine have a time-sync service.
http://quartz-scheduler.org/documentation/quartz-2.x/configuration/ConfigJobStoreTX


Q:

Access Text Value lightning:inputField lookup

Is there a way to access the text value of a lightning:inputField of lookup type? .get('v.value') returns the ID but I also want to retrieve the text value displayed within the lookup as well.

A:

After much experimentation, I gave up. Instead I added in some logic to retrieve the Name value from the Database based on the ID instead of continuing to spin my wheels. Hopefully in the future there will be some more attributes accessible to developers.


Q:

gradle - multiple module project - ant wrong execution dir

I've a multiple module projecy managed by gradle. The directory structure is as follows:

monitoring

client
server

When I invoke 'gradle war' on monitoring level I obtain the following exeception:
"monitoring/js does not exist."
Which comes from client's build.gradle:
task copyJs << {

     'mkdir src/main/webapp/js'.execute()

     def ant = new groovy.util.AntBuilder()
     ant.copy(todir: 'src/main/webapp/js') {
          fileset(dir: 'js') {
               include(name: '**/*.js')
          }
     }
}

The exception occurs because the mentioned task is executed on the root level of the project. How to change it to be executed on the appropriate (client) level? How to change the basedir for the ant task that is used?

A:

Should be done as explained here
task copyJs << {

    file('src/main/webapp/js').mkdir()

    copy {
        into 'src/main/webapp/js'
        from('js') {
            include '**/*.js'
        }
    }
}


Q:

UIView animation completion block not called

When I first call following code from dispatch queue, completion block not called.
- (void)viewDidLoad
{
    [super viewDidLoad];
    dispatch_queue_t initialize_queue;
    initialize_queue = dispatch_queue_create("init", NULL);
    dispatch_async(initialize_queue, ^{
        _onInit = YES;
        _isRunning = NO;
        [self startProgress];
        _onInit = NO;
    });
}

 - (void)startProgress
 {
  if (!_isRunning) {
    _isRunning = YES;
    NSLog(@"Starting");
    [UIView animateWithDuration:0.5 animations:^{
        self.progressStatusButton.hidden = NO;
        self.activityLeftConstraint.constant = _activityLeftSpace;
        self.activityWidthConstraint.constant = _activityWidth;
        self.buttonWidthConstraint.constant = _progressStatusButtonWidth;
        self.buttonLeftConstraint.constant = _progressStatusButtonLeftSpace;
        self.activityView.alpha = 1.0;
    }completion:^(BOOL finished){
        NSLog(@"Start Animating");
        [self.activityView startAnimating];
    }];
  }
 }

When I delete dispatch_aync method and execute startProgress method in viewDidLoad,
completion block called. How should I correct my code?
I tried to change dispatch_async to use dispatch_async(dispatch_get_main_queue(),..),
then completion block called, but I would like to execute asynchronously startProgress method.
Please Let me know.

A:

Everything connected with GUI should be called from main thread/ pushed to main queue. In other case expected behavior is not guaranteed.
So you should use
dispatch_get_main_queue()

Also animation ALWAYS executed asynchronously so I do not think you really need separate queue for it.


Q:

Where to put hibernate annotations?

Where do i put my hibernate annotations?
Is it the line above my instance variable? Or before the getter? Or before the setter? Or doesn't it really matter?
Thanks a lot

A:

You place them either on the field or on the getter. From the Hibernate Annotations Reference Guide:

2.2.1. Marking a POJO as persistent entity
(...)
Depending on whether you annotate
  fields or methods, the access type
  used by Hibernate will be field or
  property. The EJB3 spec requires that
  you declare annotations on the element
  type that will be accessed, i.e. the
  getter method if you use property
  access, the field if you use field
  access. Mixing annotations in both
  fields and methods should be avoided.
  Hibernate will guess the access type
  from the position of @Id or
  @EmbeddedId.

You might also want to read about the @Access annotation that allows to force/override the access type (prior to Hibernate Annotations 3.5 and JPA 2.0, it was part of Hibernate Annotation Extensions):

2.2.2.2. Access type
By default the access type of a class
  hierarchy is defined by the position
  of the @Id or @EmbeddedId annotations.
  If these annotations are on a field,
  then only fields are considered for
  persistence and the state is accessed
  via the field. If there annotations
  are on a getter, then only the getters
  are considered for persistence and the
  state is accessed via the
  getter/setter. That works well in
  practice and is the recommended
  approach.

Note
The placement of annotations within a class hierarchy has to be consistent
    (either field or on property) to be
    able to determine the default access
    type. It is recommended to stick to
    one single annotation placement
    strategy throughout your whole
    application.

However in some situations, you need
  to:

force the access type of the entity hierarchy
override the access type of a specific entity in the class hierarchy
override the access type of an embeddable type

The best use case is an embeddable
  class used by several entities that
  might not use the same access type. In
  this case it is better to force the
  access type at the embeddable class
  level.
(...)

Regarding the pros and cons of both styles, I suggest to read the following questions:

Hibernate/JPA - annotating bean methods vs fields
Hibernate Annotations - Which is better, field or property access?
Performance difference between annotating fields or getter methods in Hibernate / JPA


Q:

ZF2 User group specific layouts

I have a project with 3 different Layouts. 1 Layout for the Login page, 1 Layout for the administrators and editors and a 3rd Layout for general users where also the administrators have access to (its a layout for 3 different pages where you can fill out surveys which is possible for the 3 mentioned user groups).
At the moment I am using EdpModuleLayouts for this purpose, which did fine until now. Because now I need to adapt the 3rd layout depending on which usergroup accesses it.
Do you have any idea how to get this done?
Thanks in advance.

A:

you can listen you to the zf2 mvc events and change your layout based on your criterias.
this is an example how your application Module.php can look like.
public function onBootstrap(MvcEvent $e)
{
    $application =  $e->getApplication();
    $serviceManager = $application->getServiceManager();
    $eventManager = $application->getEventManager();
    $sharedManager = $eventManager->getSharedManager();

    // DISPATCH EVENT
    $sharedManager->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function( MvcEvent $e) use ($serviceManager) {

        // get your instance to locate current user group or something else
        $auth = $serviceManager->get('Some/Auth/Service');
        $userGroup = $auth->getUserGroupFromCurrentUser();

        $controller      = $e->getTarget();

        if( $userGroup == 'someGroup' )
        {
            $controller->layout('layout/somelayoutname');
        } else {
            $controller->layout('layout/someotherlayoutname');
        }
    }, 50 );
}


Q:

python: how can i create a list of integers,to a number?

I receive an input int that I don't previously know. How can I create a new list of integer from 0 to that int? An easy way please. Thank you in advance.
I mean that:
k = n
...
list = [0, ... , k]

A:

numbers = list(range(k+1))   # For Python 2, it is just range(k+1).

Given an integer k, which you can get with input.
The range creates an iterator (in Python 3) with those numbers (k+1 because it is not inclusive, but you need it to be), then we make it into a list.

Demo:
>>> k = int(input())
16
>>> numbers = list(range(k+1))
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]


Q:

How safe is a PGP private key that has “escaped”, but without its password?

Assuming your PGP private key is protected with a password, and it "escapes", but the password does not, how worried should you be?
Obviously in the real world, you would immediately revoke the key and generate a new one. But on a theoretical level, does having a private key, but not its associated password, get you any closer to decrypting messages encrypted with it?

A:

The point of a password is to prevent the key from immediately being compromised once it leaks.  It should be considered partially compromised though as the security is reduced from the keysize down to the password complexity.  If you have a high complexity password, it may still be an acceptable level of security for your needs, but generally it is advisable to work on replacing the key since security is reduced.
The urgency of the transition depends on your password though.  If your password was "password" then you should immediately stop using it and transition, but if it was something reasonably complex, then you should be able to keep using it for a bit and distribute your new public key to your contacts using it.  Don't use it for anything you need long term privacy on, but it should be fine for communicating out your new credentials with confidence that you still control the private key for the reasonable future.

A:

It's not that hard to brute force the password once you have the key, unless the password is very long.
So having the enrypted key does get the attacker closer to getting the real key. However, make your password 20 characters long (and don't use dictionary words), and  you ought to be fine as such long passwords will take a long time to bruteforce.


Q:

Is there excessive lubricant on my new rear derailleur?

I just received a new Shimano Deore rear derailleur, which has large gobs of lubricant in two locations (one clearly visible in photo). This seems excessive.
Do I leave it, or are they expecting you to wipe the excess away before installing?

A:

All of that goo is very typical of drivetrain components that are fresh from the factory. The factory uses a particularly thick lubricant to protect the parts until they're purchased or installed (lest they sit on a shelf and risk being exposed to moisture).
Basically, the factory is expecting whoever installs said drivetrain components to identify any excessive grease (some of it is there for good cause, such as protecting the inner spring from the elements), wipe it down, and re-lubricate with something lighter!

A:

I'd wipe it off a bit--it won't serve any purpose as it is, apart from collecting dirt.


Q:

After upgrade to kernel 3.16.0-30-generic I cannot use the keyboard

After installation of 14.10 and the "automatic upgrade" of the kernel to 3.16.0-30-generic from 3.16.0-23-generic I cannot use my keyboard to enter my passphrase for decrypting my physical drive.

Any keyboard input is displayed at the first row of the
  'ubuntu-decrypt-drive' phase/page/graphical picture.

Actually, keyboard input isn't working at all, except the possibility to use ALT+Fn combination takes me to an empty blinkning marker without any input-possibilites.
If I try switching with the Alt+Fx combination I just get a blinking marker at the first row and the first column, and the same result there:
It takes keyboard input but I'm definitely not using the input to surpass my encrypted physical device.
When comparing the configuration files (config-kernel-generic) I cannot see anything that could cause this incident (side note: I'm not the best of both worlds regards to troubleshooting issues like this):
(sorry about the text-blob):
> diff config-3.16.0-30-generic config-3.16.0-23-generic

**3c3
< # Linux/x86_64 3.16.0-30-generic Kernel Configuration
---
> # Linux/x86_64 3.16.0-23-generic Kernel Configuration
68c68
< CONFIG_VERSION_SIGNATURE="Ubuntu 3.16.0-30.40-generic 3.16.7-ckt3"
---
> CONFIG_VERSION_SIGNATURE="Ubuntu 3.16.0-23.31-generic 3.16.4"
1934d1933
< CONFIG_GENWQE_PLATFORM_ERROR_RECOVERY=0
5049c5048
< # CONFIG_SOUND_OSS_CORE_PRECLAIM is not set
---
> CONFIG_SOUND_OSS_CORE_PRECLAIM=y*******

I used the guided "encrypt drive" during the installation of 14.10 and booting into the earlier kernel was and isn't a problem.
At this point I have to manually select my older kernel manually and can login/decrypt the drive without problems.
I am really thankful for any feedback or requests about further data since this is quite not what I've wanted and I've tried bypassing the incident by reinstalling ubuntu from scratch several times (suspecting there were a corruption/deficiency in the upgrade process) but I have no logs that points to that this is the cause.
Maybe my information has been lacking in regards to reporting my problem but I've been trying looking further into my issue and have noticed discrepancies in the initramfs in the kernel that works (3.16.0-23-generic) and the one which isn't (3.16.0-30-generic).
I ran a diff between the both lsinitramfs:
http://pastebin.com/jLpLUk43
But I'm unsure in how to resolve the incident for the later kernel.
@user3807087 let me take my hat off and bow, cause this was driving me nuts and after numerous reinstallations and troubleshooting the incident I am now happy to say that your suggestion resolved the incident for me.
(no need pressing the ESC though).
So to clarify the solution I edited the /etc/default/grub file and replaced the text in the row: GRUB_CMDLINE_LINUX_DEFAULT= to:
GRUB_CMDLINE_LINUX_DEFAULT="ro"
And then ran:
update-grub

A:

Some possibilities:
nomodeset lurking in the grub config
http://ubuntuforums.org/showthread.php?t=2264430
Hit Esc in the prompt
Ubuntu 14.10 boot takes ESC to give encryption passphrase prompt
I'm also seeking an answer, since I'm struggling with the same problem. Fresh install of 14.10, get the encryption prompt and nothing works.
I resolved this on my own machine just now, by removing the "quiet" and "splash" options from the kernel and using the same "ro" option used by the recovery mode. Otherwise, when running not in recovery mode, I get stuck at loading initramfs.
To do this, I edited /etc/default/grub to set the variable GRUB_CMDLINE_LINUX_DEFAULT to "ro" from "quiet splash"


Q:

PHP code gets commented out

I have the following problem within the following script
PHP code:
$var = file_get_contents('template/default/index.php');
$content1 = str_replace('{php}','<?php',$var);
$content2 = str_replace('{/php}','?>',$content1);
echo $content2;

template/default/index.php code:
<!DOCTYPE html>

My First Heading

My first paragraph.

      {php} echo 'worked'; {/php}

I'm trying to transform the {php}{/php} tags within the template/default/index.php to propper php tags. This actually happends, but the php code gets commented out. The browser gives this in return:

My First Heading

My first paragraph.

Does anybody know how to solve this?

A:

Instead of echoing out the replaced content, it should be eval'd. Although I don't recommend that.


Q:

Cannot launch Pydev in Eclipse

I first installed Java; then installed Eclipse IDE using this (no problems at all).
Then I installed Pydev using this.
But whenever I launch Eclipse in my home folder it opens Java IDE not Python IDE.

In Help --> Installation Details --> I can find Pydev.
How can I open Python IDE in eclipse or choose the IDE I want?
Python and Java are installed in the same directory.

A:

It sounds like you just need to switch to the PyDev perspective instead of the Java perspective. Do this using 'Window > Perspective > Open Perspective' and choose 'Other > PyDev'.


Q:

PyOpenGL: glutTimerFunc callback missing required param 'value'

Using PyOpenGL, I am trying to create a simple triangle that changes colour on every refresh call and I'm trying to use glutTimerFunc(...) to do this.
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

import random

def display(value):
    v1 = [-.25,0]
    v2 = [0,.25]
    v3 = [.25, 0]
    r = random.randint(0,255)
    g = random.randint(0,255)
    b = random.randint(0,255)
    glClear(GL_COLOR_BUFFER_BIT)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(-1,1,-1,1,-1,1)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

    glBegin(GL_TRIANGLES)

    glColor3b(r,g,b)
    glVertex2f(v1[0], v1[1])
    glVertex2f(v2[0], v2[1])
    glVertex2f(v3[0], v3[1])

    glEnd()
    glFlush()

    glutTimerFunc(1000, display, 5)
    glutPostRedisplay()

if __name__ == '__main__':
    glutInit()
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
    glutInitWindowSize(500,500)
    glutCreateWindow("First Shape")
    glutDisplayFunc(display)
    glutMainLoop()

This is the error I am getting...
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 232, in 'calling callback function'
TypeError: display() missing 1 required positional argument: 'value'

I have tried passing 'value' and placing it in the parameter list for display() with no luck.

A:

The callback function required by glutDisplayFunc has no paramter, but the callback function required by glutTimerFunc has on parameter. So you can't use the same function for both.
Something like the following would be possibe:
def timer(value):
    display()

def display()

    glutTimerFunc(1000, timer, 5)

But that wont solve your issue, because
glutPostRedisplay  marks the current window as needing to be redisplayed and causes that the display callback function, which is set by glutDisplayFunc, is called.
If you want to change the color by time, then create a timer function, which sets a new color and restarts the timer:
r = 255
g = 255
b = 255

def timer(value):
    global r, b, g
    r = random.randint(0,255)
    g = random.randint(0,255)
    b = random.randint(0,255)
    glutTimerFunc(1000, timer, 5)

Remove the timer initialization form the display function
def display():
    global r, b, g
    v1 = [-.25,0]
    v2 = [0,.25]
    v3 = [.25, 0]
    glClear(GL_COLOR_BUFFER_BIT)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(-1,1,-1,1,-1,1)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

    glBegin(GL_TRIANGLES)

    glColor3b(r,g,b)
    glVertex2f(v1[0], v1[1])
    glVertex2f(v2[0], v2[1])
    glVertex2f(v3[0], v3[1])

    glEnd()
    glFlush()

    glutPostRedisplay()

But call the timer function once at startup:
if __name__ == '__main__':
    glutInit()
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
    glutInitWindowSize(500,500)
    glutCreateWindow("First Shape")
    glutDisplayFunc(display)
    timer(0);
    glutMainLoop()


Q:

Grails read from one domain to another domain

I created 2 domain class which is
Duty.groovy:
    class Duty {
               String username
               String duty
    }

User.groovy:
    class User {
               String username
    }

I already assigned some users in Bootstrap.groovy, I want to create a duty list function to assigned duty to users. So in my duty list, it should include a drop-down list which contains list of users from User domain.
But when I import testApp.User at my gsp (in Duty domain) file and created a taglib to display the userlist, my compiler shows that No such property. I would like to ask for suggestions for best way to display the list of users from my Duty domain to User domain?
Here is other code:
SelectUserTagLib.groovy
    import HR_System.User
    def userInstance = new User()
    def displayType = { attrs,body ->
    def name = attrs.name

    out << "<select id=\"${name}\" name=\"${name}\" require=\"\" >"
    out << "<g:each in='${userInstanceList}'' status='i' var='userInstance'>"
    out << "<option value=\"${name}\">${fieldValue(bean: userInstance, field: "username")}</option>"
    out << "</g:each>"
    out << "</select>"
}

_form.gsp:
    <name:displayType name="username" />

A:

I think you don't really need custom taglib for such purpose.
You can do it with simple g:select.
<g:select name="user"
          from="${User.list()}"/>

You can read about it in grails docs: https://docs.grails.org/latest/ref/Tags/select.html.
Please ask if you have any questions.


Q:

How to install Gapps on a Genymotion VM

i know this is no new topic here but none of the links i found were helpful. i tried to follow this tutorial --> How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?
I have no problem following the instructions until 5. Now reboot your VM using ADB (adb reboot) or an app like ROM Toolbox. If nescessary you can simply close the VM window, but I don't recommend it.
Since I have no clue how to use adb, I just closed the window, restarted genymotion and then moved the gapps via drag and drop into the vm. i can the start to flash gapps but after a few seconds i get the genymotion error "failed to flash files gapps jb....".
So i guess i know have to use adb, but since this is done via console which I have almost never used in my life, can someone please explain the adb process to me? to which directory do i have to set the console, which commands do i have to use etc.? So basically every step after downloading the adb kit until gapps are installed in genymotion? I would really, really appreciate any help since I don't know what to do anymore.
Thanks!

A:

To reboot the VM using adb, make sure the VM is running,

Open the command prompt (I'm assuming you're using windows) and just type in    adb devices    and press enter, that should list the devices you are running (you'll only see an IP address, this step is not necessary but it gives you an idea if your VM is actually running.
Next you want to type    adb remount    and press enter.
After that has executed type in    adb reboot    and that should reboot your VM. (Congrats, you are now a console Ninja).

If this still does not work, you could follow Method 2 below:

Open your file explorer and extract the two zip files you downloaded in step 1 of the tutorial you referred to.
Create a new folder (e.g. C:\Users\Public\New Folder) in the normal way you're used to
Going back to the extracted folders, open each of the extracted folders and look for a "system" folder (each extracted zip archive should have one) and copy that to the new folder you created. If you're asked to merge, allow the folders to be merged (you should end up with one "system" folder in your new folder i.e. C:\Users\Public\New Folder\System)
Now open the command prompt (with your VM running) and type in    adb devices    and press enter (just to check if its being recognized, and if it is you should get an IP address)
Next step, type in    adb remount    and press enter
After this type in    adb push "C:\Users\Public\New Folder\System" /System    and press enter (remember to replace the stuff in the quotes with your folder's path, but keeping the quotes in place)
This may take a while but after it is done your VM should have Google Play services installed and you may open Google Play, sign in, update all apps and you should be fine (You may get a lot of error messages but just press the "OK" button and continue with what you're doing.

NB* If you download a package that lacks the system folder, just try downloading another one until you get the right one
Kind regards!


Q:

find -daystart argument explanation

So I understand that a line such as:
find /var/log/ -mtime +60 -type f -exec ls -l {} \;

Will list all files in /var/log which were modified 60 days or more ago.
After reading through the find man page though I noticed:
 Measure  times  (for  -amin,  -atime,  -cmin, -ctime, -mmin, and
 -mtime) from the beginning of today rather than  from  24  hours
 ago.   This  option only affects tests which appear later on the
 command line.

Can someone explain the rest?  (-amin, -atime, -cmin, -ctime, -mmin) The man page itself does not seem to really declare what each of these do?
Some example questions which might help me understand:

Find files modified an hour or more ago?
Find files modified between 60 minutes and 10 minutes ago?
Find files modified 2 weeks ago?
Find files created in the last 5 minutes?

A:

Find files modified an hour or more ago?

-mmin +60

Find files modified between 60 minutes and 10 minutes ago?

-mmin -60 -mmin +10

Find files modified 2 weeks ago?

-mtime +7 -mtime -8

Find files created in the last 5 minutes?

Can't be done. POSIX has no specification for creation time.
These options are explained in the TESTS subsection of the EXPRESSIONS section of the find(1) man page.


Q:

Why are proteins always made in N to C direction?

Why are proteins always synthesized from the N-terminus to the C-terminus? Can there be any “reverse” peptide-bond formation to synthesize proteins in the C-terminal to the N-terminal direction?

A:

Nice question! As you already know, DNA is always shown in 5'$\rightarrow$3' direction because it is always synthesized in this direction (amino acids are joined by CO-NH peptide bond). So, a polypeptide looks like this (source):

In fact, if you just look at the polypeptide in the reverse direction, you could view it in C terminus to N terminus direction. But we don't do so because that is not the conventional direction of the polypeptide's biosynthesis.
Tracing the Roots: To know why there is no "reverse" peptide bond (NH-CO), we first need to know how peptide bonds are formed in polypeptides. Polypeptides are formed in ribosome, and the process of formation of peptide bond occurs in the peptidyl transferase complex of ribosome. Since ribosome is a ribozyme, this reaction is also catalyzed by the catalytic sites of RNA (i.e. 2'-OH) instead of proteins. See the image below for the mechanism (from Marina V. Rodina):

As visible from the diagram, nitrogen (in -NH2) from acceptor tRNA (A site) attacks the ester linkage at the peptidyl tRNA (P site). Carboxylic carbon cannot attack the nitrogen (for "reverse" bond formation) because it is already in ester linkage. One might ask then "if the nitrogen was joined to tRNA at P-site, the carboxylic carbon could have attacked on amino acid at A-site. Why is amino acid not joined to tRNA by the amine nitrogen?" To know why it is so, lets go a step further and see how tRNAs are charged i.e. how aminoacyl tRNA synthetase works. Aminoacyl tRNA synthetase charges tRNA in a two-step reaction. For displaying mechanism, I will take the example of histidyl-tRNA synthetase (diagrams from Proteopedia):

amino acid + ATP → aminoacyl-AMP + PPi
→
aminoacyl-AMP + tRNA → aminoacyl-tRNA + AMP

As is clearly visible now, whether amine nitrogen or carboxylic carbon will attach to phosphate of ATP is decided in the first step. See the image again:

You might ask that since nitrogen (in -NH2) also has a lone pair of electrons, it could also make a nucleophilic attack on the phosphate group, similar to the oxygen (in -COOH). Why doesn't this happen then? This cannot be accounted for by saying that the amine nitrogen is far away from the reaction site (look at the diagram again, and pay attention to how close the carboxylic carbon and amine nitrogen are. If we could move the amino acid even a little bit, this reaction could easily occur). Well, here's the twist: the optimum pH of this reaction lies near pH 6 i.e. in the acidic pH range (Lui et al, 1978). Now, as we know, under acidic pH, -NH2 exists in the protonated form i.e. -NH3+. In this condition, nitrogen lacks lone pair and thus cannot attack phosphate on ATP. Thus, it is not possible to attach amino acid to AMP via -NH2 group and, thus, form a "reverse" peptide bond. I hope this depth of the answer would be enough to satisfy your curiosity :)

A:

This is just in addition to the other answers; some somewhat relevant thoughts I had.
Interestingly, even non-ribosomal peptide synthesis seems to proceed N to C terminal. Given the modular nature of such enzymes, synthesis in the reverse direction doesn't seem to be outside the realm of possibility, though I haven't found any known examples.
This might be a stretch as a counterexample, but if you consider the biosynthesis of the tripeptide glutathione, a γ-peptide bond is first formed between cysteine and glutamate, after which glycine is attached to the carboxyl group (ie C-terminus) of cysteine with an α-peptide bond.


Q:

Algorithm to find smallest N such that N! is divisible by a prime raised to a power

Is there an efficient algorithm to compute the smallest integer N such that N! is divisible by p^k where p is a relatively small prime number and k, a very large integer. In other words,
factorial(N) mod p^k == 0

If, given N and p, I wanted to find how many times p divides into N!, I would use the well-known formula
k = Sum(floor(N/p^i) for i=1,2,...

I've done brute force searches for small values of k but that approach breaks down very quickly as k increases and there doesn't appear to be a pattern that I can extrapolate to larger values.
Edited 6/13/2011
Using suggestions proposed by Fiver and Hammar, I used a quasi-binary search to solve the problem but not quite in the manner they suggested. Using a truncated version of the second formula above, I computed an upper bound on N as the product of k and p (using just the first term). I used 1 as the lower bound. Using the classic binary search algorithm, I computed the midpoint between these two values and calculated what k would be using this midpoint value as N in the second formula, this time with all the terms being used.
If the computed k was too small, I adjusted the lower bound and repeated. Too big, I first tested to see if k computed at midpoint-1 was smaller than the desired k. If so, midpoint was returned as the closest N. Otherwise, I adjusted the highpoint and repeated.
If the computed k were equal, I tested whether the value at midpoint-1 was equal to the value at midpoint. If so, I adjusted the highpoint to be the midpoint and repeated. If midpoint-1 was less than the desired k, the midpoint was returned as the desired answer.
Even with very large values for k (10 or more digits), this approach works O(n log(n)) speeds.

A:

OK this is kind of fun.
Define f(i) = (p^i - 1) / (p - 1)
Write k in a kind of funny "base" where the value of position i is this f(i).
You do this from most-significant to least-significant digit.  So first, find the largest j such that f(j) <= k.  Then compute the quotient and remainder of k / f(j).  Store the quotient as q_j and the remainder as r.  Now compute the quotient and remainder of r / f(j-1).  Store the quotient as q_{j-1} and the remainder as r again.  Now compute the quotient and remainder of r / f(j-2).  And so on.
This generates a sequence q_j, q_{j-1}, q_{j-2}, ..., q_1.  (Note that the sequence ends at 1, not 0.)  Then compute q_j*p^j + q_{j-1}*p^(j-1) + ... q_1*p.  That's your N.
Example:  k = 9, p = 3.  So f(i) = (3^i - 1) / 2.  f(1) = 1, f(2) = 4, f(3) = 13.  So the largest j with f(j) <= 9 is i = 2 with f(2) = 4.  Take the quotient and remainder of 9 / 4.  That's a quotient of 2 (which is the digit in our 2's place) and remainder of 1.
For that remainder of 1, find the quotient and remainder of 1 / f(1).  Quotient is 1, remainder is zero, so we are done.
So q_2 = 2, q_1  = 1.  2*3^2 + 1*3^1 = 21, which is the right N.
I have an explanation on paper for why this works, but I am not sure how to communicate it in text...  Note that f(i) answers the question, "how many factors of p are there in (p^i)!".  Once you find the largest i,j such that j*f(i) is less than k, and realize what  you are really doing is finding the largest j*p^i less than N, the rest kind of falls out of the wash.  In our p=3 example, for instance, we get 4 p's contributed by the product of 1-9, 4 more contributed by the product of 10-18, and one more contributed by 21.  Those first two are just multiples of p^2; f(2) = 4 is telling us that each multiple of p^2 contributes 4 more p's to the product.
[update]
Code always helps to clarify.  Save the following perl script as foo.pl and run it as foo.pl <p> <k>.  Note that ** is Perl's exponentiation operator, bdiv computes a quotient and remainder for BigInts (unlimited-precision integers), and use bigint tells Perl to use BigInts everywhere.
#!/usr/bin/env perl

use warnings;
use strict;
use bigint;

@ARGV == 2
    or die "Usage: $0 <p> <k>\n";

my ($p, $k) = map { Math::BigInt->new($_) } @ARGV;

sub f {
    my $i = shift;
    return ($p ** $i - 1) / ($p - 1);
}

my $j = 0;
while (f($j) <= $k) {
    $j++;
}
$j--;

my $N = 0;

my $r = $k;
while ($r > 0) {
    my $val = f($j);
    my ($q, $new_r) = $r->bdiv($val);
    $N += $q * ($p ** $j);
    $r = $new_r;
    $j--;
}

print "Result: $N\n";

exit 0;

A:

Using the formula you mentioned, the sequence of k values given fixed p and N = 1,2... is non-decreasing. This means you can use a variant of binary search to find N given the desired k.

Start with N = 1, and calculate k.
Double N until k is greater or equal than your desired k to get an upper bound.
Do a binary search on the remaining interval to find your k.


Q:

Checksum of versions does not match on bundle install

Okay so I created a project on my old laptop in rails and heroku. I wish to access the files and push new edits to heroku on my laptop. They are all saved on Git so I am able to clone the git depository onto my new laptop.
My laptop had no previous software on it so I installed ruby and rails and the versions were fine but when I try and bundle install when the folder is open in command prompt I get the error "The checkum of /versions does not match the checksum provided by server! Something is wrong".
I am new to rails etc etc so I do not have a clue whats going on here I just want to setup my environment exactly the same as last time so I can start where I left off on my old laptop. I've tried numerous things like clearing the gems, updating the gems, reinstalling ruby and rails.
In addition to this when I try rails -v i get the error message "You do not have [insert gem name] try running bundle install" So i'll install the new gem and then i get the same error.
This has become a nightmare and I just want to find a clean way to install ruby and rails so that these errors will get out the way.
I created this project by following a guide so I guess I could do that all again but I would much prefer to just fix this current issue. I found one other occurrence of this happening to someone but it was in the case of creating a new file.
This is my gem file in the project
source 'http://rubygems.org'

ruby '2.1.8'

gem 'rails', '4.1.8'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0',          group: :doc
gem 'pygments.rb', '~> 0.6.0'
gem 'redcarpet', '~> 3.2.2'
gem 'friendly_id', '~> 5.1.0'
gem 'will_paginate', '~> 3.0.7'

gem 'tzinfo-data', platforms: [:mingw, :mswin]

group :development do
    gem 'sqlite3'
end

group :production do
    gem 'pg'
    gem 'rails_12factor'
end

A:

Try this. I was having a similar problem. Same error.
Try running
gem uninstall bundler

If it doesn't let you, add --force at the end of the command.
Then reinstall bundler
gem install bundler
bundle

I also did some extra deleting, but I'm not sure that was necessary.


Q:

How to improve speed for table with millions of rows

I am new to R and Stack Overflow and am hoping you would be able to help me with a question I have. I wrote the following piece of code:
my = matrix(c(1,1,1,1,1,1,1,1,1,1,
          2,2,2,2,2,2,2,
          0,1,2,3,5,6,7,10,11,14,
          0,1,2,3,4,6,10),ncol = 2, nrow = 17)
colnames(my) = c("ID", "AGE")
my = as.data.frame(my)
my$new = my$ID
system.time(for (i in 1:length(my$ID)) {

ifelse(my$ID[i]==my$ID[i-1],
     ifelse(my$AGE[i]-my$AGE[i-1]==1, my$new[i]<-my$new[i-1],my$new[i]<-my$new[i-1]+0.1),
     my$new[i]<-my$ID[i])
})

It looks at ID and AGE and if AGE is not equal to previous AGE + 1, then it adds 0.1 to ID and keeps this in the column 'new'. Here is the output:
   ID AGE new
1   1   0 1.0
2   1   1 1.0
3   1   2 1.0
4   1   3 1.0
5   1   5 1.1
6   1   6 1.1
7   1   7 1.1
8   1  10 1.2
9   1  11 1.2
10  1  14 1.3
11  2   0 2.0
12  2   1 2.0
13  2   2 2.0
14  2   3 2.0
15  2   4 2.0
16  2   6 2.1
17  2  10 2.2

The problem is that it is really quick for datasets of, say, 1000 rows, but when I try it on my actual dataset, which has more than 8.5m rows, it feels like it would never do it - I tried waiting a few hours with no success.
I would greatly appreciate it if you suggest a way to improve speed/efficiency.

A:

When dealing with large datasets, you need to try to vectorize your calculations to improve speed.
Here is an example using dplyr package (because of the function lag needed to know the previous value of AGE):
require(dplyr) # for group_by, mutate and %>%
require(microbenchmark) # to compare codes
# Your data
my           <- matrix(c(1,1,1,1,1,1,1,1,1,1,
                         2,2,2,2,2,2,2,
                         0,1,2,3,5,6,7,10,11,14,
                         0,1,2,3,4,6,10), ncol=2, nrow=17)
colnames(my) <- c("ID", "AGE")
my           <- as.data.frame(my)
my$new       <- my$ID
my2          <- my[rep(1:nrow(my), times=100),] # larger dataset

# Your function
f1 <- function(my) {
    for (i in 1:length(my$ID)) {
        ifelse(my$ID[i]==my$ID[i-1],
               ifelse(my$AGE[i]-my$AGE[i-1]==1, my$new[i] <- my$new[i-1],
                                                my$new[i] <- my$new[i-1]+0.1),
               my$new[i] <- my$ID[i])
    }
}

# dplyr function
f2 <- function(my) {
    my %>% group_by(ID) %>% # Work by ID
        mutate(new2=ifelse(is.na(lag(AGE)),  # If lag(AGE) is NA, it's the first record for the ID
                           FALSE,            # Thus, no increase of new3
                           AGE!=lag(AGE)+1), # new3=TRUE if AGE != 1+previous AGE
               new3=new+cumsum(new2)/10)     # increase the decimal if TRUE for the previous new2
}

With a small dataset, the for loop is more efficient, but with large dataset, the improvement is clear:
# Compare codes
microbenchmark(f1(my), f2(my),
               f1(my2), f2(my2))
Unit: milliseconds
    expr        min         lq       mean     median         uq       max neval cld
  f1(my)   1.470699   1.957855   2.750798   2.049954   2.243380  62.34942   100  a
  f2(my)   2.741614   3.853356   4.235745   4.147085   4.421738  10.84871   100  a
 f1(my2) 156.986927 215.515605 218.806729 222.390968 228.362988 290.19161   100   b
 f2(my2)   3.398812   4.377638   5.128953   4.659674   5.161190  28.97461   100  a


Q:

c++ if else statement won't go right pathway for text adventure game, always goes to the same Void Function

I have c++ issues.
On a text adventure game I am making, and on a part where I have choices for different options on what to do in a house, every choice I make always goes to the void Sleep() function:
void Home()
{
    cout << "\nYou are in the living room of your rented home. Everything looks nice and tidy." << endl;
    cout << "Choices:" << endl;
    cout << "Sleep" << endl;
    cout << "Leave" << endl;
    cout << "Stats" << endl;
    cin >> choice;

    if (choice == "Sleep" || "sleep")
    {
        Sleep(); // No matter what choice I make, it always
        //goes to the Sleep(); void.
    }
    if (choice == "Leave" || choice == "leave"){
        TownSquare();
    } if (choice == "Stats" || choice == "stats") {
        StatsH();
    }
    else {
        cout << "Please choose correctly!" << endl;
        Home();
    }
}

All help will be much appreciated. Thank you!

A:

Your line:
if (choice == "Sleep" || "sleep")

Evaluates as:
if ((choice == "Sleep") || "sleep")

Which is always true since "sleep" will always trigger. You may want to make a proper look-up table here and force the input as lower-case if that's a concern.


Q:

Why did Joseph's brothers immediately leap to explaining Joseph's demands in the way they do?

Genesis 42:18-21 (NIV):

On the third day, Joseph said to them, “Do this and you will live, for I fear God: If you are honest men, let one of your brothers stay here in prison, while the rest of you go and take grain back for your starving households. But you must bring your youngest brother to me, so that your words may be verified and that you may not die.” This they proceeded to do.
They said to one another, “Surely we are being punished because of our brother. We saw how distressed he was when he pleaded with us for his life, but we would not listen; that’s why this distress has come on us.”

Why did they immediately jump to that conclusion? Was it because they saw Joseph and he reminded them of his younger self (so they were thinking about it anyway), or did they just feel guilty "in general"?

A:

We are not told the answer to this question but having had personal experience as a result my own stupidity, let me suggest that after 22 years of guilt over their deception and presumed indirect murder of Joseph, it does not take much to trigger personal recriminations and extreme remorse such as we see here.  [I also suspect that some other bad events might have triggered similar thoughts as well.]
Guilt is a very powerful emotion which is why the NT goes to such lengths to deal with it by way of complete forgiveness of sin (Matt 9:2, 5, 6, 12:31, 32, 26:28, Mark 14:24, Acts 8:22, Rom 4:7, James 5:12, 1 John 1:9, 2:12, etc).  See Rom 3:23-27.


Q:

Alternatives to the repository pattern?

People have yelled at me, that I should always use the repository pattern, which I've done for quite a while... Now I'm wondering whether there is any decent alternatives for this pattern at all?

A:

Well there's the Data Access Object pattern, but that often sits on top of the repository, and serves to wrap up complex queries so they can simply be called as a single method.
Repository provides a standard interface into your database, and DAO exposes standard queries, which is why the two go together so well; DAO forwards specific calls to repository.  Of course you could certainly choose to not use a repository in your DAO.  You could open a connection to your DB and run the queries directly, or use a Table Data Gateway, but I think the reason most people prefer Repository is because it's quite a bit cleaner than those two options, though they shouldn't be yelling at you :)
http://en.wikipedia.org/wiki/Data_access_object

In computer software, a data access
  object (DAO) is an object that
  provides an abstract interface to some
  type of database or persistence
  mechanism, providing some specific
  operations without exposing details of
  the database. It provides a mapping
  from application calls to the
  persistence layer. This isolation
  separates the concerns of what data
  accesses the application needs, in
  terms of domain-specific objects and
  data types (the public interface of
  the DAO), and how these needs can be
  satisfied with a specific DBMS,
  database schema, etc. (the
  implementation of the DAO). This
  design pattern is equally applicable
  to most programming languages, most
  types of software with persistence
  needs and most types of database, but
  it is traditionally associated with
  Java EE applications and with
  relational databases accessed via the
  JDBC API because of its origin in Sun
  Microsystems' best practice
  guidelines[1] ("Core J2EE Patterns")
  for that platform.


Q:

Is it necessary to use resistor when connecting backlight of 16x2 LCD display?

I wonder if it's necessary to use any resistor when you're connecting backlight of
16x2 LCD module? OR it depends on voltage?
I am using Hitachi HD47780

A:

This is just a complementary answer for people facing this question for the first time (beginners or even non-beginners), like I did a few months ago when received a batch of no-name LCD modules clones of the JHD162A with an incorrect datasheet. This answer only apply to LCD modules with a LED backlight (using a single LED or an array of LEDs) which are the most popular.

If you have the datasheet, it should contain the information somewhere, you just need to calculate the current limiter resistor value using the suggested LED forward current and supply voltage minus the LED forward voltage.
If you don't have the datasheet, check the back of the LCD. Usually you can find easily if there is a resistor in series with the A (or even the K) pin. The following images show how some modules which already have a limiting resistor. Just be sure it is really a resistor and not a jumper (a zero ohm "resistor").
If you find (or not) the limiting resistor, verify it is in series with the LED supply by measuring the resistance from the A pin to the anode of the backlight and from the K pin to the cathode of the backlight. The backlight usually is soldered to pads marked as A and K.
If even after inspecting and measuring you are not sure, just use a 100 or 220 ohms resistor and test.
If you are designing a PCB and you are not sure if the provisioned LCD modules will have already a resistor, just add the space for a resistor in your circuit; so later on, during production, you can use a resistor or a jumper. (Of course that kind of thing should be known in advance, but sometimes is not always possible, or the requirements may state that your circuit it should work with any LCD module).

In this image a LCD 16x2 character module has a 100 ohm resistor (R8) in series with the A pin (pin 15) trace. The value was verified measuring from pin 15 to the A pad (in the left edge) soldered to the backlight.

In this image, a JDH204A (JHD629) LCD 20x4 character module has a combination of jumpers and resistors to select what pins are for the cathode (K) and anode (A) (the table in the silkscreen describe the configuration options). In this case R9 and R11 are using jumpers, meaning pin 15 is for the anode and 16 is for the cathode of the backlight, and the R12 and R13 are the limiting resistors (they are in parallel, in this case both are 68 ohms, providing 34 ohms). The value was verified by measuring the resistance between pin 15 and the A1 pad (at the left edge) soldered to the backlight.

In this image, a JDH204A clone, there is a 51 ohm resistor in series with the A pin trace and a jumper for the K pin trace. The value was verified measuring the resistance between pin 15 and the top pad at the left edge (you can follow the trace from the resistor to that pad, so we expect it to be the LED anode connection). You may note the resistors are installed perpendicular to the position drawn in the silkscreen; the manufacturer can change easily the polarity of the A and K pins just by solder the resistor/jumper pair vertically or horizontally.

In all modules I have used over the years, the A and K pins are completely independents of the LCD and controller circuit, so you may use a different supply rail with a different voltage than the rest of the circuit. (Just note that this has just been my experience with the original JHD modules and some clones, but this may not apply to other brands).

A:

It depends entirely on the module.  Some have a limiting resistor (e.g. the JHD162 commonly seen on eBay) and some do not.  You will need the datasheet for your specific model, or have a look at the LED connections and see if you can see a series resistor.
The HD44780 is not connected to the backlight in any way.


Q:

Where are the actual names of the packages in "apt list --upgradable"?

It seems to be printing only the versions:
$ apt list --upgradable
Listing... Done
dpkg/bionic-updates 1.19.0.5ubuntu2.3 amd64 [upgradable from: 1.19.0.5ubuntu2.2]
file-roller/bionic-security 3.28.0-1ubuntu1.1 amd64 [upgradable from: 3.28.0-1ubuntu1]
libdpkg-perl/bionic-updates,bionic-updates 1.19.0.5ubuntu2.3 all [upgradable from: 1.19.0.5ubuntu2.2]

Tried using "1.19.0.5ubuntu2.3" or just "ubuntu", to no avail as expected:
$ apt show 1.19.0.5ubuntu2.3
N: Unable to locate package 1.19.0.5ubuntu2.3
N: Couldn't find any package by glob '1.19.0.5ubuntu2.3'
N: Couldn't find any package by regex '1.19.0.5ubuntu2.3'
N: Unable to locate package 1.19.0.5ubuntu2.3
N: Couldn't find any package by glob '1.19.0.5ubuntu2.3'
N: Couldn't find any package by regex '1.19.0.5ubuntu2.3'
E: No packages found
$ apt show ubuntu
N: Unable to locate package ubuntu
N: Unable to locate package ubuntu
E: No packages found

So, where are the actual package names? OS version reads Ubuntu 18.04.3 LTS.

A:

dpkg, file-roller, and libdpkg-perl are the packages that can be upgraded. 1.19.0.5ubuntu2.3, 3.28.0-1ubuntu1.1, and 1.19.0.5ubuntu2.3 are the versions to which they can be upgraded, respectively.


Q:

HTML5 Canvas Ellipse Outline Becomes Distorted As Transformed

When I transform an HTML5 canvas context and draw an ellipse, as the transform becomes larger the ellipse outline becomes completely distorted. Below is some sample code and the results I see in both Firefox and Chrome.
<body>
    <canvas id="myCanvas" width=900 height=900></canvas>
    <script>
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "rgba(0, 51, 255, 0.5)";
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.transform(1, 0, 0, 1, -16776544, -16776916);
        ctx.ellipse(16776994, 16777316, 400, 400, 0, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.fill();
    </script>
</body>

Chrome Results
Firefox Results
Is there a way to fix the distortion, or is it somewhere documented that there are limits on canvas transformation?

A:

This is due to the limited precision of floating point numbers. There is not much you can do about it but to avoid really big and really small numbers.
With a pixel size of 0.1mm you are addressing a pixel that is near one mile from the origin (that's a very big screen).
I am not sure if the canvas rendering uses 32bit floats (thinking it does from your example and I know that webGL definitely uses floats) you need to do the transformations in javascript as it uses doubles 64bit which will give you a screen 9 orders (approx) greater (screen now size of the sun)
eg
var x = 16776544;
var y = 16776916;
var x1 = 16776234;
var y1 = 16776446;
ctx.setTransform(1,0,0,1,0,0);
x -= x1; // apply transform using doubles
y -= y1;
ctx.ellipse(x,y,100,100,0,0,Math.PI*2);


Q:

Add dupli_extrude_cursor to Extrude dropdown box

There are two items that are not in the UI, but just available by a hotkey. Dupli Extrude and Dupli Extrude Rotate.
I want them to be visually available in the Extrude dropdown box in the tool shelf in the Tools panel. So I added them to the submenu for it, which is in the space_view3d-py file, the class VIEW3D_MT_edit_mesh_extrude. And there I am stuck.
The operator is mesh.dupli_extrude_cursor. With a flag to tell if the target object rotates randomly or not. And this flag is the trouble maker here. I can add a normal button that way:
        col.operator("mesh.dupli_extrude_cursor" , icon='DUPLI_EXTRUDE',  text = " DupliExtrude    ").rotate_source = False
        col.operator("mesh.dupli_extrude_cursor", icon='DUPLI_EXTRUDE_ROTATE', text = " DupliExRotate  ").rotate_source = True

But when I do the same in the dropdown box menu then the whole Blender menu vanishes. VS marks me the whole code red then. I also tried to include the flag with the operator. But then Blender doesn't find it and gives a missing srna error in the console. I cannot leave the flag away, that's what separates the tools. And also curious, the dropdown box entry does not show the hotkey for it.
What's the right way to put those two items into the dropdown box?
class VIEW3D_MT_edit_mesh_extrude(Menu):
    bl_label = "Extrude"

    _extrude_funcs = {
        'VERT': lambda layout:
            layout.operator("mesh.extrude_vertices_move", text="Vertices Only"),
        'EDGE': lambda layout:
            layout.operator("mesh.extrude_edges_move", text="Edges Only"),
        'FACE': lambda layout:
            layout.operator("mesh.extrude_faces_move", text="Individual Faces"),
        'REGION': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_move_normal", text="Region"),
        'REGION_VERT_NORMAL': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_move_shrink_fatten", text="Region (Vertex Normals)"),
        'DUPLI_EXTRUDE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor(rotate_source = False)", text = "DupliExtrude"), # does not work, Blender does not find the operator
        'DUPLI_EX_ROTATE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor", text="Dupli Extrude Rotate").rotate_source = True,  # does not work, Blender Menu vanishes

    }

EDIT: I could of course add two helper classes. It works. See this example. But i am not a happy bunny with this solution. I want to add the operators in the way the other operators in this dropdown box are added too. There should be a solution.
class VIEW3D_MT_edit_mesh_extrude_dupli(bpy.types.Operator):
    """Duplicate or Extrude to Cursor"""      # blender will use this as a tooltip for menu items and buttons.
    bl_idname = "mesh.dupli_extrude_cursor_norotate"        # unique identifier for buttons and menu items to reference.
    bl_label = "Duplicate or Extrude to Cursor"         # display name in the interface.
    bl_options = {'REGISTER', 'UNDO'}  # enable undo for the operator.

    def execute(self, context):        # execute() is called by blender when running the operator.
        bpy.ops.mesh.dupli_extrude_cursor('INVOKE_DEFAULT', rotate_source = False)
        return {'FINISHED'}

class VIEW3D_MT_edit_mesh_extrude_dupli_rotate(bpy.types.Operator):
    """Duplicate or Extrude to Cursor Rotated"""      # blender will use this as a tooltip for menu items and buttons.
    bl_idname = "mesh.dupli_extrude_cursor_rotate"        # unique identifier for buttons and menu items to reference.
    bl_label = "Duplicate or Extrude to Cursor Rotated"         # display name in the interface.
    bl_options = {'REGISTER', 'UNDO'}  # enable undo for the operator.

    def execute(self, context):        # execute() is called by blender when running the operator.
        bpy.ops.mesh.dupli_extrude_cursor('INVOKE_DEFAULT', rotate_source = True)
        return {'FINISHED'}

class VIEW3D_MT_edit_mesh_extrude(Menu):
    bl_label = "Extrude"

    _extrude_funcs = {
        'VERT': lambda layout:
            layout.operator("mesh.extrude_vertices_move", text="Vertices Only"),
        'EDGE': lambda layout:
            layout.operator("mesh.extrude_edges_move", text="Edges Only"),
        'FACE': lambda layout:
            layout.operator("mesh.extrude_faces_move", text="Individual Faces"),
        'INDIVIDUAL': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_individual_move", text="Individual"),
        'REGION_VERT_NORMAL': lambda layout:
            layout.operator("view3d.edit_mesh_extrude_move_shrink_fatten", text="Region (Vertex Normals)"),
        'DUPLI_EXTRUDE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor_norotate", text="Dupli Extrude"),
        'DUPLI_EX_ROTATE': lambda layout:
            layout.operator("mesh.dupli_extrude_cursor_rotate", text="Dupli Extrude Rotate")
    }

    @staticmethod
    def extrude_options(context):
        mesh = context.object.data
        select_mode = context.tool_settings.mesh_select_mode

        menu = []
        if mesh.total_face_sel:
            menu += ['INDIVIDUAL', 'REGION_VERT_NORMAL', 'FACE']
        if mesh.total_edge_sel and (select_mode[0] or select_mode[1]):
            menu += ['EDGE']
        if mesh.total_vert_sel and select_mode[0]:
            menu += ['VERT', 'DUPLI_EXTRUDE', 'DUPLI_EX_ROTATE']

        # should never get here
        return menu

    def draw(self, context):
        layout = self.layout
        layout.operator_context = 'INVOKE_REGION_WIN'

        for menu_id in self.extrude_options(context):
            self._extrude_funcs[menu_id](layout)

A:

Can quite simply ap(pre)pend those operators to the menu
import bpy
def draw_dupli_extrude(self, context):
    col = self.layout
    col.operator_context = 'INVOKE_REGION_WIN'
    col.operator("mesh.dupli_extrude_cursor" ,  text="DupliExtrude").rotate_source = False
    col.operator("mesh.dupli_extrude_cursor", text="DupliExRotate").rotate_source = True
# prepend to menu
bpy.types.VIEW3D_MT_edit_mesh_extrude.prepend(draw_dupli_extrude)

NOTE: The operators are kind of useless in the menu as that's where the mouse is to invoke... which could be why they are not there in the first place.
Always look at system console for errors, as in your sample code there are no icons for
icon='DUPLI_EXTRUDE'
icon='DUPLI_EXTRUDE_ROTATE'

which will lead to a TypeError.


Q:

parse form (POST) data to create a multidimensional hash

I have a form which is used to submit data about multiple people. There are multiple properties for each person, and I'm grouping them like the following:
<input type=hidden name="person1[firstname]" value='Sam'/>
<input type=hidden name="person1[lastname]" value='Higgins'/>

<input type=hidden name="person2[firstname]" value='Jiminy'/>
<input type=hidden name="person2[lastname]" value='Cricket'/>

...etc

When I do the following:
my %hash = params;
die Dumper \%hash;

I get:
VAR1 = {
          'person1[firstname]' => 'Sam',
          'person1[lastname]' => 'Higgins',
          'person2[firstname]' => 'Jiminy',
          'person2[lastname]' => 'Cricket',
};

When I was expecting something like:
VAR1 = {
          'person1' => { firstname => 'Sam', lastname => 'Higgens' },
          'person2' => { firstname => 'Jiminy', lastname => 'Cricket' },
};

Is there a way to get the above, or am I doing it wrong in my HTML?
Edit
I've also tried with empty brackets at the end:
<input type=hidden name="person1[firstname][]" value='Sam'/>

but that just gave:
'person1[firstname][]' => 'Sam',

A:

To answer the question more wholly than providing a link:
I went with a solution that uses jQuery, specifically using a plugin (https://github.com/marioizquierdo/jquery.serializeJSON), to send the data asynchronously (AJAX) and using Dancers from_json method which creates a hashref of the JSON string.
I emphasise string because the function offered by the serializeJSON plugin creates a JSON object, and this Dancer does not convert to the proper structure. Therefore you need to use JSON.stringify() to create a json string, which Dancer does accept :)
Below is the code:
Example HTML:
<input type=hidden name="person1[firstname]" value='Sam'/>
<input type=hidden name="person1[lastname]" value='Higgins'/>

JS (jQuery):
var formData = $(this).serializeJSON();
console.log(formData);
$.ajax({
     'url': '/your_url',
     'type': 'POST',
     'data': JSON.stringify(formData),
     'success': function(res){
         console.log(res);
   }
 });

Perl (Dancer):
post '/your_url' => sub {
    my $json = request->body;
    use Data::Dumper;
    my $hashref = {};
    $hashref = from_json($json);
    die Dumper \$hashref->{person1}->{name}; # 'Sam'
}

Thanks to all who helped!


Q:

C++ operating on "packed" arrays

Suppose that I have two, for example, float arrays a and b, an int key array k and a template mySortByKey function of my own, operating on a single array, something like
template<class T>
mySortByKey(int *k, T *a)

Is there a possibility (for example, using zip iterators and tuples of some sorts) to enable mySort operating simultaneously on a and b, so that they can be simultaneously ordered according to the key k?

A:

I don't think you can do that. However, you can accomplish something similar by the use of a helper array of indices.
int keys[ARRAY_SIZE];
float a[ARRAY_SIZE];
float b[ARRAY_SIZE];

// Fill up the contents of keys, a, and b

// Create an array of indices.
int indices[ARRAY_SIZE];
for ( int i = 0; i < ARRAY_SIZE; ++i )
   indices[i] = i;

// Sort the indices using keys.
mySortByKey(keys, indices);

// Now access the arrays a and b indirectly, using the sorted array
// of indices as an intermediate object.
for ( int i = 0; i < ARRAY_SIZE; ++i )
{
   float fa = a[indices[i]];
   float fb = b[indices[i]];
}


Q:

No puedo trabajar con las propiedades text en Atom, aparecen deshabilitadas

 background-color: red;
  text-align: center;
  text-decoration: overline;
  text-indent: inherit;
  text-overflow: inherit;

en la imagen se ve: ( puede que sea un package que sea necesario, no me había pasado esto antes)

A:

Me sucedió lo mismo hace algún tiempo.
Atom toma por defecto la extensión de tu archivo (.css .html .php, etc) y así mismo aplica a la sintaxis unos colores preestablecidos.
Si esto no sucede de forma automática, o está como texto plano, puedes cambiarlo de la siguiente manera.
Abajo del todo a la derecha vas a ver la sección donde se especifica el lenguaje a usar y por tanto a marcar (en el ejemplo, plain text)

Haciendo clic sobre esa opción, puedes cambiar el tipo de lenguaje que se va a aplicar en la sintaxis, puedes ver que son varios.

Por último, escoge el que deseas usar (puedes hacer este cambio manualmente las veces que desees). Como recomendación, y en caso de no ser así, deja por defecto Auto Detect

Fuente

Actualización

Me quedó vagando tu pregunta en la mente, y me doy cuenta que no había intentado reproducir exactamente tu código CSS en mi editor Atom; para sorpresa mía, ocurre lo mismo que en tu imagen:

Esto sucede porque Atom (por defecto) resalta en color (en archivos CSS en este caso) únicamente las clases, los valores de color (hexadecimal, RGBA, etc), los valores de número (px, % , .rem, etc), valores de duración (s, ms, etc), las pseudo-clases y los pseudo-elementos (:hover, :focus, ::after, ::before, etc) entre otros.
No resalta ni da color a propiedades con valores como display, none, relative, auto, absolute y muchos más valores de tipo "texto".
Puedes validarlo tú mismo, por ejemplo, viendo en Atom la hoja de estilos de Bootstrap.