Q:

Java sending UTF-8 characters after compiled to Jar not working

This is really strange, when i am running my application from within NetBeans everything works fine. However when i build the app into a Jar and run it from the Jar the following code converts characters like ä, ö, å to ?
os = new DataOutputStream(socket.getOutputStream());
String string = "{\"id\":1,\"type\":\"" + methoden + "\",\"message\":\"" + msget + "\"}";

PrintWriter pw = new PrintWriter(os);
pw.println(string);
pw.flush();

In the above example the String msget = "Hej där, vad händer"
When i console.log this on the server i get: {"id":"1", "type":message, "message": "Hej d?r, vad h?nder "}
Again, this does only happend when i compile my app into a Jar.
Any ideas what is going on?

A:

You get question marks when the text encoding you are using does not support a given character.

PrintWriter pw = new PrintWriter(os);

When you are not setting a specific character set, the behaviour becomes platform-dependent. For example, environment variables will be taken into consideration, which may be different when started from inside Netbeans.
Always specify the character set to use

PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8")); // or whatever


Q:

Is it possible to send a HEREDOC over ssh to a remote host from inside a script running locally?

I essentially want to run a script on machine A which will SSH into machine B, execute commands on B, and return the output to machine A.
So I am creating a csh script to do this, hopefully, if it's possible.
For instance, this solution from this answer works from command line:
ssh user@host << 'ENDSSH'
ls -l
ENDSSH

I can verify it is running the ls on the remote and not locally.
However I want to be able to do this within the backticks, inside my csh script running locally. Would that be possible?
I know it is possible to SSH in and run a script that is on the remote, but that is not my case.
I have also heard it is possible to send a second script stored locally over the SSH (which I also have not figured out), but I like the idea of having all of the commands inside the original script, hence the HEREDOC.
I know it is a pretty particular question, but if there is a way, it would be very cool to know how.
Things that don't work
1)
`ssh user@host<<'ENDSSH'`
`echo "ls -l"`
`echo "ENDSSH"`

This gives the error:
stty: standard input: Invalid argument.
stty: standard input: Invalid argument.
Warning: Command not found
And then it runs ls -l locally, and then it tried to run ENDSSH locally and of course fails with command not found.
2)
`ssh user@host<<'ENDSSH'`
echo "ls -l"
echo "ENDSSH"

Same problem as above, except it only displays ls -l and ENDSSH as text. Makes sense...since the HEREDOC portion failed.
3) 3-5 aren't exactly what I asked about, but still trying just to get even the basic case working.
`ssh user@host ls-l`

This returns total: Command not found.
Yeah, I have no clue where that's coming from.
4)
`cat ./test.csh | ssh user@host`

Also returns the same as attempt #1
5)
`cat ./test.csh | ssh -t user@host`

Same as #1 and 4.
I am beginning to exhaust other solutions from stackoverflow/Ubuntu/serverfault...etc.  Most people ask about how to run their script on a remote from command line, not how to run commands on a remote from a locally running script.
Edit
Well I think I have part of the problem figured out.  With case 3 from above for example, what happens is ls -l runs locally, and the first part of the output is then sent over SSH as a command.
I noticed this because I tried ssh user@host $CMD, with $CMD set to "whoami". The output was username: Command not found, and then I realized the total is from the ls output. Still not sure about how to solve this, though

A:

If you wrap the entire command that you want executed inside backticks it's likely you'll get the correct solution. There are issues regarding the evaluation of variables and other interpolated elements, but I'll put those to one side for a moment.
However, I'm not entirely sure why you want anything in backticks. Your Question says you want to run a local script remotely. Your first example does this.
ssh -q user@host << ENDSSH
hostname
ls -l
id
ENDSSH

Perhaps you want to get the output of the remote execution into a variable? It doesn't say that anywhere in the Question, but you'd do it like this (bash)
RESULT=$(ssh user@host <<ENDSSH
hostname
id
ENDSSH
)
...
echo "$RESULT"

Or, since you mentioned csh, like this
set result = `ssh -q user@host` <<ENDSSH
hostname
id
ENDSSH
...
echo "$result"

Note that for the csh variant all output lines are concatenated together.
I see that you have reported an error, stty: standard input: Invalid argument. This is probably occurring because you have an stty command in your login script on the remote server. This should be wrapped in a test for an interactive shell. In bash you would do something like this:
if test -n "$PS1"
then
    # Interactive setup here
    stty ...
fi


Q:

Regarding .Net Windows Authentication

I have a web application which is set up to use windows authentication. This is used by people across the state. These users are not in our AD and are authenticated against the database when they try to log in. After a successful login, the resources to which the use has access to are stored as bits in the session.
For each subsequent request we check the session variables to see if it is valid request and if the user is authorized to access the resource. We do not use Forms authentication.
As the number of users grow I am worried about the size of the session state. How do we better handle the authentication/authorization without the use of session variables? This is a .Net Web Application using 2.0.

A:

A few bits per user is not something that will take too much memory and affect the scalability of your website. Well, unless you have thousands of bits per user.
However, the real performance hit can be coming from the code that is calculating all those resources accessible by each user. If that code is a bit heavy, you can consider spreading out the load:
Once the user is authenticated, just save one value that indicates the user's role. Then every time you need to check if the user has access to a specific resource, you retrieve the role-value from the session and use it to determine whether the user has access or not.


Q:

How to provide Vertica user with read-only access to certain specified system tables?

We're looking to set up a user in our Vertica database that can see certain system tables, (projections, projection_storage and views), but we don't want this user to be a dbadmin, because we don't want them to have write privileges on these tables.  I've tried using GRANT statements to give a regular user access to these tables, but that doesn't seem to work.  Each user can only see their own own records in those tables.  Is there a way to set up a user as I describe, or do we need to have this user be a dbadmin?
Our use case is that we need a user that can get a list of the schemas that exist in our database and iterate through each schema, gathering information to store in one central location.  If our user is granted usage on the individual schemas, then they can get a list of those schemas, but they aren't able to access the necessary records in the projection_storage and views tables.
Thank you!

A:

Granting USAGE on the schema to the user or role is not enough for users to see its projections in projection_storage table. If the user or the role has SELECT access on the table, then projections for those tables can be viewed in projection_storage. I am in Vertica 7.1, and I was able to view projection records by granting SELECT permission just to the role instead of granting to individual user ID.
If the user does not need to access tables but needs to list out tables in the schema for some reporting purpose, one option would be to periodically dump the content of projection_storage to a different table and grant proper privileges on this table to the user.


Q:

Plunker giving me 404s on scripts that worked a several days ago

I made a plunker a few weeks ago and everything was going well.
However today when I revisited it I am bombarded by 404s on my scripts, any idea on what changed?
http://plnkr.co/edit/M2hRaf?p=preview

Here is what the index.html looks like
<!DOCTYPE html>
<html>

  <head>
    <base href="." />
    <script type="text/javascript" charset="utf-8">
      window.AngularVersionForThisPlunker = 'latest'
    </script>
    <title>angular playground</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css" />
    <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js/dist/zone.js"></script>
    <script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js"></script>
    <script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
    <script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
    <script src="config.js"></script>
    <script>
    System.import('app')
      .catch(console.error.bind(console));
  </script>
  </head>

  <body>
    <my-app>
      Loading...
    </my-app>
  </body>

</html>

A:

That's because your plunker now uses latest rxjs version and there were a lot of changes lately.
So try updating your config like:
System.config({
  ...
  map: {
    ...,
    'rxjs': 'npm:rxjs',
    'rxjs-compat': 'npm:rxjs-compat',
    'rxjs/operators': 'npm:rxjs/operators',
  },
  packages: {
    ...,
    'rxjs': { main: 'index.js', defaultExtension: 'js' },
    'rxjs/operators': {main: 'index.js', defaultExtension: 'js' }
  }
  ...

Forked Plunker


Q:

JQuery Mobile Collapsable Slide Transition

Has anyone been able to add a slide transition to the JQuery Collapsible property?
I am trying to make a list that is collapsable with data-inset="false", and when the user taps the menu item, the collapsed section slides out.
Here is an example of what I am trying to do (but with JQuery Mobile instead), however, in this example, the transition is not as smooth as I would like it: http://www.designgala.com/demos/collapse-expand-jquery.html
Ideas?
Note: I have seen other posts with a similar objective, however, none of the posts used the transition I described, they used a fade.

A:

Here's a very simple and concise bit of JS that I use to animate my collapsible sets.
$(document).on('pageinit', function(){
    $("[data-role='collapsible']").collapsible({

        collapse: function( event, ui ) {
            $(this).children().next().slideUp(150);
        },
        expand: function( event, ui ) {
            $(this).children().next().hide();
            $(this).children().next().slideDown(150);
        }

    });
});

Here's a demo in JSFiddle.


Q:

Swift Firebase: Identify Change in Database

I am writing a chat application and attempting to implement readReceipts. I have the following Firebase database structure, and when a message is opened, I will do a updateChildValue. This will update the Bool to true, like so:
Snap (messages) {
    "-L7E-3km6bvx3WWFHeuj" = 1;
    "-L7E-MXzwmZ9iv6Bj0oM" = 1;
    "-L7E-N5pm-FGtb3m3AOr" = 1;
    "-L7E-Q2cRJz9DDFgRWL_" = 1;
    "-L7E-U4r1vd94i-xbNTh" = 1;
    "-L7E1LdrJaqZDjIkWd7X" = 1;
    "-L7EBz3hxfJ-E3f7joJ6" = 1;
    "-L7EE8A5eZNyey12GcHB" = 1;
    "-L7EEwX2m-rrPYFgDoA8" = 0;
    "-L7EFA7CHfyRoECUkeLm" = 0;
    "-L7EFPICxdWQcrLOEUkM" = 0; //Updating this will change Bool to 1
    "-L7EJ1byG2KLKZf_Cspv" = 0;
    "-L7EKRmXYz_94UrIPGhS" = 0;
}

I listen for childChanged on my messages node, and when the update changes to true, I will update the views of the collectionViewCells. However, implementing childChanged will always extract the whole messages node.
Is there a way to identify the exactly which id gets the update and hence obtain the indexPath to update the collectionViewCells? Alternatively, is there a better way to implement readReceipts?

A:

There is another observer function just for your case
from Firebase Docs

observeEventType:andPreviousSiblingKeyWithBlock: is used to
  listen for data changes at a particular location. This is the primary
  way to read data from the Firebase Database. Your block will be
  triggered for the initial data and again whenever the data changes. In
  addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved,
  and FIRDataEventTypeChildChanged events, your block will be passed the
  key of the previous node by priority order.

func observe(_ eventType: DataEventType, andPreviousSiblingKeyWith block: @escaping (DataSnapshot, String?) -> Void) -> UInt

Example:
Database.database().reference().child("messages").observe(.childChanged) { (snapshot, key) in
    print(key)
    //"-L7EFPICxdWQcrLOEUkM"
}


Q:

n-th: как написать/произнести?

If I want to write the word "n-th" (as in n-th solution, n-th derivative,...), is it more conventional to write n-ый/n-ая/n-ое or n-й/n-я/n-е, or are both styles equally common? In terms of pronunciation, is it always э́ный/э́ная/э́ное (e.g., someone who writes n-я wouldn't actually say that as э́ня)?
EDIT: I found out later that for every variable x it's acceptable to express "x-th" as "xтый" (e.g., m-ый = эмтый, n-ый = энтый, j-ый = житый, q-ый = кутый), and since this works in all cases while the ending -ный for n-ый doesn't apply to variables ending with a vowel sound, I'll use the -тый version.

A:

While both written styles are grammatically correct, the more common one is

n-ый, -ая, -ое, -ые

In addition, you could see sometimes the n- part spelled out in Russian as:

энный, энная, энное, энные

The pronunciation in all cases would be

э́нный / э́нная / э́нное / э́нные

(Note the double н)
pronunciation э́ня is wrong and it's more than likely that people will not understand what you're referring to.

A:

The grammatically correct form is only n-й.
Acoording to entrenched tradition accretion suffix must be one-letter if the last letter of numeral follows by vowel: 5-й день (пятый день), 25-я годовщина (двадцать пятая годовщина), в 14-м ряду (в четырнадцатом ряду). It must be two-letter if the last letter of numeral follows by consonant: 5-го дня (пятого дня), к 25-му студенту (к двадцать пятому студенту), из 14-го ряда (из четырнадцатого ряда). Spelling n-ый is incorrect, but widely used. Sad but true; it is common mistake. Accretion suffixes for variables also comply these rules.


Q:

.xlsx downloading issue

I have generated .xlsx reports on server, and page with direct links to these reports.
When user clicks a link, report file is downloaded, but file extension is changed to .xls.
Therefore, I can't open file correctly, only after changing of extension.
Problem occurs in IE, Firefox correctly downloads file, and Chrome saves file with name "File.xlsx.xls"
What can cause such behaviour? Any help appreciated.

A:

Problem fixed with setting of mime-type "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" for .xlsx files


Q:

How to listen to children elements events in a directive?

Since there is no template, what's the best way to listen to child elements event in a directive? Is it possible with HostListener? If not, is there any other way?
There's also this similar question: How to listen for child event from parent directive in Angular2, but the suggested approach does not solve my problem, as my directive and child element aren't in the same template (directive is on host).
Cheers!
Edit #1
This is how I'm currently doing it (there has to be a better way):
First injecting ElementRef into my directive:
constructor(private elView: ElementRef) {}

Then binding with jQuery (or plain JS):
$(this.elView.nativeElement)
.on('drag', '#childId', this.slide.bind(this))

A:

If the event you want to listen to is a native DOM event that bubbles, then you can just use @HostListener()
@HostListener('click', ['$event'])
handleClick(event) {
  // handle event
}

If they are outputs of child components, you can query them and subscribe to their outputs
@ContentChildren(ChildComponent) children:QueryList<ChildComponent>;

ngAfterContentInit() {
  this.children.toArray().forEach((item) => {
    item.someOutput.subscribe(...);
  });
}

or you can use the approach used in the answer you linked to in your question.


Q:

Spy on Backbone.js View Functions with Jasmine

I'm trying to write a Jasmine spec to verify that a view's function is called when a model is added to the view's collection.
In the view's initialize function I do
this.collection.on('add', this.fooAdded, this);

In my Jasmine spec I'm doing:
describe('Foo View', function() {
   it('should call fooAdded when a Foo is added', function() {
      var view = new FooView({collection: new FooCollection()});
      spyOn(view, 'fooAdded').andCallThrough();
      view.delegateEvents();
      view.collection.add({name: 'foo'});
      expect(view.fooAdded).toHaveBeenCalled();
   });
});

My implementation of fooAdded() logs something to the console, so I know it's being called. However the spy doesn't see that the fooAdded() has been called.
See my jsFiddle

A:

Your problem is that spyOn replaces the spied on function with a new wrapper function but you're replacing it after the function has been used. By the time you call spyOn(view, 'fooAdded') to attach your spy, a reference to the original fooAdded is already in the collection's listener list so it is too late to spy on that callback.
If you spy on the fooAdded in the view's prototype before instantiating your view:
spyOn(FooView.prototype, 'fooAdded');
var view = new FooView(...);
view.delegateEvents();
//...

then things should work better. Demo: http://jsfiddle.net/m5Baw/1/ (thanks to amiuhle for updating the Jasmine links in the demo).
As an aside, I think something strange is going on your view, you shouldn't need to view.delegateEvents() outside the view's code so you might want to have a closer look at that.


Q:

What the terms Basis functions and Orthogonal denote in case of signals?

I am a beginer. I have read that any given signal whether it is simple or complex one,can be represented as summation of orthogonal basis functions.
Here, what the terms Orthogonal and Basis functions denote in case of signals?

A:

If you think of a signal as a function of time $s(t)$ ($t$ could be a continuous variable or a discrete one $t_n$) that satisfies certain criteria, it can be thought of as a vector in some vector space of functions. It depends which vector space you want to use (e.g. $L^2$ or tempered distributions), but as most signals are finite and limited in space and/or time, it's usually safe to assume that they satisfy the criteria.
After that most rules from linear algebra can be used. Most importantly, a vector can be decomposed into a linear combination of basis vectors. An analog of standard basis vectors are shifted $\delta$ functions. If the basis vectors are orthonormal, the coefficients in the linear combination will be scalar products of the basis vector and the vector being decomposed. These coefficients are then known as Fourier coefficients.
So I suggest you revise your knowledge of linear algebra (mainly basis vectors, scalar product) and then try to look at functions as vectors and it will all fall into place.
Edit: to answer the "physical significance" part:
If you can attribute some meaning or behavior to basis functions in your system, then knowing how the signal is composed of them tells you how "similar" (but only in the linear sense of cross-correlation) it is to certain behaviors or patterns.
A common example are the $\sin(mt)$ and $\cos(mt)$ basis functions used in Fourier analysis. In most physical systems they represent oscillation modes and if you can decompose a signal into these modes, you can understand it in terms of oscillation modes. That's pretty much what spectrograms do.
In case of wavelets you can think of them as waveform packets that tell you not only what oscillation mode was present, but also where and/or when.
Edit: an intuitive way to look at functions as vectors:
If you think of a function as a mapping from one set to another (usually $\mathbb{R} \rightarrow \mathbb{R}$), simple array vectors are actually functions that map $\hat n = \{1, \dots, n\}$ onto $\mathbb C$ or $\mathbb R$. So you can imagine continuous functions as vectors that have so many elements that their length becomes infinite and the spacing between the element indices goes to zero, forming a "continuous" vector. This also means that in most formulas in linear algebra summations turn into integrals (they were always integrals, but the integration set was changed from $\hat n$ to $\mathbb R$). Of course, all this is much more complicated if done rigorously, because integrals as infinite sums can introduce infinite results.
It's a little simpler with finite discrete signals of length $N$ because then it's simple to look at them as array vectors of length $N$. However, any formulas derived for continuous signals might introduce edge defects.


Q:

How to find all the roots of $xe^{-x}=A$

I am trying to find all the roots of the equation $xe^{-x}=A$.
I tried using LambdertW function. I used
$-xe^{-x}=-A$
Solution is $x = -LW(-A)$, where $LW$ is the Lambertw finction.
As $-xe^{-x}$ is negative, decreases intially and then increases close to zero, there will two roots corresponding to -A.
When I use the lambertW function in matlab, I am only able to get one root out of the two roots.
Is there any way to get both the roots?

A:

According to the documentation: https://www.mathworks.com/help/symbolic/lambertw.html, the syntax for both roots should be lambertw(0,k) and lambertw(-1,k), as the description says:

lambertw(k,x) is the kth branch of the Lambert W function. This syntax returns real values only if k = 0 or k = -1.


Q:

Removing duplicates from a DoublyLinkedList

I'm trying to remove duplicate items in C++.  I've managed to get the object to = null by using the objects default constructor.  But I am unable to completely remove it from the list.  This code also deletes the two objects rather than just one. This is a re-post from another question.  My code and partially my post has changed.How to remove duplicates from a doubly linked list by full name. Can anyone help me with this?  Here is my removeDuplicates function:
***Remove Duplicates***
    void RemoveDuplicates(DoublyLinkedListIterator<Datatype> m_itr, string searchByFirstName, string searchBySecondName)
    {
        for (m_itr.Start(); m_itr.Valid(); m_itr.Forth())
            {
                if ((m_itr.Item().getFirstName() == searchByFirstName )
                          && (m_itr.Item().getSecondName() == searchBySecondName))
                {
                    for (m_itr.Item(); m_itr.Valid(); m_itr.Forth())
                    {
                        if ((m_itr.Item().getFirstName() == searchByFirstName )&&
                            (m_itr.Item().getSecondName() == searchBySecondName))
                                {
                                    m_itr.Item() = Stats();
                                }
                    }
                }
            }
        delete m_itr.Item();
    }
***Remove***
    void Remove(DoublyLinkedListIterator<Datatype> m_itr)
        {
            query.clock1();
            DoublyLinkedListNode<Datatype>* node = m_head;
            //Check to see if the iterator belongs to this list, if not return nothing.
            if (m_itr.m_list != this)
                return;
            //Check to see if the node is valid, if not return nothing.
            if (m_itr.m_node == 0)
                return;
            //If the iterator is pointing to the head...
            if (m_itr.m_node == m_head)
            {
                //Move the iterator forward.
                m_itr.Forth();
                //Delete the head.
                RemoveHead();
                //Decrement the size.
                m_count--;
            }
            //If the iterator is not pointing to the head...
            else
            {
                //Search forward through the list until you find
                //the node prior to the node you want to remove.
                while (node->m_next != m_itr.m_node)
                node = node->m_next;
                // move the iterator forward.
                m_itr.Forth();
                //If the node being are deleted is the tail...
                //Then update the tail node.
                if (node->m_next == m_tail)
                {
                    //Tail is now equal to node.  Which means we can now delete the node.
                    m_tail = node;
                }
                //Delete the node.
                delete node -> m_next;
                //Relink the list.
                node -> m_next = m_itr.m_node;
                //Decrement the count because a node was removed.
                m_count--;
                query.clock2();
                cout << "\nTime Taken : " << query.time2 - query.time1 << "\n";
            }
        }

***Class Declarations***
template <class Datatype>
class DoublyLinkedList
{
public:
//-------------------------------------------------------------------------------------------
//  Member Vairables.
//-------------------------------------------------------------------------------------------
DoublyLinkedListNode<Datatype>* m_head;
DoublyLinkedListNode<Datatype>* m_tail;
int m_count;

template<class Datatype>
class DoublyLinkedListNode
{
public:
//-------------------------------------------------------------------------------------------
//  Member Vairables.
//-------------------------------------------------------------------------------------------
    DoublyLinkedListNode<Datatype>* m_next; //The next node.
    DoublyLinkedListNode<Datatype>* m_prev; //The previous node.
    Datatype m_data;                        //The data in the node.

template <class Datatype>
class DoublyLinkedListIterator
{
public:
//-------------------------------------------------------------------------------------------
//  Member Vairables.
//-------------------------------------------------------------------------------------------
    DoublyLinkedListNode<Datatype>* m_node; //A node for the Iterator to pointn to.
    DoublyLinkedList<Datatype>* m_list;     //A list for the Iteraotor to go through.
//-------------------------------------------------------------------------------------------
//  Name:           Constructor.
//  Description:    Constructs the DoublyLinkedListIterator.
//-------------------------------------------------------------------------------------------
    DoublyLinkedListIterator(DoublyLinkedList<Datatype>* p_list= 0, DoublyLinkedListNode<Datatype>* p_node= 0)
    {
        m_list= p_list;
        m_node= p_node;
    }

// ------------------------------------------------------------------
//  Name:           Start
//  Description:    Resets the iterator to the beginning of the list.
//  Arguments:      None.
//  Return Value:   None.
// ------------------------------------------------------------------
    void Start()
    {
        if(m_list!= 0)
        m_node= m_list -> m_head;
    }

// ----------------------------------------------------------------
//  Name:           End
//  Description:    Resets the iterator to the end of the list.
//  Arguments:      None.
//  Return Value:   None.
// ----------------------------------------------------------------
    void End()
    {
        if(m_list!= 0)
        m_node = m_list->m_tail;
    }

// ----------------------------------------------------------------
//  Name:           Forth
//  Description:    Moves the iterator forward by one position.
//  Arguments:      None.
//  Return Value:   None.
// ----------------------------------------------------------------
    void Forth()
    {
        if(m_node != 0)
        {
        m_node = m_node ->m_next;
        }
    }

// ----------------------------------------------------------------
//  Name:           Back
//  Description:    Moves the iterator back by one position.
//  Arguments:      None.
//  Return Value:   None.
// ----------------------------------------------------------------
    void Back()
    {
        if(m_node!= 0)
        m_node = m_node->m_prev;
    }

// ----------------------------------------------------------------
//  Name:           Item
//  Description:    Gets the item that the iterator is pointing to.
//  Arguments:      None.
//  Return Value:   Reference to the data in the node.
// ----------------------------------------------------------------
    Datatype& Item()
    {
        return m_node->m_data;
    }
//-----------------------------------------------------------------
//  Name:           Valid
//  Description:    Determines if the node is valid.
//  Arguments:      None.
//  Return Value:   true if valid.
// ----------------------------------------------------------------
    bool Valid()
    {
        return (m_node!= 0);
    }
};

A:

Use the DoublyLinkedList's built-in Remove function and pass it the iterator. The delete call is the bare bones C++ variant which doesn't deal with the deletion of nodes and re-linking the list properly. The call to delete only removes what's in the node, not the node itself!
Remove(m_itr);

Instead of
delete m_itr.Item();

Also, I think the place of your deletion might be off (you will always delete the last item, it seems). Maybe you want to do something like below. Not sure what Stats() does, but hopefully you'll get the idea. Basically you need to put away the item to delete, step forward the regular iterator and then remove the one you put away. Alternatively, stop the iteration completely once removal is complete. This is needed because when the iterator gets removed, it can't be used for further iterating.
    if ((m_itr.Item().getFirstName() == searchByFirstName ) &&
        (m_itr.Item().getSecondName() == searchBySecondName))
    {
      DoublyLinkedListIterator<Datatype> toDelete = m_itr;
      m_itr.Forth();
      Remove(toDelete);
    }


Q:

Component not reloading but state is changing with useState

I'm not new to react, but im new using hooks, today I was playing with an array of selected elements and selection/unselection.
If they are selected then one icon is shown, if not, another icon (I just change the name prop, not the component itself.
The console.log I do every render shows the right results, but it is not working as expected on the JSX.
The render seems to only reload (Show the right icon) when I unselect. Explaining as a list the procedure and my problem:

All elements come selected
I unselect one element (remove from list), the icon changes.
I select back the element (add to list), the icon don't change.
I unselect another element, then it works and the components are
reloaded

Here is my object array:
const dies = [
  {
    id: 1,
    nomDia : 'Dies',
    dataDia : 'previs'
  },
  {
    id: 2,
    nomDia : 'Dies',
    dataDia : 'previs'
  },
  {
    id: 3,
    nomDia : 'Dies',
    dataDia : 'previs'
  }
]

Here is the useSate declaration:
const [diesSeleccionats, setDiesSeleccionats] = useState(dies)

Here is the functions that check if is selected and the function that adds/removes from selected list:
// check if selected
const estaSeleccionat = (dia) => {
    return diesSeleccionats.findIndex((aDia) => aDia.id === dia.id ) != -1
  }
// remove selected or add selected
const gestionarSeleccionats = (dia) => {
    if(estaSeleccionat(dia)){
      return diesSeleccionats.filter((aDia) => aDia.id !== dia.id)
    } else {
      diesSeleccionats.push(dia)
      return diesSeleccionats
    }
 }

Here is the component:
   dies.map((dia) => (
                      <View key={dia.id} style={{flexDirection: 'row', marginTop: 5, alignSelf: 'flex-end'}}>
                        <TouchableOpacity
                          style={{backgroundColor: Colors.llistat1 + 'CC'}}
                          key={dia.id}
                          onPress={() => setDiesSeleccionats(gestionarSeleccionats( dia ))}
                        >
                            <Text style={{fontSize: 18, color: Colors.titolsPantalles}}> {dia.nomDia} </Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                          style={{
                            minWidth: 24,
                            backgroundColor: Colors.llistat1 + 'CC',
                            marginLeft: 5,
                            paddingHorizontal:5,
                            justifyContent:'center', alignItems: 'center'}}
                          onPress={ () => setDiesSeleccionats(gestionarSeleccionats( dia ))}
                          >
                          <Ionicons name={ estaSeleccionat( dia ) ? "md-checkmark" : "md-close"} size={18} color={Colors.titolsPantalles} />
                        </TouchableOpacity>
                      </View>
                    ))

You can see than <Ionicons> name comes defined by if the element is on the selected list.
The log I do every re-render shows the right results. (Boolean of the check function, and the right elements on the array of objects)
Thanks.

A:

I think the issue is related to mutating diesSeleccionats instead of copying it. I think you need to make a copy of it to provide to setDiesSeleccionats so React can analyze the differences and render the correct updated state.
const gestionarSeleccionats = (dia) => {
    const selections = [...diesSeleccionats];
    if(estaSeleccionat(dia)){
      return selections.filter((aDia) => aDia.id !== dia.id);
    } else {
      selections.push(dia)
      return selections;
    }
 }


Q:

Nicely formatted text file

I’m writing to a text file and it looks like this...

19/05/2010 15:33:34   Verbose Main    in main method
19/05/2010 15:33:34   Information DoesSomethingInteresting()  the answer to faster than light travel is

But what i’d like it to look like is...

19/05/2010 15:33:34   Verbose     Main                        in main method
19/05/2010 15:33:34   Information DoesSomethingInteresting()  the answer to faster than light travel is

You know, so it's all nicely formatted and tabbed aligned. Is there an easy way to do this, some function in the runtime that will deal with all the tedious padding?
Here is my code that does the writing
LogFile.Write(string.Format("{0}\t{1}\t{2}\t{3}", log.Time, log.Level, log.Method, log.Message));

A:

To align a string to the left use formatting pattern with comma (,) followed by a negative number of characters:
LogFile.Write(string.Format("{0,-10} {1,-11} {2,-30} {3}", ...));

For right alignment use a positive number.


Q:

Setting active status of checkboxes depending on value

i'm creating a filtering system and I recently started using radio boxes instead of just buttons. The problem I have right now is that I'm refreshing all the button states when the user clicks on a button, but the button they actually clicked doesn't become active. If I click another button it does become active.
The whole thing, exactly how it misbehaves on my actual site, is here.
JS and jQuery for setting active buttons and filters:
var filters = {
    'period_months': [],
    'period_years': [{filter_value: 2013, filter_display: "2013"}],
    'period_quarters': [{filter_value: 1, filter_display: "Q1"}]
};
draw();
$(".filter_toggle").click(function(e) {
    var key = $(this).children('input').data('filterKey');
    var value = $(this).children('input').data('filterValue');
    var display = $(this).children('input').data('filterDisplay');
    if (key === "period_months") {
        filters['period_years'] = [];
        filters['period_quarters'] = [];
    } else if ((key === "period_years") || (key === "period_quarters")) {
        filters['period_months'] = [];
    }
    toggle(key,value,display);
});
function toggle(filter_key,filter_value,filter_display) {
    var filter_exists = false;
    for (var i in filters[filter_key]) {
        if (filters[filter_key][i]['filter_value'] == filter_value) {
            filter_exists = true;
            filters[filter_key].splice(i,1);
            break;
        }
    }
    var filter_in = { filter_value: filter_value, filter_display: filter_display };
    if (!filter_exists) {
        filters[filter_key] = [];
        filters[filter_key].push(filter_in);
    }
    draw();
}
function draw() {
    $('input').prop("checked",false).parent(".btn").removeClass("active").attr("aria-pressed",false);

    for (i in filters) {
        for (k in filters[i]) {
            $("*[data-filter-key="+i+"][data-filter-value="+filters[i][k]['filter_value']+"]")
            .prop("checked",true)
            .parent(".btn")
            .addClass("active")
            .attr("aria-pressed",true);
        }
    }
}

In the case of period_* filters, one year and one quarter can go together. If you set months or range, every other period is unset.
All of the above works fine when I set the states on page load, but doesn't when I click a new filter. The rest of the code is in the fiddle, including on click events and such.

A:

If I understand correctly, this could be the solution
UPDATE:
function clearMonths() {
    $('#period_months .filter_toggle').removeClass('active');
    $('#period_months input').prop("checked", false)
}

function clearYears() {
    $('#period_years .filter_toggle').removeClass('active');
    $('#period_years input').prop("checked", false)
}

function clearQuarters() {
    $('#period_quarters .filter_toggle').removeClass('active');
    $('#period_quarters input').prop("checked", false)
}

$(".btn-group").click(function (e) {

    if ($(this).attr('id') == 'period_months') {
        clearYears()
        clearQuarters()
        clearMonths()
    }

    if ($(this).attr('id') == 'period_years') {
        clearMonths();
        clearYears();
    }

    if ($(this).attr('id') == 'period_quarters') {
        clearMonths();
        clearQuarters()
    }

    $(this).find('label:active input').prop("checked", true);

});

http://jsfiddle.net/25v4m6ue/5/


Q:

Minimal values of cell arrays in MATLAB

I have a cell array in MATLAB which contains some matrices in a descending size order (e.g. [512x512 double] [256x256 double] [128x128 double] etc).
Now I want to find and wipe (turn into zeros) the 100 smallest elements in the matrices in the cell array altogether (not in each matrix individually). For example, the smallest element might be in the 128x128 matrix, the next in the 512x512 matrix and so on.
How can I do it most efficiently?
The next is my super-slow code for the case of three such cell arrays - H,D,V (percent2zero is a parameter for the percent of elements to wipe from the whole cell array):
details=[H;D;V];
for k=1:3
    numOfLevels=length(details(k,:));
    TotalCoeffs=0;
    minimalInEachLevel=zeros(1,numOfLevels);
    for i=1:numOfLevels
        temp=cell2mat(details(k,i));
        TotalCoeffs=TotalCoeffs+numel(temp);
        minimalInEachLevel(i) = min(min(abs(temp)));
    end
    CoeffsToBeRemoved=percent2zero*TotalCoeffs/100;
    for i=1:CoeffsToBeRemoved
        for j=1:numOfLevels
            temp=cell2mat(details(k,j));
            minimalInEachLevel(j) = min(min(abs(temp)));
        end
        [val,ind]=min(minimalInEachLevel);
        temp=cell2mat(details(k,ind));
        temp(find(abs(temp==val),1))=0;
        details(k,ind)=mat2cell(temp,size(temp,1),size(temp,2));
    end
end

A:

One thing I can suggest is to place every single value over all matrices into a single 1D vector, sort the vector and choose the 100 smallest values.  Use cellfun and sort to do this first step.  The logic behind this is that if we collect all of the values over all matrices and place them into a single vector then sort the entire vector, we will choose the 100 smallest values all together as you have mentioned.
Once you find these 100 smallest values, you'll have to loop over each cell then you can use intersect to see if there are any elements in each matrix in the cell array that are common with the 100 smallest values.  You can use the second output of intersect then use this to index into each cell and set the values to 0.  Because you're dealing with cells and each cell is a different size, looping is the only option.
Something like this comes to mind.  This is assuming that details is a cell array where each cell is a matrix:
%// Create single 1D vector of all values
vals = cellfun(@(x) reshape(x, [], 1), details, 'uni', 0);
vals = cat(1, vals{:});

%// Sort the UNIQUE values and grab the 100 smallest values
vals = unique(vals);
vals = vals(1:100);

%// Loop through each cell, determine those values that are among
%// the 100 smallest and set to 0
for ii = 1 : numel(details)
    [~,ind,~] = intersect(details{ii}, vals);
    details{ii}(ind) = 0;
end

unique finds the unique values in an array or matrix but also has the added bonus of sorting the unique values too.  Therefore, this code will find the 100 smallest and unique values to process your cell arrays.


Q:

Adobe Illustrator CS4 Intersection vs Adobe Illustrator CS6 Intersection

I hope you can help me. I work for a graphic design studio and we have recently upgraded to Adobe CS6. One of our designers who works heavily with Illustrator.
He has noticed, when intersecting two lines that, unlike Adobe CS4 (which we have also tested as a comparison) the two lines don't seem to 'snap'. They do not connect like Adobe CS4 did and always seem to jump about a pixel out.
This is a screenshot of the result when intersecting in CS6 -

Does anyone have any ideas why this is happening? I hope you can help!

A:

There are several things to check regarding snap.

Snap to Point (View Menu)
Snap to Grid (View Menu)
Smart Guides (View Menu)
Align to Pixel Grid (Transform Panel)

Any one of the above can alter snapping behavior. If moving from CS4, the mo0st likely change will be the Align to Pixel Grid option on the Transform Panel. This will cause snapping to the nearest pixel in order to help produce sharper lines for on-screen/web projects. However, if you aren't working on a project where screen sharpness is desired, it can cause an undesired snap. Simply select objects and uncheck the option on the Transform Panel. and when creating a new document, be certain the option to "Align New Objects to Pixel Grid" is not checked there as well.


Q:

How to display title in the center of navigation bar without using padding-left

I want to center the "title123" div element without using padding-left. I have tried fidgeting around with the css as you can see below but the title remains on the left end of the navigation bar. Any help/advice would be appreciated!
Code below:
<nav class="navbar fixed-top navbar-expand-lg" style="background-color:black">
        <div class="title123">
            Title
        </div>
    </nav>

.title123 {
    font: bold;
    font-family: "Arial Black", Gadget, sans-serif;
    font-size: 28px;
    color: ghostwhite;
    display: block;
    text-align: center;
    float:right;
    vertical-align: top;
}

A:

.navbar {
  display: block;
  text-align:center;
}

.title123 {
    font: bold;
    font-family: "Arial Black", Gadget, sans-serif;
    font-size: 28px;
    color: ghostwhite;
    display: inline-block;
    text-align: center;
}


Q:

Refresh activity on phone wakeup?

In the case where the user suspends the phone when an activity is shown, and then later resumes the phone with the activity shown, I'd like to refresh the data.  But the onStart() does not get called in this case.  Is there an equivalent event to override for this case?

A:

onResume?
 @Override
    protected void onResume()
       {
         super.onResume();
        //stuff that needs to be restarted
 }


Q:

Remove, or change color of the safe area at the bottom of the View in SwiftUI

Here is the screen shot:

The code to the view is as follows:
struct ViewDetails: View {

    @EnvironmentObject var displayDetails: DisplayDetails

    var body: some View {

        ScrollView {

            GeometryReader { geometry in

                ZStack {

                    if geometry.frame(in: .global).minY <= 0 {

                        Image("header")
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: geometry.size.width, height: geometry.size.height)
                            .offset(y: geometry.frame(in: .global).minY/9)
                            .clipped()

                    } else {

                        Image("header")
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: geometry.size.width, height: geometry.size.height + geometry.frame(in: .global).minY)
                            .clipped()
                            .offset(y: -geometry.frame(in: .global).minY)

                     }

                }

            }.frame(height: 400)

            VStack(alignment: .leading) {

                HStack {

                    Image("author")
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: 60, height: 60)
                        .clipped()
                        .cornerRadius(10)

                    VStack(alignment: .leading) {

                        Text("Article by")
                            .font(.custom("AvenirNext-Regular", size: 15))
                            .foregroundColor(.gray)

                        Text("John Doe")
                            .font(.custom("AvenirNext-Demibold", size: 15))

                    }

                }.padding(.top, 20)

                Text("Lorem ipsum dolor sit amet")
                    .font(.custom("AvenirNext-Bold", size: 30))
                    .lineLimit(nil)
                    .padding(.top, 10)

                Text("3 min read • 22. November 2019")
                    .font(.custom("AvenirNext-Regular", size: 15))
                    .foregroundColor(.gray)
                    .padding(.top, 10)

                Text(articleContent)
                    .font(.custom("AvenirNext-Regular", size: 20))
                    .lineLimit(nil)
                    .padding(.top, 30)

            }
            .frame(width: 350)

        }
        .edgesIgnoringSafeArea(.all)

            .onAppear(perform: {

                self.displayDetails.showFullScreen.toggle()

            })

    }

}

So I'm not sure if I can remove whatever is displaying as gray/white at the bottom or if I can change the color for it, either way works for me but I am unable to achieve it!? Can anyone help.

A:

I changed your code a little and ran it on the simulator. The only change is just adding .background(Color.yellow) before .edgesIgnoringSafeArea(.all). Here is the full code snippet with result:
struct ViewDetails: View {

    var body: some View {

        ScrollView {

            GeometryReader { geometry in

                ZStack {

                    if geometry.frame(in: .global).minY <= 0 {

                        Image("hp")
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: geometry.size.width, height: geometry.size.height)
                            .offset(y: geometry.frame(in: .global).minY/9)
                            .clipped()

                    } else {

                        Image("header")
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: geometry.size.width, height: geometry.size.height + geometry.frame(in: .global).minY)
                            .clipped()
                            .offset(y: -geometry.frame(in: .global).minY)

                     }

                }

            }.frame(height: 400)

            VStack(alignment: .leading) {

                HStack {

                    Image("author")
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: 60, height: 60)
                        .clipped()
                        .cornerRadius(10)

                    VStack(alignment: .leading) {

                        Text("Article by")
//                            .font(.custom("AvenirNext-Regular", size: 15))
                            .foregroundColor(.gray)

                        Text("John Doe")
                            .font(.custom("AvenirNext-Demibold", size: 15))

                    }

                }.padding(.top, 20)

                Text("Lorem ipsum dolor sit amet")
//                    .font(.custom("AvenirNext-Bold", size: 30))
                    .lineLimit(nil)
                    .padding(.top, 10)

                Text("3 min read • 22. November 2019")
                    .font(.custom("AvenirNext-Regular", size: 15))
                    .foregroundColor(.gray)
                    .padding(.top, 10)

                Text("articleContent")
                    .font(.custom("AvenirNext-Regular", size: 20))
                    .lineLimit(nil)
                    .padding(.top, 30)

            }
            .frame(width: 350)

        }
        .background(Color.yellow)
            .onAppear(perform: {

            //                self.displayDetails.showFullScreen.toggle()

                        })
        .edgesIgnoringSafeArea(.all)

    }

result:

P.S: There are lots of unnecessary details in your code snippets, so it's hard to analyze it =(


Q:

How to change the font size and color of a Telerik MVC Chart title?

Can it be done? I did a lot of research and couldn't find anything.
Thanks

A:

It seems that there isn't any settings for that in the Chart API, but what when I inspected Telerik ASP.NET MVC demo page I found out the text element that is used on the title.
With some JavaScript you could change the title font size and color easily.

This is a jQuery example:
$('#chart').find('text:nth(0)').css('font-size', '30px').css('text', 'red')

First I'll get the chart control with id and then find the title which is the first text element. Then I'll place my own css styling.
This isn't the optimal way to do this and it is basically a hack, but if nothing else cannot be done then this might be your solution.


Q:

log4j debug is not working in Jboss 7.1

I have Enterprise Java Project with Jboss 7.1.
I've added log4j for my EAR.
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
     <version>1.2.17</version>
</dependency>

now , logger.error() works well.  but logger.debug is not working. What do you think about this?.. how to enable debug?
@Startup
@Stateless
import org.apache.log4j.Logger;
public class MyClass{

    public static final Logger logger = Logger.getLogger(MyClass.class.getSimpleName());

    @PostConstruct
    private void invoke() {
           logger.error("error ");
       logger.debug("debug");
        }
}

A:

Jboss has it's own binder which can not be overridden runtime, pls ensure you have added log4j.properties with proper debug level. try to use fileappender in it so that you will come to whether Jboss is using your log4j binder or it's own.


Q:

Why CKEditor does not care about compatibility?

I implemented CKEditor on a project and I was surprised to discover, either in the interface or in the source code, that it's written in ECMA 6, using all its modern features such as the short function notation (arrow functions).
Given these features are not widely supported as the ECMA 5 version is (not yet as of today, July 2018), I ask why the developers made this strategic choice: are they not interested in a wide browser compatibility? Or is CKEditor so well spread to allow them to dictate a precise direction towards modern browser versions, risking to lose a portion of users?

A:

Browsers are not a problem
Let's be clear here:
CKEditor 5 can be run in all browsers which it supports without any transpilation. All browsers which it supports have a sufficient level of ES6 support.
Why would you need ES5?
The only reason why you might want to transpile CKEditor 5 from ES6 to ES5 are:

Legacy browsers which it doesn't support (at least at the moment).
Existing setups which use ES6-incompatible JS minifiers (UglifyJS). It may be a bit inconvenient to include CKEditor 5 in such applications but, as it was commented already, we explain how to transpile CKEditor 5 to ES5.
Development environments for frameworks like React (create-react-app) or Angular (angular-cli) which didn't catch up yet and still require that libs kept in your node_modules/ are in ES5.

The last case is indeed a bigger problem because you don't have that much control over this environments as on your own projects. As I commented on Twitter:

3 years ago we decided that CKEditor 5 will be released in ES6 because all browsers which we planned to support should have a sufficient ES6 support by our ETA.
We were right – it worked great... in the browsers.
It turned out that the problem is in the build environments (create-react-app, angular-cli) which did not catch up.
We'll need to introduce ES5 builds just to satisfy these envs ;/
To clarify – I'm not criticising authors of these tools. It's more of an observation that we've been always worried about browser support while today the tools stop us.
And, as I mentioned in the other tweet, the problem is broad (e.g. finding a supported, stable, ES6+ compatible and fast minifier – see e.g. https://github.com/webpack-contrib/uglifyjs-webpack-plugin/issues/262 …).

Fortunately, the situation is improving:
@mtrebizan:

I think CRA 2.0 will be shipping non-transpiled code,just don't know how far release is. cc @dan_abramov

@dan_abramov:

There’s alphas you can try. Other than that the ETA is when the community makes it happen  there’s active work and you can help too

I know there was work in angular-cli on improving this situation too. So, in a relatively short time, all should work smoothly too.
Time aspect
The difference (in terms of features) between ES6 and ES5 is huge. Back in 2014, when we've been starting CKEditor 5 development, we chose ES5. ES6 wasn't standardised yet.
However, the situation changed in 2015. ES6 got published and our tests proved that all features we looked to (classes, generators, iterators, weak sets, weak maps, and more) were already available in Chrome. We decided to go for it and see.
About 1.5 year later CKEditor 5 worked natively (without any transpilation) in all modern browsers (with the exception of Safari which had a nasty bug). At the same time, babel-minify became usable so we didn't have to transpile CKEditor 5 to ES5 even for production.
It's 2018 and the number of obstacles was reduced even more. There's a chance that still this year you won't have to transpile CKEditor 5 to ES5 unless your project is supposed to be ES5 because of browser support (but then, why would you include CKEditor 5? it's not going to work in those browsers anyway).
Looking at the history of CKEditor 3-4, CKEditor 5 will stay with us for the next 8+ years. So, we're talking here about 2026+. This means that for the vast majority of its lifetime ES6 will not be a problem.

A:

CKEditor supports vanilla javascript (ES5) and ES6 as well. The issue is not the editor, it just supports it, doesn't care about compatibility because it doesn't know where your code is going to run but only how to highlight and give you tools to develop it.
The thing is that, by the time, the ECMA standard is under heavy development, improving in every version, so there's a lot going on, there are a lot of proposals being added every month, some passes and makes their way into the standard, which later gets into cool features we can use like arrow function.
All of that makes it harder for browsers to catch on the new updates. Even so, there are a lot that supports the new features now (you may track the updates in that page).
Anyway, besides from all of that, you may use a code compiler like Babel (which compiles ES6/ES7... down to code the browsers can understand such as ES5). It's widely adopted, and recommended for the thing it does: Make your life easier. Many big companies adopted it, such as Facebook which uses react (and made it) using Babel to compile not only ES6 but JSX (check this).

Side note: Why should I use ES6 if I need a compiler?
https://itnext.io/why-you-should-use-es6-56bd12f7ae09


Q:

Rspec false positive because failure exception is rescued in code being tested

I have an rspec test that I expect to fail, but it is passing because the code that it is testing rescues the exception that rspec raises. Here's an example of the situation:
class Thing do

  def self.method_being_tested( object )
    # ... do some stuff

    begin
      object.save!
    rescue Exception => e
      # Swallow the exception and log it
    end
  end

end

In the rspec file:
describe "method_being_tested" do
  it "should not call 'save!' on the object passed in" do
    # ... set up the test conditions

    mock_object.should_not_receive( :save! )
    Thing.method_being_tested( mock_object )
  end
end

I knew that the execution was reaching the "object.save!" line of the method being tested, and the test should therefore be failing, but the test passes. Using the debugger in the rescue block, I find the following:
(rdb:1) p e # print the exception object "e"
#<RSpec::Mocks::MockExpectationError: (Mock "TestObject_1001").save!
    expected: 0 times
    received: 1 time>

So basically the test is failing but, but the failure is being suppressed by the very code it is trying to test. I cannot figure out a viable way to stop this code from swallowing Rspec exceptions without somehow compromising the code. I don't want the code to explicitly check if the exception is an Rspec exception, because that is bad design (tests should be written for code, code should never be written for tests). But I also can't check that the exception is any particular type that I DO want it to catch, because I want it to catch ANYTHING that could be raised in a normal production environment.
Someone must have had this problem before me! Please help me find a solution.

A:

Assuming the code is correct as-is:
describe "method_being_tested" do
  it "should not call 'save!' on the object passed in" do
    # ... set up the test conditions
    calls = 0
    mock_object.stub(:save!) { calls += 1 }
    expect {Thing.method_being_tested(mock_object)}.to_not change{calls}
  end
end

If there's no need to catch absolutely all exceptions including SystemExit, NoMemoryError, SignalException etc (input from @vito-botta):
begin
  object.save!
rescue StandardError => e
  # Swallow "normal" exceptions and log it
end

StandardError is the default exception level caught by rescue.


Q:

Left outher join count rows from different table minus value different row

Hello I have following SQL query
SELECT K.name AS Name, K.surname AS Surname, U1.akce AS Event,
U2.[text] AS [Scheme], U1.[text]  AS [Registered under>],
( U1.x - (
    SELECT Count(K.ubytov)
    FROM klient
    WHERE ubytov = U2.[text]) ) AS [Free space]
      FROM klient K
      INNER JOIN ubytov U1 ON U1.[text] = K.ubytov
      LEFT OUTER JOIN ubytov U2 ON U1.z = U2.id WHERE U1.akce = '140012-02'
    ORDER BY U1.[text]

I'm trying to achieve that in column Free space would be (value from ubytov.x that matches U1.z = U2.id) - (total number of rows from table klient that has the same value in U1.[text]=K.ubytov)
In table klient column ubytov I have values that matches ubytov.text and in ubytov.z I have value that matches ubytov.x in different row.
Would somebody help me solve this out please?
Thank you for your time.
An example:
Table klient
ID_K ubytov

1   RoomOwner

2   RoomOwner

table ubytov
id text x z

1 roomType1 2 NULL

2 RoomOwner NULL 1

Desired Output:
Name Surname Event Scheme Registered under: Free space

Nam1 Surname1 Even1 Scheme1 RoomOwnerName  0 // (because 2 counts from klient) - (roomType1 x)

A:

Although, it wasn't much clear because of missing columns.
I tried to build the required query using a CTE expression.
Here is the sqlfiddle code.
Let me know, if this is what you are looking for.
   create table klient
   (
     id_k int,
     ubytov varchar(25)
   )
   go

   create table ubytov
   (
     id int,
     text varchar(25),
     x int null,
     z int null
   )
   go

   insert into klient(id_k, ubytov)
   select 1, 'RoomOwner'
   union select 2, 'RoomOwner'
   go

   insert into ubytov(id, text, x, z)
   select 1, 'roomType1', 2, null
   union select 2, 'RoomOwner', null, 1
   go

   ;WITH cte_klint_counts_by_ubytov
   AS
   (
      SELECT
         ubytov,
         Count(ubytov) AS ubytovCount
       FROM klient
       GROUP BY ubytov
   )
   SELECT
     U2.[text] AS [Scheme],
     U1.[text] AS [Registered under>],
     (isnull(U1.x, 0) - isnull(c.ubytovCount, 0)) AS [Free space]
   FROM
     klient K
     INNER JOIN ubytov U1 ON U1.[text] = K.ubytov
     LEFT OUTER JOIN ubytov U2 ON U1.z = U2.id
     LEFT OUTER JOIN cte_klint_counts_by_ubytov c ON c.ubytov = U2.[text]
   ORDER BY u1.[text]


Q:

何もかも and 全部 usages

What's the difference in using 何もかも and 全部?
Eg:
何もかも捨てる
全部捨てる
I have also seen:
何もかも全部捨てる
What are the differences and when should I use them

A:

全部 just objectively says that the statement applies to "all" the things concerned.
何もかも is more emphatic, in that it suggests the statement applies to all the things concerned, whatever or whichever it may be. It's kind of like "whatsoever" in English, except it can be used by itself.
Using both, as in 何もかも全部捨てる, is like in English saying "any...whatsoever"


Q:

Django app on Elastic Beanstalk can't connect to RDS

I have a Django app running on Elastic Beanstalk that is throwing the following error:
[:error] [pid 12271] (2003, "Can't connect to MySQL server on 'xxxxxxxx.xxxxxxxxxxx.us-east-1.rds.amazonaws.com' (110)")

I have no issue connecting to the EB server via ssh and then connecting to MySql:
mysql -uadmin -p -hxxxxxxxx.xxxxxxxxxxx.us-east-1.rds.amazonaws.com

So I've ruled out that its a firewall issue, or problems with my VPC.  I've also tried hardcoding the credentials in the settings.py file to rule out issues with the ENV vars.  I don't know much about Django so any help would be appreciated.

A:

I was missing some packages for my .ebextensions, I added:
packages:
  yum:
    gcc: []
    mysql: []
    mysql-devel: []
    python-devel: []


Q:

Java JList Not Updating

Why isn't my JList updating?
I re-instantiate the list object.  I repaint and revalidate... What's going wrong?
needmoredetailsneedmore
External class:
                ControlPanel.usernames.add(username);
            ControlPanel.list = new JList(ControlPanel.usernames.toArray());
            ControlPanel.panel.repaint();
            ControlPanel.panel.revalidate();

ControlPanel.java
package main;

import java.awt.BorderLayout;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

@SuppressWarnings("serial")
public class ControlPanel extends JFrame {

public static JPanel panel = new JPanel();
JScrollPane scrollpane;
static JLabel players;
static String s;
public static ArrayList<String> usernames = new ArrayList<String>();
public static JList list;

// public static String categories[] = {};

public ControlPanel() {
    list = new JList(usernames.toArray());
    scrollpane = new JScrollPane(list);

    panel.add(scrollpane, BorderLayout.CENTER);
    add(panel);

    setTitle("RuneShadows CP");
    setSize(400, 400);
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}
}

A:

You've created a new JList which has not been added to the screen
Instead, create a new ListModel and set it as the model for the list that's already on the screen
ControlPanel.usernames.add(username);
ControlPanel.list,setModel(new UserNamesListModel(ControlPanel.usernames));
ControlPanel.panel.repaint();
ControlPanel.panel.revalidate();

See How to use lists for more details
Your access model is, frankly, scaring. It allows complete access to everything form anywhere, so any nasty class might come along and completely dismantle your UI, for example.
The use if static is not a solution for easy access and greatly reduces the flexibility of your application over time.
You should be providing simply getters and setters to allow outside classes access to the information contained within and managed by the class.eapqually, you should provide the class's with management functionality that other class might need to use, such as refresh.
No one should care exactly how refresh works, only that it does...
Start by taking a look at How to use lists
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractListModel;

public class UserNamesListModel extends AbstractListModel<String> {

    private List<String> userNames;

    public UserNamesListModel(List<String> userNames) {
        this.userNames = new ArrayList<>(userNames);
    }

    @Override
    public int getSize() {
        return userNames.size();
    }

    @Override
    public String getElementAt(int index) {
        return userNames.get(index);
    }

}


Q:

Git - Auto rebase while pushing

While working on a git project, I want to run a git pull --rebase before each git push. However, some developers in my team often forget to call git pull --rebase before pushing. So, Git/Gerrit automatically performs a merge which creates a malformed commit message.I want to avoid this auto merging.
I want to configure clients git so that when developers run a git push, a git pull --rebase should automatically occurs. Is there any way?

A:

Tell all your developers to add the following to their .git/config files after cloning. Then require all of them to use git goodpush instead of git push.
[alias]
        goodpush = "!git pull --rebase && git push"

This configuration can also be placed inside the .gitconfig file in the user's home directory to avoid doing it for each repository that is cloned.
Note that the name of the alias cannot be push, for reasons discussed here, so you will have to provide some incentives or train your developers to no longer use push directly.
On the plus side, since you get a malformed commit message whenever somebody does use push accidentally, you will immediately know whom to speak with if such a use occurs.


Q:

xcodebuild archive generates malformed xcarchive when adding custom build settings

I'm trying to generate an xcarchive using xcodebuild that I can later export as an .ipa using the new functionality added with Xcode 5.
This works perfectly fine:
xcodebuild -workspace 'MyWorkspace.xcworkspace' -scheme 'MyScheme' -configuration 'Release' -archivePath tmp.xcarchive archive
xcodebuild -exportArchive -exportFormat IPA -archivePath tmp.xcarchive -exportPath app.ipa -exportWithOriginalSigningIdentity

But as soon as I add custom build settings to the archive command:
-derivedDataPath build SYMROOT=build/build.sym DSTROOT=build/build.dst OBJROOT=build/build.obj SHARED_PRECOMPS_DIR=build/build.pch

The .xcarchive generated is empty, but there is no error.
Any ideas?

A:

For me, this had to do with the Installation Directory Deployment Build Setting in Xcode: CMake somehow set this to "", i.e. an empty string, when it should have been "/Applications", the Xcode default. For me, setting it to anything else than "/Applications" caused the resulting archive to be empty and therefore 'malformed'.
So maybe your project somehow did not have Installation Directory set to "/Applications", either because of CMake or something else.
To set this using CMake, add this to your target properties:
set_target_properties(${MODULE} PROPERTIES
     ...
     XCODE_ATTRIBUTE_INSTALL_PATH "/Applications"
     ...
)

A:

For me this error happened when I had no space left on the drive where I tried to create the archive. But I could not tell that from the errors int he console


Q:

In Bash, how can I tell if I am currently in a terminal

I want to create my own personal logfile that logs not only when I log in and out, but also when I lock/unlock my screen. Kindof like /var/log/wtmp on steroids.
To do this, I decided to run a script when I log into Ubuntu that runs in the background until I quit. My plan to do this is to add the script to .bashrc, using ./startlogging.sh & and in the script I will use trap to catch signals. That's great, except .bashrc gets run every time I open a new terminal, which is not what I want for the logger.
Is there a way to tell in Bash that the current login is a gnome login? Alternatively, is there some sort of .gnomerc I can use to run my script?
Edit: Here is my script:
Edit 2: Removed the script, since it's not related to the question. I will repost my other question, rather than repurpose this one.

A:

Are you looking for a way to detect what type of terminal it is?
Try:
echo $TERM

From Wikipedia:

TERM (Unix-like) - specifies the type of computer terminal or terminal
  emulator being used (e.g., vt100 or dumb).

See also: List of Terminal Emulators


Q:

Is there a way to select multiple input field types with CSS?

I have a text and a password input field that I'm trying to select in this fashion:
input[type=text][type=password]

however this does not work. I would refrain from using jQuery, so any help would be appreciated (without using custom classes).

A:

You need to specify the attributes separately, repeating the types if necessary and using comma(s):
input[type=text], input[type=password]

Your given selector is trying to match an input with a type that is both text and password, but a single element can't have different values for the same attribute so it fails.


Q:

how to start two threads at the same time(or at the close time)

I have a class Note and a class Meeting. There is an ArrayList named noteList in class Note. When an object of Meeting is created it is then registered in the noteList.
I just want to demostrate in the main class that two objects of Meeting can be created at the same time (or at the close time). My program is:
public class Note{
    //some field and method hier
    public void add(Meeting m){
        notes.add(m);
    }
    private  static final List<Entry> notes =
        Collections.synchronizedList(new ArrayList<Entry>());
}

public class Meeting implements Runnable{
    public Meeting(Note note_1,Note note_2,Calendar calendar){
        note_1.add(this);
        note_2.add(this);}
        //some method
    }

    public class Test implements Runnable{
        public static void main(String[] args) {
            Note note_1 = new Note();
            Note note_2 = new Note();
            Meeting m_1 = new Meeting(note_1,note_2);
            Meeting m_2 = new Meeting(note_2,note_1)
            Thread t1 = new Thread(m_1);
            Thread t2 = new Thread(m_2)
            t1.start();
            t2.start();
        }
        //t1,t2 are two thread and they start one to one(not at the same time).

I have read anywhere that wait(), notify() or notifyAll() can be used, but they must be used in a synchronized method. I have no synchronized methods in my program.

A:

This is as close as you are going to get to starting the two threads.
What you could do to synchronize the run methods even more is to have them wait on a CountDownLatch on the top of their run methods.
What this does is taking away the overhead of creating and starting Threads (the part that happens before your run method gets executed), and maybe also some freak scheduling oddities. You have no guarantee however, how concurrent the code after the latch will actually be executed.
CountDownLatch latch = new CountDownLatch(2);

Runnable r1 = new Meeting(latch);
Runnable r2 = new Meeting(latch);

// in Meeting

private final CountDownLatch latch;

public void run(){

   latch.countDown();
   latch.await();

   // other code
}

A:

Unfortunately, there is no way to start two threads at the same time.
Let me explain better: first of all, the sequence t1.Start(); and t2.Start(); is executed with t1 first and, after that, t2. It means only that thread t1 is scheduled before thread 2, not actually started. The two methods take fractions of second each one, so the fact that they are in sequence cannot be seen by a human observer.
More, Java threads are scheduled, ie. assigned to be eventually executed. Even if you have a multi-core CPU, you are not sure that 1) the threads run in parallel (other system processes may interfere) and 2) the threads both start just after the Start() method is called.


Q:

Run A Batch Script Automatically Everyday

I have a batch file ( that ends with .bat), and I want to run it automatically everyday.
What is the tool I can use in order to automate my batch script running?
I'm on Windows.

A:

Use the Scheduled Tasks control panel applet (GUI interface) or the schtasks command (command line interface).
Instructions for the Scheduled Tasks applet are found in Microsoft Knowledge Base article KB308569.
Instructions for the schtasks command are available on Microsoft TechNet.


Q:

Is my recursion solution to this problems correct?

I need to solve this by recursion, here is what they ask to do:
Write a recursion function that takes a positive number and returning the sum(+,-) of its digits from right to left, like this way(for example): the number is 56894, the sum is 4-9+8-6+5=2.
Another example, the number is 7762348, the sum is 8-4+3-2+6-7+7=11.
Does my solution below is correct? I tried compiling it with a lot of numbers and it seems to be correct, but need to be sure.
Here is my recursive solution:
int func(int num){
  if(num/10 ==0)
    return num;
  return (num%10) - func(num/10);
}

A:

Your solution seems to be correct -- the problem asks you to do:
ABCD -> D - C + B - A

But your code does:
ABCD -> (D - (C - (B - A)))

Though it's not hard to show that:
(D - (C - (B - A))) == (D + -1 * (C + -1 * (B - A)) == D - C + B - A

Or some similar informal proof.  But is the code considered correct if it computes num/10 twice instead of using a local variable to store the quotient:
int func(int number) {
    int quotient = number / 10;

    if (quotient == 0) {
           return number;
    }

    return number % 10 - func(quotient);
}

Alternatively, this seems like an opportunity to play with div() and div_t:
#include <stdlib.h>  // where div() and div_t are found

int func(int number) {
    div_t result = div(number, 10);

    if (result.quot == 0) {
        return number;
    }

    return result.rem - func(result.quot);
}

Possibly avoiding yet another division on each iteration.


Q:

Find convergence of $\sum_{1}^{\infty }(\ln\frac{1}{n^{\alpha }} - \ln(\sin\frac{1}{n^{\alpha }}))$

What test do I use to find out if the series is convergent or divergent? Thanks a lot!
$$\sum_{n=1}^{\infty }\left(\ln\frac{1}{n^{\alpha }} - \ln \left(\sin\frac{1}{n^{\alpha }}\right)\right)$$

A:

$\ln(\frac 1{n^a}) - \ln(\sin\frac 1{n^a}) = \ln(\frac {\frac 1{n^a}}{\sin(\frac 1{n^a})})$
$\frac {\frac 1{n^a}}{\sin(\frac 1{n^a})} = \frac 1{1-\frac {1}{6n^{2a}} + o(n^{-4a})} =  1 + \frac 1{6n^{2a}} + o(n^{-4a})$
$\ln(1 + \frac 1{6n^{2a}}+o(n^{-4a}) = \frac 1{6n^{2a}} + o(n^{-4a})$
$\sum_\limits{n=1}^\infty \frac 1{6n^{2a}}$ converges if $2a>1$

A:

First, write this as:
$$-\sum\limits_{n=1}^{\infty}\ln\left(n^{\alpha}\sin\left(\frac{1}{n^{\alpha}}\right)\right).$$
Then, you must know that:
$$\frac{\sin(x)}{x}=1 -\frac{x^2}{6} + o(x^3).$$
And that:
$$\ln(1-X) = -X - \frac{X^2}{2} + o(X^2).$$
Now, if $\alpha>0$, $\frac{1}{n^{\alpha}}\xrightarrow[n \to +\infty]{}0$. Therefore, you get: $$\ln\left(n^{\alpha}\sin\left(\frac{1}{n^{\alpha}}\right)\right) = \ln\left(1 - \frac{1}{6n^{2\alpha}} + o\left(\frac{1}{n^{3\alpha}}\right) \right) = - \frac{1}{6n^{2\alpha}} + o \left(\frac{1}{n^{3\alpha}}\right).$$
Hence, if $\alpha > \frac{1}{2}$, then the sum converges. If $\alpha \leq\frac{1}{2}$, then the sum diverges.


Q:

$q$-series identity

I have to prove the following identity: $$\sum_{n\geq 0} (-1)^n(2n+1)q^{\frac{n(n+1)}{2}} = (q;q)_\infty^3$$ where $(a;q)_\infty = \prod_{i\geq 0}1-aq^i$ is the $q$-Pochhammer symbol. In my notes the identity is stated as a corollary of Jacobi triple product, whose statement is $$\sum_{n\in\mathbb Z} z^nq^{\frac{n(n+1)}{2}} = (-zq;q)_\infty(-1/z;q)_\infty(q;q)_\infty$$
What I have done so far is to change the range of $n$ to $\mathbb Z$, noting that
\begin{align*}\sum_{n\geq 0} (-1)^n(2n+1)q^{\frac{n(n+1)}{2}} &= \sum_{n\in\mathbb Z} (-1)^n n q^{\frac{n(n+1)}{2}} \\
&= \sum_{n\in\mathbb Z} (-1)^n \frac{2n+n^2-n^2}{2} q^{\frac{n(n+1)}{2}} \\
&= \sum_{n\in\mathbb Z} (-1)^n \frac{n^2+n}{2} q^{\frac{n(n+1)}{2}} + \sum_{n\in\mathbb Z} (-1)^n \frac{n-n^2}{2} q^{\frac{n(n+1)}{2}} \\
&= q\left(\sum_{n\in\mathbb Z} (-1)^n q^{\frac{n(n+1)}{2}}\right)' + \sum_{n\in\mathbb Z} (-1)^{n+1} \frac{n(n-1)}{2} q^{\frac{n(n+1)}{2}} \\
&= 0 + \sum_{n\in\mathbb Z} (-1)^{n+1} \frac{n(n-1)}{2} q^{\frac{n(n+1)}{2}} \end{align*}
where the first sum is zero, thanks to Jacobi triple product with $z=-1$.
However, I can't tell if I'm getting closer to my goal. Any hint would be appreciated at this point!
As a side question, I think I'm not getting the Jacobi triple product properly. In the LHS, there are negative powers of $z$. Does this mean that the equality is not happening in $\mathbb C[[z,q]]$ but only for values of $z,q$ where the sum converges? If so, what is the region of convergence of the series?

A:

The theorem is due to Jacobi.
An english-language demonstration can be found in
chapter 19.9, at theorem 357 (with typos) by

G. H. Hardy and E. M. Wright: An introduction to the theory of numbers.
Oxford University press, sixth edition 2008, ISBN 978-0-19-921985-8.
Note: First edition 1938.
The fourth edition seems to be preferable, the sixth has shameful OCR artefacts.

The proof goes like this.
Jacobi's triple product identity, as quoted in the question:
$$\sum_{n\in\mathbb{Z}} z^n q^{n(n+1)/2} =
(-zq;q)_\infty (-\tfrac{1}{z};q)_\infty (q;q)_\infty$$
To get somewhere near $(q;q)_\infty^3$, we want to set $z=-1$.
The problem is then the second product:
Its first factor is $(1+\tfrac{1}{z})$ which becomes zero for $z=-1$.
So let us pull this first factor out:
$$\begin{align}
 (-\tfrac{1}{z};q)_\infty &=
 (1+\tfrac{1}{z}) (-\tfrac{1}{z}q;q)_\infty
\\\therefore\quad
 (-zq;q)_\infty (-\tfrac{1}{z}q;q)_\infty (q;q)_\infty
 &= \frac{\sum_{n\in\mathbb{Z}} z^n q^{n(n+1)/2}}{1+\tfrac{1}{z}}
\\ &= \sum_{n=0}^\infty \frac{z^n+z^{-n-1}}{1+\tfrac{1}{z}} q^{n(n+1)/2}
\\ &= \sum_{n=0}^\infty z^{-n}\frac{z^{2n+1}+1}{z+1} q^{n(n+1)/2}
\\ &= \sum_{n=0}^\infty z^{-n}\,(z^{2n}-z^{2n-1}\pm\cdots-z+1)\,
 q^{n(n+1)/2}
\end{align}$$
Thus, the singularity at $z=-1$ can be removed.
Setting $z=-1$ now gives
$$(q;q)_\infty^3 = \sum_{n=0}^\infty (-1)^n (2n+1)\,q^{n(n+1)/2}$$
which is what we wanted to prove.


Q:

awkward monad transformer stack

Solving a problem from Google Code Jam (2009.1A.A: "Multi-base happiness") I came up with an awkward (code-wise) solution, and I'm interested in how it could be improved.
The problem description, shortly, is: Find the smallest number bigger than 1 for which iteratively calculating the sum of squares of digits reaches 1, for all bases from a given list.
Or description in pseudo-Haskell (code that would solve it if elem could always work for infinite lists):
solution =
  head . (`filter` [2..]) .
  all ((1 `elem`) . (`iterate` i) . sumSquareOfDigitsInBase)

And my awkward solution:

By awkward I mean it has this kind of code: happy <- lift . lift . lift $ isHappy Set.empty base cur
I memoize results of the isHappy function. Using the State monad for the memoized results Map.
Trying to find the first solution, I did not use head and filter (like the pseudo-haskell above does), because the computation isn't pure (changes state). So I iterated by using StateT with a counter, and a MaybeT to terminate the computation when condition holds.
Already inside a MaybeT (StateT a (State b)), if the condition doesn't hold for one base, there is no need to check the other ones, so I have another MaybeT in the stack for that.

Code:
import Control.Monad.Maybe
import Control.Monad.State
import Data.Maybe
import qualified Data.Map as Map
import qualified Data.Set as Set

type IsHappyMemo = State (Map.Map (Integer, Integer) Bool)

isHappy :: Set.Set Integer -> Integer -> Integer -> IsHappyMemo Bool
isHappy _ _ 1 = return True
isHappy path base num = do
  memo <- get
  case Map.lookup (base, num) memo of
    Just r -> return r
    Nothing -> do
      r <- calc
      when (num < 1000) . modify $ Map.insert (base, num) r
      return r
  where
    calc
      | num `Set.member` path = return False
      | otherwise = isHappy (Set.insert num path) base nxt
    nxt =
      sum . map ((^ (2::Int)) . (`mod` base)) .
      takeWhile (not . (== 0)) . iterate (`div` base) $ num

solve1 :: [Integer] -> IsHappyMemo Integer
solve1 bases =
  fmap snd .
  (`runStateT` 2) .
  runMaybeT .
  forever $ do
    (`when` mzero) . isJust =<<
      runMaybeT (mapM_ f bases)
    lift $ modify (+ 1)
  where
    f base = do
      cur <- lift . lift $ get
      happy <- lift . lift . lift $ isHappy Set.empty base cur
      unless happy mzero

solve :: [String] -> String
solve =
  concat .
  (`evalState` Map.empty) .
  mapM f .
  zip [1 :: Integer ..]
  where
    f (idx, prob) = do
      s <- solve1 . map read . words $ prob
      return $ "Case #" ++ show idx ++ ": " ++ show s ++ "\n"

main :: IO ()
main =
  getContents >>=
  putStr . solve . tail . lines

Other contestants using Haskell did have nicer solutions, but solved the problem differently. My question is about small iterative improvements to my code.

A:

Your solution is certainly awkward in its use (and abuse) of monads:

It is usual to build monads piecemeal by stacking several transformers
It is less usual, but still happens sometimes, to stack several states
It is very unusual to stack several Maybe transformers
It is even more unusual to use MaybeT to interrupt a loop

Your code is a bit too pointless :
(`when` mzero) . isJust =<<
   runMaybeT (mapM_ f bases)

instead of the easier to read
let isHappy = isJust $ runMaybeT (mapM_ f bases)
when isHappy mzero

Focusing now on function solve1, let us simplify it.
An easy way to do so is to remove the inner MaybeT monad. Instead of a forever loop which breaks when a happy number is found, you can go the other way around and recurse only if the
number is not happy.
Moreover, you don't really need the State monad either, do you ? One can always replace the state with an explicit argument.
Applying these ideas solve1 now looks much better:
solve1 :: [Integer] -> IsHappyMemo Integer
solve1 bases = go 2 where
  go i = do happyBases <- mapM (\b -> isHappy Set.empty b i) bases
            if and happyBases
              then return i
              else go (i+1)

I would be more han happy with that code.
The rest of your solution is fine.
One thing that bothers me is that you throw away the memo cache for every subproblem. Is there a reason for that?
solve :: [String] -> String
 solve =
    concat .
    (`evalState` Map.empty) .
    mapM f .
   zip [1 :: Integer ..]
  where
    f (idx, prob) = do
      s <- solve1 . map read . words $ prob
      return $ "Case #" ++ show idx ++ ": " ++ show s ++ "\n"

Wouldn't your solution be more efficient if you reused it instead ?
solve :: [String] -> String
solve cases = (`evalState` Map.empty) $ do
   solutions <- mapM f (zip [1 :: Integer ..] cases)
   return (unlines solutions)
  where
    f (idx, prob) = do
      s <- solve1 . map read . words $ prob
      return $ "Case #" ++ show idx ++ ": " ++ show s

A:

The Monad* classes exist to remove the need for repeated lifting. If you change your signatures like this:
type IsHappyMemo = Map.Map (Integer, Integer) Bool

isHappy :: MonadState IsHappyMemo m => Set.Set Integer -> Integer -> Integer -> m Bool

This way you can remove most of the 'lift's. However, the longest sequence of lifts cannot be removed, since it is a State monad inside a StateT, so using the MonadState type class will give you the outer StateT, where you need tot get to the inner State. You could wrap your State monad in a newtype and make a MonadHappy class, similar to the existing monad classes.


Q:

Fixing the spacing on last row when browser window is expanded

edit: Resolved: See Mr. Lister's answer.
The last row seems to lose its horizontal spacing when the browser window is stretched wider than about 1000px.
Note specifically that on the final row of the screenshot below, the horizontal spacing between elements is smaller than on the rows above it.
Example: http://opinnacle.ca/galleria.html
How can I resolve this?

The source used in this example is shown below:
HTML:

Aaton Boards

Ascento

Blackmagic

Festivo

Midicon

CSS:
.stretch {
    width: 100%;
    display: inline-block;
    height:0px;
}

.roundcontainer{
    display: inline-block;
    float:none;
    margin-bottom:35px;
    margin-top:35px;
    height:190px;
    width:190px;
    border-style: solid;
    border-width: 1px;
    border-color: #ccc;
    -moz-border-radius: 7px;
    border-radius: 7px;}

.roundcontainer img {
    height:175px;
    width:175px;
    list-style: none;
    margin:10px 10px auto;
    display:inline-block;
}
.icononame {text-align: center;
    font-family: 'minion-pro', serif;
    font-style: normal;
    font-weight: 400;
    font-size: 0.75em;
    color: #323c46;
    margin-top: 9px;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

A:

The
 has inline style text-align:justify, and the list items are all inline-blocks.
Effectively this means that the list items behave just like words in justified paragraphs: they get distributed evenly across the width of the ul. All except the last line of words, that is.
Solution: remove the text-align:justify from the
, or change it to text-align:center. Then all the list items will be as close together as the last line. Add some left and right margins to the list items to space them wider apart.


Q:

Trouble installing Magick Rotation

I'm new to Ubuntu and having trouble installing Magick Rotation. I downloaded version 1.6.2 and extracted the archive. But when I want to launch the installer it just opens a text file with a bunch of code. When I click on "Open With" and select "Run Software" it only loads for a few seconds without result. Do I need to install some other software first?
I'm using a clean install of Ubuntu 16.04 on a Lenovo Yoga 500.

A:

Every normal software has some kind of "install instructions" - did you read that?
General answer:
Exactly HOW to install depends on how the software developer has chosen to implement that function.
It might be by use of a package installer like apt-get. synaptic, (both are front-ends for ubuntu) rpm (redhat) or a plethora of others, depending on OS.
It might be a specific software developed in any of the programming langauges available
Or it might be a "bash" or "sh" script (a text file with commands) that you run from a Terminal emulator / Shell prompt.
It may also be a few simple bash commands, that does the trick.
Which style it is, makes the installation be very different depending on that.
Specific for ubuntu:
If you can find a Ubuntu specific installation method that involvers apt, apt-get, synaptic, or the Ubuntu software center - prefer that choice, as it normally provides the means to REMOVE the software as easily as it is to install it.


Q:

Password salt and PBKDF2

I'm looking into different solutions regarding storing passwords in Database. After reading a lot I think i will end up with PBKDF2.
Although I'm a little bit confused regarding if I should input salt to my PBKDF2 function and store the salt in a column and the PBKDF2'd password in another column.
I'm also using CodeIgniter and found a library for PBKDF2 (https://github.com/HashemQolami/CodeIgniter-PBKDF2-Library) Which claims I don't need to store the salt separately.

Register user by using $pbkdf2['hash'] as user's password which has
  been recommended; no need to store user's salt separately.
https://github.com/HashemQolami/CodeIgniter-PBKDF2-Library#step-2

So if I'm assuming correct all I need is to provide a password into the function and the function take care of the rest?

A:

I'm the creator of CodeIgniter PBKDF2 Library. Just found this topic on SO, and I decide to clarify how this library works.
Here is the sample code from the doc:
# Load pbkdf2 library into your controller
$this->load->library('pbkdf2');

# Get password, which has been sent via POST method
$password = $this->input->post('password');

# Encrypt the given password using a random generated salt
$pbkdf2 = $this->pbkdf2->encrypt($password);

The encrypt() method, returns an array which has 3 keys: salt, password, hash.
The value of hash is the concatenation of salt and password.
This feature lets the user to choose how to use this library, whether to work with salt and password or hash (salt + password).
The syntax of encrypt() method:
encrypt( string $password [, mixed $good_hash = NULL [, bool $object_output = FALSE]] )

The function uses the given $good_hash as the salt to generate the encrypted password. And it uses a random generated salt if the $good_hash parameter is not given.
So, If you have stored the salt separately, you could pass it to the function as the second parameter to encrypt the given password:
$pbkdf2 = $this->pbkdf2->encrypt($password, $salt);

On the other hand, If you have stored the concatenation of salt and password into database, you could pass that to the function as the second parameter, too:
$pbkdf2 = $this->pbkdf2->encrypt($password, $hash);

The function will break the given $hash automatically to fetch the salt.
So, you could store the concatenation of salt and password in a column (64 characters by default) and then encrypt the new given password by using old stored one.
Putting all together
In the following, I'll show you how to work with this library to register/login the user, without storing the salt and the password separately.
Registering the user:
$this->load->library('pbkdf2');
$password = $this->input->post('password');
$pbkdf2 = $this->pbkdf2->encrypt($password);

# Store $pbkdf2['hash'] into User table as the user's password

Logging in the user:
$this->load->library('pbkdf2');
$username = $this->input->post('username', TRUE);
$password = $this->input->post('password');

# Fetch the stored user's password from the database
$user_password = $this->user_model->get_password_by($username);

# Check whether the User exists
if ($user_password)
{
    # Encrypt the new given password by using the old one:
    $pbkdf2 = $this->pbkdf2->encrypt($password, $user_password);

    # Check whether the new generated password matches the old one
    if ($pbkdf2['hash'] === $user_password) {
        # Log in the user ...
    } else {
        # Show an error...
    }
} else {
    # Show an error...
}


Q:

database design for 1 activity has 1..* date_held

i would like to learn from you on designing the database schema:
ie. my problem is 1 activity has 1..* date_held
eg. activity name is
"see movie" has date_held on 1 Sep
"shopping" has date_held on 2 Sep , 5 Sep, 6 Sep
Method1
so my current database design is
---------------------------
Activity Table
---------------------------
id|name|date_held

1|see moive|20120901

2|shopping|20120902

3|shopping|20120905

4|shopping|20120906

You can see that shopping record is duplicated 3 time. I think it seem not good.

Method2
So I divide into 3 table
---------------------------
Activity Table
---------------------------

id|name

1|see moive

2|shopping

---------------------------
Date Table
---------------------------
id|date

1|Sep 1

2|Sep 2

3|Sep 5

4|Sep 6

---------------------------
Activity_Date Table
---------------------------
activity_id|date_id

1|1

2|2

2|3

2|4

But I think method 2 is very confused. Any one can give me a suggestion how to do table design on 1 activity match 1..* date_held?
Thanks!!

Hi Branko Dimitrijevic
after I think a few hour , i discover another method, i.e. use redis json format
{
"name":"shopping",
"date":[
"Sep1"
]
},
{
"name": "see movie",
"date":[
"Sep2","Sep5","Sep6"
]
}
It seem very easier~ :D
But let me think your suggestion..

A:

You can see that shopping record is duplicated 3 time.

The value of the name field, taken alone, does repeat in different rows. The whole records (i.e. rows) are not repeated.
Logically, if the same activity is repeated on multiple dates, the same piece of data identifying that activity1 must be repeated for each of these dates. There is no magic and all the relevant combinations must be listed in the database. Fortunately, databases are good at handling huge amounts of data.
I think there are two issues here:

Do you need a surrogate key id? If there can never be the same activity on the same date, then the {name, date_held} is a "natural" key, no matter whether you'll add another "surrogate" key such as id. So unless you actually need the the surrogate PK, you can just leave the natural key as primary. If there can be multiple activities per day, consider replacing date_held with datetime_held.
Do you need a third table? If you want to associate more information than just name with each activity, or you want an activity to be able to exist even without ever being held, then you need it at the logical level anyway. But even if you don't, at the purely physical level, using a surrogate PK in a third table would save you from repeating a string, and instead allow you to repeat the (slimmer) integer. You could potentially save space (and cache performance) with that, but could also require more JOINing. As you see, it's a matter of balance and measurements can be an invaluable tool for picking the right one.

1 Be it activity name or ID.


Q:

Is there a way to set the environment path programmatically in C++ on Windows?

Is there a way to set the global windows path environment variable programmatically (C++)?
As far as I can see, putenv sets it only for the current application.
Changing directly in the registry (HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment) is also an option though I would prefer API methods if there are?

A:

MSDN Says:

Calling SetEnvironmentVariable has no
  effect on the system environment
  variables. To programmatically add or
  modify system environment variables,
  add them to the
  HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session
  Manager\Environment registry key, then
  broadcast a WM_SETTINGCHANGE message
  with lParam set to the string
  "Environment". This allows
  applications, such as the shell, to
  pick up your updates. Note that the
  values of the environment variables
  listed in this key are limited to 1024
  characters.

A:

As was pointed out earlier, to change the PATH at the machine level just change this registry entry:
HLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

But you can also set the PATH at the user level by changing this registry entry:
HKEY_CURRENT_USER\Environment\Path

And you can also set the PATH at the application level by adding the application\Path details to this registry entry:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\

A:

There is no API - changing the registry is the way to do it. The changed value will be used for processes starting after the change was made.
Also:  Notice that running applications must actively process the settings changed message and many (most?) do not do so.


Q:

UTF-8 and PHP, mbstring.func_overload doesn't work

I have:
ini_set('mbstring.internal_encoding','UTF-8');
ini_set('mbstring.func_overload',7);

echo strlen("õôóõêç");

The strlen prints 12, instead of 6.
Any suggestion?
http://php.net/manual/en/mbstring.overload.php

A:

mbstring.func_overload can only be set from php.ini (or httpd.conf), and not at runtime.


Q:

Using conditional operator with mixed data types in String.Format

I have a String.Format method that I want to insert either a string or an int, depending on whether a condition is met. My code looks like this:
Box.Text = String.Format("{0}", ScoreBoolCheck ? student1.ScoreInt : "null");

So ideally, the method should check whether ScoreBoolCheck is true, and if so, insert student1.ScoreInt, but if not, it should insert the string "null" instead.
However, this doesn't work yet. I am getting an alert that says "there is no implicit conversion between int and string." Anyone see where I'm going wrong here? Thanks in advance for any help.

A:

Just cast to object:
Box.Text = String.Format("{0}", ScoreBoolCheck ? (object)student1.ScoreInt : "null");

As there is an implicit conversion from string to object, this will work just fine. Assuming ScoreIntis an int, it will get boxed, but it would have been boxed anyway while passing parameters to String.Format (its last parameter is of type object[]).
The conversion is required, as the ternary expression must have a type.
You can't write:
var x = someCondition ? 42 : Guid.NewGuid();

Because no type could be assigned to x, as int and Guid aren't compatible (none of these can be assigned to the other one).
But if you write:
var x = someCondition ? (object)42 : Guid.NewGuid();

Then x is unambiguously of type object. Guid can be implicitly boxed to object.


Q:

Ionic Proxy and oAuth

I'm trying to set up this test environment, involving running the ionic server, and an apache server running Magento. I have the following setup:

Ionic Server running on port 8100 (http://localhost:8100/#/app/home), with a proxy in the ionic.project file  to avoid any CORS issues
"proxies": [
    {
      "path": "/magento",
      "proxyUrl": "http://www.appfactory.loc"
    }
An apache server running on port 80, im setting a virtual host with the domain http://www.appfactory.loc/.

Everything looks find and i can see the app communicating with Magento, the problem is that Magento API is using oAuth for their API authentication, so im getting a oAuth signature invalid error, because of the proxy i set up. Any other call from magento without requiring oAuth works fine, but i still need it for the APIs. What's the best configuration to run this kind of environment?

A:

Okay so the best workflow for ionic (from my perspective) when developing with the local server, is simply to launch Chromw with the flags:
"\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security --user-data-dir

And then you can open the local html file by typing to the address bar:
file:///C:/stage/path-to-project/www/index.html

This was way simpler than using the ionic proxy.