Q:

Javascript convert dropdown to text ONLY if text is clicked

Is there a way in javascript to distinguish if the dropdown text is clicked or if the down arrow is clicked?
There are many answers here on how to convert a DD to a textbox, eg:
Convert drop-down into textbox?
BUT, I would like the DD to change into a textbox ONLY if the text is clicked.
If the arrow is clicked I would like it to function as a dropdown.

A:

There is no function that can allow you to click on a certain part of a default HTML element like Drop Down.
When you click on the inspect element, you'll see that the Drop down is a basic unit and can't be divided into sub-elements so that you can fetch teh exact area that is clicked for drop-down


Q:

How do I use egrep to list words that match a regular expression?

I need to use egrep to count words that contain strings which match a regular expression. For instance, I need to do something like "Count the number of words containing three consecutive vowels" (not exactly that, but that's the gist of it).
I've figured out how to do it to count lines which contain these words, but when I add the -w tag I get an egrep: illegal option -- w error.
Here's the regular expression I'd use to count lines in the scenario above, which seems to work:
egrep -i -c '[aeiou][aeiou][aeiou]' full.html

Using the -w tag with this command causes the error I listed above, even if I add \b tags around the regex expression. e.g.:
egrep -i -c -w '\b.*[aeiou][aeiou][aeiou].*\b' full.html

What am I doing wrong?
EDIT: I'm running this on Solaris 10 out of the terminal.

A:

use this way also to find the count of the words that contains strings
grep --color -Eow '[aeiou][aeiou][aeiou]' filename | wc -l
or
egrep -ow '[aeiou][aeiou][aeiou]' filename | wc -l
o for Print only the matched.
w for word.
finally, it will display the count of the word.


Q:

Weird object found in garage

I was working with my father in the garage and we were cleaning up the boxes in the section above the garage door. I found three green rods, two had smaller rods sticking out the sides and two did not.
I'm not sure what the purpose of these are, they didn't have a buyers tag or anything on it to my knowledge. Is it common?

A:

Looks like pieces of a hammock frame.


Q:

Expected BEGIN_ARRAY but was BEGIN_OBJECT with an array of three elements

I'm developing an Android 3.1 and above application.
I'm using Spring Framework 1.0.0.0RC1 for Android, and Google GSon 2.1.
I'm getting an error when I'm trying to parsing JSON.
This is JSON returned by "http://192.168.1.128/RestServiceImpl.svc/forms/".
{
    "allFormsResult": [
        {
            "FormId": 1,
            "FormName": "Formulario 1"
        },
        {
            "FormId": 2,
            "FormName": "Formulario 2"
        },
        {
            "FormId": 3,
            "FormName": "Formulario 3"
        }
    ]
}

Here I do everything:
public class FormSpringController
{
    public static List<Form> LoadAll()
    {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
        HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

        String url = "http://192.168.1.128/RestServiceImpl.svc/forms/";

        GsonHttpMessageConverter messageConverter = new GsonHttpMessageConverter();
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        messageConverters.add(messageConverter);

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setMessageConverters(messageConverters);

        ResponseEntity<Form[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Form[].class);
        Form[] result= responseEntity.getBody();

        return Arrays.asList(result);
    }
}

When I try to parse it I get the following error:
W/System.err(519): Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Do you know how can I fix it?
UPDATE
@hotveryspicy has suggested me there is a "problem" with JSON. This is how I'm generating JSON response (C# code):
public class RestServiceImpl : IRestServiceImpl
{
    public List<FormContract> allForms()
    {
        List<FormContract> list = null;
        using (var vAdmEntities = new ADMDatabase.ADMEntities())
        {
            list = new List<FormContract>();
            foreach (var form in vAdmEntities.Form)
            {
                FormContract formC = new FormContract
                {
                    FormName = form.name.Trim(),
                    FormId = form.formId
                };
                list.Add(formC);
            }
        }

        return list;
    }
}

A:

as your string starts with "{", which means it is an Object(json concept) and it seems that your considering it as an array, which is wrong.
EDITED:
{"data":
   {
    "allFormsResult": [
        {
            "FormId": 1,
            "FormName": "Formulario 1"
        },
        {
            "FormId": 2,
            "FormName": "Formulario 2"
        },
        {
            "FormId": 3,
            "FormName": "Formulario 3"
        }
    ]
  }
}

just append a object "data", and then continue with you parsing. It is a problem of Json when it got first element as an Array "[".


Q:

Show textarea of checked chekbox only and hide when unchecked

I want to show textarea only when checkbox is checked and hide when the checkbox is unchecked. But my current code display all the textarea when certain checkbox is checked. textarea and checkbox are dynamically generated, so there can be any number of checkbox and textarea.
Basically, what I want to do is toggle the textarea on checkbox event.

$( document ).ready(function() {
 $(".with-us").hide();
    $(".with-other").hide();
    $('textarea[name="shopDescription"]').hide();
    $("#work-option :radio").change(function () {
     var workType = $('input[name=work]:checked').val();
        if (workType == "wc") {
         $(".with-other").hide();
            $(".with-us").show();
        } else if (workType == "woc") {
            $(".with-us").hide();
            $(".with-other").show();
        } else {
            $(".with-us").hide();
            $(".with-other").hide();
        }
    });
 $(document).on('click', 'input[name="shop"]', function () {
     if (this.checked) {
         $('textarea[name="shopDescription"]').show();
        } else {
         $('textarea[name="shopDescription"]').hide();
        }
    });
});

        Show your work:

            <input type="radio" name="work" value="wc">
            With us
      <input type="radio" name="work" value="woc">
            With other

        <input type="hidden" name="withus" id="withus">
        <input id="work1" type="checkbox" name="shop" value="test1">
        Work 1
        <textarea id="test1Description" placeholder="Description" name="shopDescription"></textarea>

        <input id="work2" type="checkbox" name="shop" value="test2">
        Work 2
        <textarea id="test2Description" placeholder="Description" name="shopDescription"></textarea>

        <input id="work3" type="checkbox" name="shop" value="test3">
        Work 3
        <textarea id="test3Description" placeholder="Description" name="shopDescription"></textarea>

        <input id="work4" type="checkbox" name="shop" value="test4">
        Work 4
        <textarea id="test4Description" placeholder="Description" name="shopDescription"></textarea>

        <input id="work5" type="checkbox" name="shop" value="test5">
        Work 5
        <textarea id="test5Description" placeholder="Description" name="shopDescription"></textarea>

        <input id="work6" type="checkbox" name="shop" value="test6">
        Work 6
        <textarea id="test6Description" placeholder="Description" name="shopDescription"></textarea>

        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

A:

The selector $('textarea[name="shopDescription"]').hide(); selects all textarea's.
Instead search for the next() textarea:

$(document).ready(function() {
  $(".with-us").hide();
  $(".with-other").hide();
  $('textarea[name="shopDescription"]').hide();
  $("#work-option :radio").change(function() {
    var workType = $('input[name=work]:checked').val();
    if (workType == "wc") {
      $(".with-other").hide();
      $(".with-us").show();
    } else if (workType == "woc") {
      $(".with-us").hide();
      $(".with-other").show();
    } else {
      $(".with-us").hide();
      $(".with-other").hide();
    }
  });
  $(document).on('click', 'input[name="shop"]', function() {
    if (this.checked) {
      $(this).next('textarea').show();
    } else {
      $(this).next('textarea').hide();
    }
  });
});

  Show your work:

    <input type="radio" name="work" value="wc"> With us
    <input type="radio" name="work" value="woc"> With other

  <input type="hidden" name="withus" id="withus">
  <input id="work1" type="checkbox" name="shop" value="test1"> Work 1
  <textarea id="test1Description" placeholder="Description" name="shopDescription"></textarea>

  <input id="work2" type="checkbox" name="shop" value="test2"> Work 2
  <textarea id="test2Description" placeholder="Description" name="shopDescription"></textarea>

  <input id="work3" type="checkbox" name="shop" value="test3"> Work 3
  <textarea id="test3Description" placeholder="Description" name="shopDescription"></textarea>

  <input id="work4" type="checkbox" name="shop" value="test4"> Work 4
  <textarea id="test4Description" placeholder="Description" name="shopDescription"></textarea>

  <input id="work5" type="checkbox" name="shop" value="test5"> Work 5
  <textarea id="test5Description" placeholder="Description" name="shopDescription"></textarea>

  <input id="work6" type="checkbox" name="shop" value="test6"> Work 6
  <textarea id="test6Description" placeholder="Description" name="shopDescription"></textarea>

  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Alternativ
You can simplify your jQuery a bit:
$(document).on('click', 'input[name="shop"]', function() {
    $(this).next('textarea').toggle(this.checked);
});


Q:

WPF datagrid live-update with button-column

I have a datagrid which contains bid and ask - prices for currency-symbols. The data is updated every seconds. I update the data by creating a new collection of my viewmodel-entities and bind this collection to the datagrid every second.
The problem is:
Because my datagrid contains a template-column with a button "buy", this button is also recreated every second! This means, that when the user hovers the button, the hover-styles blinks, as the button is recreated every second. Additionally sometimes the click-event is not fired correctly, if the button is recreated while the user has his mouse-left-button pressed.
Any suggestions, how to solve real-time-update a datagrid with button-columns?

A:

If I understand correctly, you have a collection of items and you have a couple fields (bid/ask in particular), all of which will be updated every second. It sounds like what may be happening is that in the process of changing the ItemsSource of your data grid, you're losing some important state that is causing problems for the event handlers on your buttons.
Even if you update all of the items, the important distinction to make is that you should update the items, and not completely clear out the collection that is currently bound to your datagrid. Changing the ItemsSource to a new one will cause the data grid to have to do a lot more work than if you simply update the contents of the existing collection. If you're using an ObservableCollection, this may mean making your viewmodel items mutable so that you can simply update bid/ask. If your viewmodel items are mutable and implement INotifyPropertyChanged, the bid/ask updates will be reflected in the datagrid or in any other bindings to those properties of the objects. The neat thing about doing it this way is that the same objects are staying bound to the same containers in the ItemsControl, so during each update, absolutely nothing is happening to your buttons. Now, if your viewmodel objects that contain bid/ask are immutable, you should still be able to pull this off. Every second, you simply iterate through your collection of items and use SetItem to replace each existing item with a new one. The important thing to remember in this latter case is that every second, the datagrid is still getting notified that there has been a change in the ObservableCollection, and because of this, the bindings on each row are going to cause the DataContext of the row/cells/button to update.
Here's a quick example of how I might go about this problem. I'm going to assume use of the datagrid in .NET 4.0 (if you're using toolkit though with 3.5, this should be the same). I'm going to take the first approach, where my CurrencyPair object is mutable.
First, some simple viewmodel code with a self contained timer to update a few currency pair bid/asks each second:
public class CurrencyPairsViewModel
{
    private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
    private readonly ObservableCollection<string> _orders = new ObservableCollection<string>();
    private readonly ObservableCollection<CurrencyPair> _pairs = new ObservableCollection<CurrencyPair>();
    private readonly Random _rand = new Random();
    private readonly System.Timers.Timer _timer = new System.Timers.Timer(1000);
    private readonly Action _update;

    public CurrencyPairsViewModel()
    {
        this._timer.Elapsed += OnIntervalElapsed;
        this._update = new Action(this.Update);
        this._pairs.Add(new CurrencyPair("USD/GBP"));
        this._pairs.Add(new CurrencyPair("AUD/USD"));
        this._pairs.Add(new CurrencyPair("WOW/CAD"));
        this._timer.Start();
    }

    public ObservableCollection<string> Orders { get { return this._orders; } }

    public ObservableCollection<CurrencyPair> Pairs { get { return this._pairs; } }

    public void Buy(CurrencyPair pair)
    {
        this._orders.Add(string.Format("Buy {0} at {1}", pair.Name, pair.Ask));
    }

    private void OnIntervalElapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        this._dispatcher.Invoke(this._update);
    }

    private void Update()
    {
        foreach (var pair in this._pairs)
        {
            pair.Bid = this._rand.NextDouble();
            pair.Ask = pair.Bid + 0.01;
        }
        this._timer.Start();
    }
}

public class CurrencyPair : INotifyPropertyChanged
{
    private readonly string _name;

    private double _ask;
    private double _bid;

    public CurrencyPair(string name)
    {
        this._name = name;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public double Ask
    {
        get { return this._ask; }
        set
        {
            this._ask = value;
            this.OnPropertyChanged("Ask");
        }
    }

    public double Bid
    {
        get { return this._bid; }
        set
        {
            this._bid = value;
            this.OnPropertyChanged("Bid");
        }
    }

    public string Name { get { return this._name; } }

    protected void OnPropertyChanged(string name)
    {
        if (null != this.PropertyChanged)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

Second, the view, which in this example is just my MainWindow.
<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
  <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="4"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <DataGrid Grid.Row="0"
              ItemsSource="{Binding Pairs}"
              AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*"/>
            <DataGridTextColumn Header="Bid" Binding="{Binding Bid}" Width="*"/>
            <DataGridTextColumn Header="Ask" Binding="{Binding Ask}" Width="*"/>
            <DataGridTemplateColumn Header="Buy">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="BUY"
                                Click="OnBuyClicked"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
    <GridSplitter Grid.Row="1" Height="4" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
    <ListBox Grid.Row="2"
             ItemsSource="{Binding Orders}"/>
  </Grid>
</Window>

And finally, I have a bit of code behind this XAML to handle the BUY button clicks and initialize a viewmodel right in the view (note that this, and other practices outside of how to update the bid/ask on the collection of items may not be the best way to go about things, depending on how your application is going to grow).
public partial class MainWindow : Window
{
    private readonly CurrencyPairsViewModel _model = new CurrencyPairsViewModel();

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this._model;
    }

    private void OnBuyClicked(object sender, RoutedEventArgs e)
    {
        var pair = (CurrencyPair)((Button)sender).DataContext;
        this._model.Buy(pair);
    }
}

Hope the example is helpful!


Q:

Mercurial: impact from named branch creation in the middle of the development

I am using Mercurial named branch to mark a big thread of development (CustomerA branch).
When starting work on CustomerB changes (in the same repo), I have forgotten to start named branch (Customer B) from the very beginning.
I have the following history in my repo:
CustomerA-1 > CustomerA-2 > CustomerA-3 > CustomerA-8 > CustomerA-9
                          |
                          > CustomerA-4 > CustomerA-5 > CustomerB-6 > CustomerB-7

Is there any negative impact from leaving it "as-is"? Are there specific practical issues with any Mercurial workflows (merging, switching between branches, cloning, etc) if I leave "4" and "5" changesets "as is", even though logically they belong to CustomerB branch? For example, "5" appears in the list of "hg heads", will it have any adverse impact?
There are good answers on stackoverflow on how to fix it, but I don't want to rewrite history, unless this situation can cause specific pain points in future:
Mercurial move changes to a new branch
Mercurial: Named Branches vs Multiple Repositories

A:

You are fine. I can't think of any adverse impact that is inherently due to the use of named branches.


Q:

Explaining the argument formula

I am beginning my study of Complex Analysis, and I stumbled on the following definition on how to compute the  argument:
$\varphi = \arg(z) =
\begin{cases}
\arctan(\frac{y}{x}) & \mbox{if } x > 0 \\
\arctan(\frac{y}{x}) + \pi & \mbox{if } x < 0  \mbox{ and } y \ge 0\\
\arctan(\frac{y}{x}) - \pi & \mbox{if } x < 0 \mbox{ and } y < 0\\
\frac{\pi}{2} & \mbox{if } x = 0 \mbox{ and } y > 0\\
-\frac{\pi}{2} & \mbox{if } x = 0 \mbox{ and } y < 0\\
\mbox{indeterminate } & \mbox{if } x = 0 \mbox{ and } y = 0.
\end{cases}$
I am striving to understand why in the second and third quadrant we have $\arctan(\frac{y}{x}) + \pi$ and $\arctan(\frac{y}{x}) - \pi$ respectively. I have been searching for the reason why $\pi$ is summed and subtracted however this is presented as a formula and I have nor found any intuition that would explain those operations.
Question:
What is the reasoning behind summing and subtracting $\pi$?
Thanks in advance!

A:

The maximum and minimum values of arctan are π/2 and -π/2, so all the values will be between these.
You must be already knowing that arg(z) is the angle made by line joining the point representing our complex number on Cartesian plane with the origin, from the x axis (where x represents real component and y represents imaginary component).
Lets see the cases of 2nd and 3rd quadrant.
Case-1 second quadrant:
Your x part will be negative and y is positive hence arctan(y/x) will give you a value between -π/2 and 0. If you will directly plot this angle on the Cartesian plane it will be somewhere below x axis hence will be wrong as it will be representing negative y and positive x. So we add π to solve this problem.
Similar logic is applicable for the third quadrant where both x and y are negative hence arctan(y/x) will give you an angle somewhere in the 1st quadrant i.e between 0 and π/2. To get the correct angle you might add or subtract π.
This whole adjustment is done due to the limits of arctan function which does not cover whole 0 to 360 degrees instead just covers -90 to 90 degres i.e (-π/2 to π/2).
Hope this solves your doubt.


Q:

How to show buttons with user authentication in AngularJS?

Currently I am working on my master project. My application is online portfolio management. User can register on app and create profiles. Now i want to give Edit and Delete buttons on the profile view. But just the users who have created the profile are able to see this buttons. For example, if i am a user of app then only i can see the edit and delete buttons on my profile and i can only see the other user's profile.
I am new in AngularJS. It looks easy but still did not work for me. I have a different views of view profile and edit profile. But i have just one controller for both of it.
This is how my view profile code looks like,
HTML

{{profile.firstname}} {{profile.lastname}}

            <button class="btn-success btn-lg" type="button" data-ng-click="profilesCtrl.modalUpdate('lg', profile)">Edit</button>
            <button class="btn-danger btn-lg" type="button" data-ng-click="profilesCtrl.remove(profile)">

            </button>

Controller
profilesApp.controller('ProfilesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Profiles', '$modal', '$log',
    function($scope, $stateParams, $location, Authentication, Profiles, $modal, $log) {

        this.authentication = Authentication;

        // Find a list of Profiles
        this.profiles = Profiles.query();

        // open a modal window to view single profile
        this.modalview = function(size, selectedProfile) {

            var modalInstance = $modal.open({
                templateUrl: 'modules/profiles/views/view-profile.client.view.html',
                controller: function($scope, $modalInstance, profile) {
                    $scope.profile = profile;

                    console.log(profile);

                    $scope.ok = function() {
                        $modalInstance.close($scope.profile);
                    };
                },
                size: size,
                resolve: {
                    profile: function() {
                        return selectedProfile;
                    }
                }
            });

            modalInstance.result.then(function(selectedItem) {
                $scope.selected = selectedItem;
            }, function() {
                $log.info('Modal dismissed at: ' + new Date());
            });
        };

        // open a modal window to update single profile
        this.modalUpdate = function(size, selectedProfile) {

            var modalInstance = $modal.open({
                templateUrl: 'modules/profiles/views/edit-profile.client.view.html',
                controller: function($scope, $modalInstance, profile) {
                    $scope.profile = profile;

                    $scope.ok = function() {
                        $modalInstance.close($scope.profile);
                    };

                    $scope.cancel = function() {
                        $modalInstance.dismiss('cancel');
                    };
                },
                size: size
            });

            modalInstance.result.then(function(selectedItem) {
                $scope.selected = selectedItem;
            }, function() {
                $log.info('Modal dismissed at: ' + new Date());
            });
        };

        // Remove existing Profile
        this.remove = function(profile) {
            if (profile) {
                profile.$remove();

                for (var i in this.profiles) {
                    if (this.profiles[i] === profile) {
                        this.profiles.splice(i, 1);
                    }
                }
            } else {
                this.profile.$remove(function() {
                    $location.path('modules/profiles/views/list-profiles.client.view.html');
                });
            }
        };

        // Update existing Profile
        this.update = function(updatedProfile) {
            var profile = updatedProfile;

            profile.$update(function() {}, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

    }
]);

Please suggest me some way, how can i fix this issue? Any help would appreciated.

A:

you can use a directive like this:
<button access-level="canEdit">Edit</button>

and your directive is bound to accessLevel:
angular.module("app")
    .directive('accessLevel', ['AuthService', 'AUTH_EVENTS', function (authService, authEvents) {
        return {
            restrict: 'A',
            link: function ($scope, element, attrs) {
                var accessLevel;

                attrs.$observe('accessLevel', function (acl) {
                    if (acl) {
                        accessLevel = acl;
                        updateCss();
                    }
                });

                $scope.$on("auth-change", function (event, data) {
                    switch (data) {
                        case authEvents.logoutSuccess:
                        case authEvents.loginSuccess:
                            updateCss();
                            break;
                        case authEvents.notAuthorized:
                        default:

                    }

                });

                function updateCss() {
                    if (accessLevel) {
                        if (!authService.isAuthorized(accessLevel)) {
                            switch (element[0].nodeName) {
                                case "A":
                                    element.hide();
                                    break;
                                default:
                                    element.attr("disabled", "disabled");
                                    break;
                            }
                        } else {
                            switch (element[0].nodeName) {
                                case "A":
                                    element.show();
                                    break;
                                default:
                                    element.removeAttr("disabled");
                                    break;
                            }
                        }
                    }
                }
            }
        }

    }]);

this is a little bit more than what you need, but gives you an idea what you can achieve. (and you have to write your auth service etc.)
as example here is a part of my auth service:
angular.module('app')
    .factory("AuthService", ["$rootScope", "$http", "AuthSession", "AUTH_EVENTS", function ($rootScope, $http, AuthSession, AUTH_EVENTS) {

       AuthSession.load();

       $rootScope.$on('$stateChangeStart', function (event, nextState) {
            if (nextState.data && nextState.data.accessLevel && !service.isAuthorized(nextState.data.accessLevel)) {
                event.preventDefault();
                $rootScope.$broadcast('auth-change', AUTH_EVENTS.loginRequired, nextState.name);
            }
        });

        var service = {
            login: function (credentials) {
                return $http
                            .post('/api/account/login', credentials)
                            .success(function (data, status) {
                                if ((status < 200 || status >= 300) && data.length >= 1) {
                                    $rootScope.$broadcast("auth-change", AUTH_EVENTS.loginFailed);
                                    return;
                                }

                                AuthSession.create(data.AccessToken, data.User);
                                $rootScope.$broadcast("auth-change", AUTH_EVENTS.loginSuccess);
                            }).error(function (data, status) {
                                $rootScope.$broadcast("auth-change", AUTH_EVENTS.loginFailed);
                            });
            },
            logout: function () {
                AuthSession.destroy();
                $rootScope.$broadcast("auth-change", AUTH_EVENTS.logoutSuccess);
            },
            isAuthenticated: function () {
                return (AuthSession.token !== null);
            },
            isAuthorized: function (accessLevel) {
                if (!accessLevel) return true;

                return (this.isAuthenticated() && AuthSession.user.UserRoles.indexOf(accessLevel) !== -1);
            }

        }
        return service;
    }]);

this service retrieves a bearer token from the server and stores it in the authsession service. the user roles are also stored beside of other user information. since the backend is also secured, one who changes the user roles on the client, can't write to the backend. (everything on client side is just for the look and feel of the user)


Q:

How to find the correct replacement glass dome for a light fixture?

My wife and I were cleaning the glass dome for our kitchen's main overhead light fixture and it broke.  How do we go about finding a matching replacement?
The electrical and structural metal parts are fine, we just need the glass part.  Would a manufacturer's code be etched on the metal parts somewhere?  Do we need to contact the original builder?
I wish I had a picture (I'm at work at the moment), but the dome was basically the bottom third of a glass sphere, like a shallow bowl, with several holes to attach metal supports.  Nothing terribly fancy, but I have no idea where to look for a matching replacement.

A:

See if the globe is a standard/common design.
There are a few "standard" designs for how globes/domes/shades attach to the lamp fixture.  Many manufacturers intentionally build to the standard, and there is a huge aftermarket of various styles of globe, specifically for replacement or "style upgrade" in any compatible fixture.  A lighting distributor or real hardware store will have these.  Big-box chain stores maybe not so much.
Contact manufacturer
Part number is probably on a sticker on the fixture itself, usually around where the light bulbs are or on the back. You may have to take the fixture down to be able to see this (and if you do, be sure to turn the power off).
Just a warning: It's possible they don't sell the individual part, don't make it anymore, or want to charge more for the part and/or shipping than other options (below).
Buy an identical fixture
Find the same fixture somewhere, and use the parts from it you need
Just replace the fixture with something better
If you can't find a matching fixture, just replace it with something else.
You can also just use this as an excuse to replace it with something you like better anyway.


Q:

ubuntu14.04 python3.4 unable to pip3 matplotlib

Have searched other similar questions, with no success. Do I just have to go back to Python 2.7?
ubuntu 14.04 on Intel 32b desktop. Was using Python2.7 everything OK.  Now installed Idle for Python3.4 using Ubuntu Software Center.  It works but
import matplotlib

results in
matplotlib not found

and then
pip3 install matplotlib

results in a huge amount of benign looking output but ends with errors.  Here is the last of the pip log file:
running install_lib

copying pylab.py -> /usr/local/lib/python3.4/dist-packages

error: [Errno 13] Permission denied:
'/usr/local/lib/python3.4/dist-packages/pylab.py'

---------------------------------------- Cleaning up...
>Removing temporary dir /tmp/pip_build_jim... Command /usr/bin/python3 -c
"import setuptools,
tokenize;__file__='/tmp/pip_build_jim/matplotlib/setup.py';exec(compile(getattr(tokenize,
'open', open)(__file__).read().replace('\r\n', '\n'), __file__,
'exec'))" install --record /tmp/pip-77rf26vy-record/install-record.txt
--single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_jim/matplotlib Exception information: Traceback
(most recent call last):   File
"/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)   File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 283, in
run
    requirement_set.install(install_options, global_options, root=options.root_path)   File
"/usr/lib/python3/dist-packages/pip/req.py", line 1436, in install
    requirement.install(install_options, global_options, *args, **kwargs)   File "/usr/lib/python3/dist-packages/pip/req.py", line 707, in install
    cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)   File
"/usr/lib/python3/dist-packages/pip/util.py", line 715, in
call_subprocess
    % (command_desc, proc.returncode, cwd)) pip.exceptions.InstallationError: Command /usr/bin/python3 -c "import
setuptools,
tokenize;__file__='/tmp/pip_build_jim/matplotlib/setup.py';exec(compile(getattr(tokenize,
'open', open)(__file__).read().replace('\r\n', '\n'), __file__,
'exec'))" install --record /tmp/pip-77rf26vy-record/install-record.txt
--single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_jim/matplotlib

A:

This error
error: [Errno 13] Permission denied: '/usr/local/lib/python3.4/dist-packages/pylab.py'

indicates the script is trying to write in the directory /usr/local.
Run the command as a super user:
sudo pip3 install matplotlib


Q:

Como fazer dois relacionamentos para a mesma tabela?

Tenho uma tabela chamada advertencias, nesta tabela eu tenho 2 foreign key para a mesma tabela chamada pessoas nesta tabela pessoa eu tenho dois tipos de pessoa Aluno e Professor, entao na tabela advertencias quando vou criar uma nova advertencia eu tenho 2 $this->Form->input um para Aluno e outro para Professor. Na funcao add() do meu controller eu consigo trazer os alunos e adicionar no input de Aluno mas não consigo preencher o input de Professor.
Como fazer isso ?
Meu ambiente esta assim:
Model
class Advertencia extends AppModel {
    public $belongsTo = array(
             //aluno
            'Pessoa' => array(
                'className' => 'Pessoa',
                'foreignKey' => 'pessoas_id',
                'conditions' => '',
                'fields' => '',
                'order' => ''
            ),
            //professor
            'Pessoa' => array(
                'className' => 'Pessoa',
                'foreignKey' => 'pessoas_id1',
                'conditions' => '',
                'fields' => '',
                'order' => ''
            ),
        );

    }

AdvertenciasController
public function add() {
        if ($this->request->is('post')) {
            $this->Advertencia->create();
            if ($this->Advertencia->save($this->request->data)) {
                $this->Session->setFlash(__('The advertencia has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The advertencia could not be saved. Please, try again.'));
            }
        }

                //alunos
                $this->set("pessoas", $this->Advertencia->Pessoa->find('list', array(
                                                        'fields' => array("Pessoa.id", "Pessoa.nome", "Pessoa.tipopessoas_id",'Tipopessoa.id','Tipopessoa.descricao'),
                                                        'conditions' => array('Tipopessoa.descricao'=>'ALUNO'),
                                                        'recursive' => 0)));

                //professores
                $this->set("professores", $this->Advertencia->Pessoa->find('list', array(
                                                        'fields' => array("Pessoa.id", "Pessoa.nome", "Pessoa.tipopessoas_id",'Tipopessoa.id','Tipopessoa.descricao'),
                                                        'conditions' => array('Tipopessoa.descricao'=>'PROFESSOR'),
                                                        'recursive' => 0)));

    }

View

<?php echo $this->Form->create('Advertencia'); ?>
    <fieldset>
        <legend><?php echo __('Add Advertencia'); ?></legend>
    <?php
        echo $this->Form->input('data');
                echo $this->Form->input('pessoas_id');//aluno
                echo $this->Form->input('pessoas_id1');//professor
        echo $this->Form->input('disciplinas_id');
        echo $this->Form->input('turmas_id');
    ?>
    </fieldset>
<?php echo $this->Form->end(__('Submit')); ?>

<?php echo __('Actions'); ?>

<?php echo $this->Html->link(__('List Advertencias'), array('action' => 'index')); ?>

<?php echo $this->Html->link(__('List Disciplinas'), array('controller' => 'disciplinas', 'action' => 'index')); ?>

<?php echo $this->Html->link(__('New Disciplinas'), array('controller' => 'disciplinas', 'action' => 'add')); ?>

<?php echo $this->Html->link(__('List Turmas'), array('controller' => 'turmas', 'action' => 'index')); ?>

<?php echo $this->Html->link(__('New Turmas'), array('controller' => 'turmas', 'action' => 'add')); ?>

A:

Resolvido
Fiz assim.
Controller
    public function add() {
            if ($this->request->is('post')) {
                        $this->Advertencia->create();

                    //seta valores para pessoas
                    $this->Advertencia->set(array(
                        "pessoas_id"=>$this->request->data["Advertencia"]["alunos"],
                        "pessoas_id1"=>$this->request->data["Advertencia"]["professores"],
                    ));

                        if ($this->Advertencia->save($this->request->data)) {
                $this->Session->setFlash(__('The advertencia has been saved.'));
                    return $this->redirect(array('action' => 'index'));
                } else {
                    $this->Session->setFlash(__('The advertencia could not be saved. Please, try again.'));
                }
            }

                    //alunos
                    $this->set("alunos", $this->Advertencia->Aluno->find('list', array(
                                                                        'fields' => array("Aluno.id", "Aluno.nome", "Aluno.tipopessoas_id",'Tipopessoa.id','Tipopessoa.descricao'),
                                                                        'conditions' => array('Tipopessoa.descricao'=>'ALUNO'),
                                                                        'recursive' => 0)));

                    //professores
                    $this->set("professores", $this->Advertencia->Professor->find('list', array(
                                                                        'fields' => array("Professor.id", "Professor.nome", "Professor.tipopessoas_id",'Tipopessoa.id','Tipopessoa.descricao'),
                                                                        'conditions' => array('Tipopessoa.descricao'=>'PROFESSOR'),
                                                                        'recursive' => 0)));

    }

View

<?php echo $this->Form->create('Advertencia'); ?>
    <fieldset>
        <legend><?php echo __('Add Advertencia'); ?></legend>
    <?php

                echo $this->Form->input('alunos');//aluno
                echo $this->Form->input('professores');//professor

    ?>
    </fieldset>
<?php echo $this->Form->end(__('Submit')); ?>

<?php echo __('Actions'); ?>

<?php echo $this->Html->link(__('List Advertencias'), array('action' => 'index')); ?>

<?php echo $this->Html->link(__('List Disciplinas'), array('controller' => 'disciplinas', 'action' => 'index')); ?>

<?php echo $this->Html->link(__('New Disciplinas'), array('controller' => 'disciplinas', 'action' => 'add')); ?>

<?php echo $this->Html->link(__('List Turmas'), array('controller' => 'turmas', 'action' => 'index')); ?>

<?php echo $this->Html->link(__('New Turmas'), array('controller' => 'turmas', 'action' => 'add')); ?>


Q:

Firebase performance is not displaying/listing some endpoints used in the android app

I'm using firebase performance monitoring in my android app. For the most part, it works great!
Different endpoints are listed in their own rows but the uncategorised row has a lot of samples (more than a million), why is that?
Also, some endpoints which are called a lot are not shown as different rows? What could be the issue here? Has anyone faced something like this?

A:

Firebase performance monitoring now supports adding custom url patterns. So if some endpoints are not being captured, you can now create an exact custom url for that endpoint or patterns.
From the docs:

Firebase attempts to match request URLs to any configured custom URL
  patterns before falling back to automatic URL pattern matching. For
  any matching requests to a custom URL pattern, Firebase aggregates the
  requests' data under the custom URL pattern.

More mentioned in the docs here.


Q:

can I change the focus between my two JDialog?

So. I have a MainScreen extends javax.swing.JFrame from my MainScreen i open a
JDialog
Logout logout = new Logout(this,true,utilajx,user1);
 logout.setVisible(true);

then from my JDialog I will open an other JDialog and I Want to set the focus to it.:
dlg = new DialogVirtualKeyboardReal(mainScreen, false, codArticol);
       dlg.setLocaleL(Locale.ENGLISH);

this is how it looks like, I want to make my keyboard in focus but i can't

A:

if I change the modal parameter to true it works how i want. Thank you for -1.
  lg = new DialogVirtualKeyboardReal(mainScreen, true, codArticol);
           dlg.setLocaleL(Locale.ENGLISH);

And here it is what I wanted


Q:

Plotting more lines in Matlab

I have input file that stores data in this format:
x1 y1 x2 y2

That is one row and it represents two points for a line. Now, I have many such rows
and for each row I need to draw a line. Is there some efficient method to do this?
Do I have to go through each line separately with a for loop? What command do I use
to draw line?
Thank you

A:

Try something like this, you might need to change the %f %f %f %f format:
fid = fopen('yourfile', 'r');

C = textscan(fid, '%f %f %f %f');

fclose(fid);

figure(100)
plot(C{:, 1}, C{:, 2}, C{:, 3}, C{:, 4}); % column based lines

figure(200)
plot([C{1} C{3}]', [C{2}, C{4}]'); % row based lines

;


Q:

Proving The Limit Is Unique Using Open Balls

Prove: The Limit Is Unique

Attempt, let assume that the sequence $\{x_m\}$ has two limit namely: $p ,q$
Let $\epsilon=\frac{d(p,q)}{2}$
$p,q$ are limits of $\{x_m\}\Rightarrow$ There are $m_1\text{ and }m_2$ such that for all $n_1>m_1$ and $n_2>m_2$  let $N=\max\{n_1,n_2\}$ we get $x_{N}\in B(p,\epsilon)$ and $x_{N}\in B(q,\epsilon)$
Looking at $d(p,q)$ we get:
$$d(p,q)\leq_{(1)} d(x_N,p)+d(x_N,q)<\epsilon+\epsilon=d(p,q)$$
Contradiction.
$(1)$ triangle inequality and definition of open ball
Is the proof valid?

A:

Yes, it's fine. However, it's not well written:

You wrote “There are $m_1\text{ and }m_2$ such that for all $n_1>m_1$ and $n_2>m_2$  let $N=\max\{n_1,n_2\}$ we get $x_{N}\in B(p,\epsilon)$ and $x_{N}\in B(p,\epsilon)$ ”. There  should be two sentences here: “There are $m_1$ and $m_2$ such that, for all $n_1>m_1$ and $n_2>m_2$, $d(x_{n_1},p),d(x_{n_2},q)<\epsilon$. Let $N=\max\{n_1,n_2\}$; we get $x_{N}\in B(p,\epsilon)$ and $x_{N}\in B(p,\epsilon)$.”
You assert that $d(p,q)\leqslant d(x_N,p)+d(x_N,q)$ by the triangle inequality and the definition of open ball. Acutally, all you need is the triangle inequality. The definition of open ball is only used later.


Q:

Plotting with folium

The task is to make an adress popularity map for Moscow. Basically, it should look like this:
https://nbviewer.jupyter.org/github/python-visualization/folium/blob/master/examples/GeoJSON_and_choropleth.ipynb
For my map I use public geojson: http://gis-lab.info/qa/moscow-atd.html
The only data I have - points coordinates and there's no information about the district they belong to.
Question 1:
Do I have to manually calculate for each disctrict if the point belongs to it, or there is more effective way to do this?
Question 2:
If there is no way to do this easier, then, how can I get all the coordinates for each disctrict from the geojson file (link above)?

A:

Thanks to @BobHaffner, I tried to solve the problem using geopandas.
Here are my steps:

I download a shape-files for Moscow using this link click
From a list of tuples containing x and y (latitude and logitude) coordinates I create list of Points (docs)
Assuming that in the dataframe from the first link I have polygons I can write a simple loop for checking if the Point is inside this polygon. For details read this.


Q:

Use MongoDB with Laravel 5.3

I want to use MongoDB with Laravel 5.3. For that I have found this package:
https://github.com/jenssegers/laravel-mongodb
I have setup MongoDB on my machine and database connection with Laravel too.
I'm also able to run queries using Laravel Eloquent and Query builder.
The only issue is with authentication.
In order to use this package with Laravel, we need to extend its Eloquent class in each model like:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class User extends Eloquent {}

But User model provided by Laravel 5.3 already extends Authenticatable class and PHP doesn't support multiple inheritance. So, what is the solution here?
https://github.com/laravel/laravel/blob/master/app/User.php
I would prefer a solution in which User model provided by Laravel 5.3 doesn't need to be modified much.
Thanks,
Parth vora

A:

I have 5.2 project and auth system works just fine with jenssegers/laravel-mongodb. You should add Jenssegers\Mongodb\Auth\PasswordResetServiceProvider if you're using password reminders.

If you don't use password reminders, you don't have to register this service provider and everything else should work just fine.

https://github.com/jenssegers/laravel-mongodb#extensions
Also, here's my working User.php, maybe it will help:
namespace App;

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Eloquent implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;


Q:

Appling Jensen's inequality

I have to prove that for every $a,b,c \in \mathbb{R}$ $$1+\sqrt[3]{e^{2a}}\sqrt[5]{e^b}\sqrt[15]{e^{2c}}\le \sqrt[3]{(1+e^a)^2}\sqrt[5]{(1+e^b)}\sqrt[15]{(1+e^c)^2}.$$
We can prove that  $$\sqrt[3]{e^{2a}}\sqrt[5]{e^b}\sqrt[15]{e^{2c}}\le \sqrt[3]{(1+e^a)^2}\sqrt[5]{(1+e^b)}\sqrt[15]{(1+e^c)^2}$$ by appling $\ln$ function to both sides of inequality but how to prove the original one?

A:

Weighted Jensen and convexity of $x \mapsto \log(1+e^x) \implies$
$$\frac23\log(1+e^a)+\frac15\log(1+e^b)+\frac2{15}\log(1+e^c) \ge \log(1 + e^{\frac23a+\frac15b+\frac2{15}c})$$
with equality iff $a=b=c$.


Q:

Converting a list to an array when list has quotes and embedded comma

This function converts a list to an array when list has quotes and embedded comma:
array function convertRow(required string lstRow) {

    var arResult = [];
    var arTemp = ListToArray(arguments.lstRow, ',', true);

    var quoteMode = false;
    var startQuote = false;

    for (var i in arTemp) {

        if (i CONTAINS '"' && not quoteMode) { startQuote =  true; }

        if (startQuote) {
            ArrayAppend(arResult, replace(i, '"', ''));

            startQuote = false;
            quoteMode = true;
        }
        else if (quoteMode) {
            arResult[ArrayLen(arResult)] &= "," & replace(i, '"', '');

            if (i CONTAINS '"') quoteMode = false;
        }
        else
            ArrayAppend(arResult, i);
    }

    writedump(lstRow);
    writedump(arResult);

    return arResult;
}

A:

I could get rid of your startQuote variable, I reduced the number of i CONTAINS '"' comparasions by 1.
array function convertRow(required string lstRow) {
    var arResult = [];
    var arTemp = ListToArray(arguments.lstRow, ',', true);
    var quoteMode = false;

    for (var i in arTemp) {
        var containsQuote = i CONTAINS '"';
        if (containsQuote && not quoteMode) {
            ArrayAppend(arResult, replace(i, '"', ''));
            quoteMode = true;
        }
        else if (quoteMode){
            arResult[ArrayLen(arResult)] &= "," & replace(i, '"', '');
            quoteMode = not containsQuote;
        }
        else{
            ArrayAppend(arResult, i);
        }
    }

    writedump(lstRow);
    writedump(arResult);

    return arResult;
}


Q:

Python package recognized in Pycharm, not in terminal

I'm developing a Django project which imports django-imagekit; everything works fine on my Windows machine.  On my Linux-Ubuntu laptop though, Pycharm recognizes the package in the editor, it's listed in the project's interpreter's packages but it's not recognized from the command line:
    simon@Simon-Swanky:~/PycharmProjects/tcspt$ python manage.py check
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/simon/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/home/simon/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute
    django.setup()
  File "/home/simon/.local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/simon/.local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/home/simon/.local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/simon/PycharmProjects/tcspt/assetmanage/models.py", line 3, in <module>
    from imagekit.models import ProcessedImageField
ImportError: No module named imagekit.models

It seems to be looking in python 2's packages but I'm using python 3 for this project.  I tried a few things like adding the path to the project variables but so far I can't get it to work.
Trying to import imagekit from python 2's shell:
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import imagekit
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named imagekit

Trying to import imagekit from python 3's shell:
>>> import imagekit
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/imagekit/__init__.py", line 2, in <module>
    from . import conf
  File "/usr/local/lib/python3.5/dist-packages/imagekit/conf.py", line 5, in <module>
    class ImageKitConf(AppConf):
  File "/usr/local/lib/python3.5/dist-packages/appconf/base.py", line 74, in __new__
    new_class._configure()
  File "/usr/local/lib/python3.5/dist-packages/appconf/base.py", line 100, in _configure
    value = getattr(obj._meta.holder, prefixed_name, default_value)
  File "/home/simon/.local/lib/python3.5/site-packages/django/conf/__init__.py", line 55, in __getattr__
    self._setup(name)
  File "/home/simon/.local/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting IMAGEKIT_DEFAULT_CACHEFILE_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

A:

If you are using Python 3, then you should be using python3 manage.py check. It might be better to use a virtual environment, in which case you would activate the virtual environment before running python manage.py check.
The import fails in the Python 3 shell because you have not set the DJANGO_SETTINGS_MODULE environment variable (see the docs for more info). The easiest fix is to use the Django shell, which takes care of this for you.
$ python3 manage.py shell
>>> import imagekit


Q:

Not clickable transparent window on ubuntu desktop

The past couple of days two transparent window areas appeared on my ubuntu desktop, which are not clickable.
This is a printscreen on my desktop where you can clearly see the windows I am referring to.

Do you have any idea what has caused them and how I can remove them? I tried closing all open applications and rebooting and they didn't seem to disappear.

A:

Open a terminal.
Run xprop.
Click on the window. In your terminal, all information will appear.


Q:

IE can't use "return false" on radio button

I use js like below to prevent click on some radio button.
It's work totally fine in Chrome.
But on IE8 It's still can't check but default value was disappear when click other radio in group.
 $("body").on("change", ".readonly", function () {
    return false;
});

How can i make radio readonly and also work on IE8?

A:

<input type="radio" readonly />  does not work, but using click does partly work. If you have two radios with the same name, IE will however still uncheck the checked one regardless with this code

$("body").on("click", ".readonly", function(e) {
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input name="rad" type="radio" class="readonly" />
<input name="rad" type="radio" checked class="readonly" />

Here is a solution: https://stackoverflow.com/a/5437904/295783

$(function() {
  $(':radio:not(:checked)').attr('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input name="rad" type="radio" class="readonly" />
<input name="rad" type="radio" checked class="readonly" />


Q:

React.js Redux reducer does not insert the item

I'm very new to React.js and Redux.
I'm trying to build a very simple shopping cart application.

What I want is if you hit on an item (eg :- banana) It should appear in the cart.
(It should change the state of the cartReducer.js)
But instead of pushing the item to the reducer state it pushes something else.

What is the reason for this error?
This is my code.
cartReducer
import {ADD_TO_CART} from '../actions/index'

const initialState =[

]

export default (state = initialState,action)=>{
  console.log("ACTION PAYLOAD",action.payload)
  switch(action.type){
    case ADD_TO_CART:
    return[...state,action.payload]
    default:
    return state
  }
}

Item component
import React, { Component } from "react";
import { connect } from "react-redux";
import {addToCart} from '../../actions/index'

export class Etem extends Component {
  showItems = () => {
    const { items, addToCartAction } = this.props;
    console.log("ITEMS", items);
    return items.map(items =>
{items.name}
);
  };

  render() {
    return (

Items

{this.showItems()}

    );
  }
}

// export default items;

const mapStateToProps = reduxState => ({
  items: reduxState.items
});

const mapDispatchToProps = dispatch => ({
  addToCartAction: item => dispatch(addToCart(item))
});

export default connect(mapStateToProps, mapDispatchToProps)(Etem);

Action
export const ADD_TO_CART = 'ADD_TO_CART';

export const addToCart=(item) =>{
    console.log("ITEMMMMMMMMMM",item)
    return(
        {

            type:ADD_TO_CART,
            payload:item,
        }
    )
}

A:

 this will pass the click event to addToCartAction instead of item.
Try this:
return items.map(item => (

 addToCartAction(item)}>
    {item.name}

));


Q:

Unexpected result comparing values of rows and columns in two text files

This is related to one of my previous question: How to compare values of rows and columns of two text files in bash?
file1.txt (with special characters: cat -vet file1.txt)
Name  Col1  Col2  Col3^M$
-----------------------^M$
row1  1     4     7^M$
row2  2     5     8^M$
row3  3     6     9$

file2.txt (with special characters: cat -vet file2.txt)
Name  Col1  Col2  Col3^M$
-----------------------^M$
row1  1     4     7^M$
row2  2     5     999$

I have somewhat figured out a way to compare two files. But for some reason it is not giving me the result that I want. Here is the code I use to compare the files.
awk '
FNR < 2 { next }
FNR == NR {
    for (i = 2; i <= NF; i++)
    {
        a[i,$1] = $i;
    }
    b[$1];
    next;

}
($1 in b) {
   for (i = 2; i <= NF; i++)
   {
      if (a[i,$1] == $i)
          printf("%s->Col%d: %d vs %d: Equal\n", $1, i-1, a[i,$1], $i);
      else
          printf("%s->Col%d: %d vs %d: Not Equal\n", $1, i-1, a[i,$1], $i);
   }
} ' file1.txt file2.txt

Expected result:
row2->Col1: 1 vs 1: Equal
row2->Col2: 4 vs 4: Equal
row2->Col3: 7 vs 7: Equal
row1->Col1: 2 vs 2: Equal
row1->Col2: 5 vs 5: Equal
row1->Col3: 8 vs 999: Not Equal

Actual result:
row2->Col1: 1 vs 1: Equal
row2->Col2: 4 vs 4: Equal
row2->Col3: 0 vs 7: Not Equal
row1->Col1: 2 vs 2: Equal
row1->Col2: 5 vs 5: Equal
row1->Col3: 0 vs 999: Not Equal

Does anyone know why lines 3 and 6 of the actual result are comparing with 0 (not supposed to do so)?

A:

Special thanks to @jaypal for helping me solve the problem. The problem was that these text files were created in MS-DOS and had to be converted to Unix format in order to be executed in Linux or Unix environment. So before executing the segment of code from the question above, I had to use this command: dos2unix file1.txt


Q:

My transition doesn't work

In this code, when invoking the play() method for the transition (PathTransition pt;) the program hides the orange rectangles and displays no transitions. It has no syntax error. I'm trying to get the rectangle to circle around the circles.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.control.*;
import javafx.event.Event;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.shape.*;
import javafx.scene.paint.Color;
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.util.Duration;

public class Test__javafx extends Application{
    public void start(Stage stage) {
        Pane p = new Pane();
        Button b = new Button("Play");
        b.setStyle("-fx-background-radius: 3em;" +
                "-fx-background-color: #66a3ff;" +
                "-fx-min-width: 120;" +
                "-fx-min-height: 40;" +
                "-fx-max-width: 120;" +
                "-fx-min-height: 40;" +
                "-fx-cursor: hand;" +
                "-fx-text-fill: white;");
        b.setLayoutX(320);
        b.setLayoutY(400);

        b.setOnAction((ActionEvent event) -> {

            Circle big = new Circle();
       // create rectangle for big circle
       Rectangle bigRec = new Rectangle();
            Circle circ = new Circle();
            Rectangle r = new Rectangle();
            //event for small rectangle
            r.setWidth(20);
            r.setHeight(30);
            r.setLayoutX(362);
            r.setLayoutY(335);

            r.setArcWidth(5);
            r.setArcHeight(5);
            r.setStyle("-fx-fill: #ff9933;" +
                    "-fix-stroke-width: 20;" +
                    "-fix-stroke: #ff4d4d;");

            //event for small circle
            circ.setStyle("-fx-fill: #88ff4d;" +
                    "-fx-stroke-width: 12;" +
                    "-fx-stroke: #3399ff;");
            circ.setCenterX(370);
            circ.setCenterY(400);
            circ.setRadius(50);

            // event for big circle's rectangle
             bigRec.setLayoutX(205);
            bigRec.setLayoutY(375);
            bigRec.setWidth(30);
            bigRec.setHeight(20);
            bigRec.setArcWidth(5);
            bigRec.setArcHeight(5);
            bigRec.setStyle("-fx-fill: #ff9933;" +
                    "-fix-stroke-width: 20;" +
                    "-fix-stroke: #ff4d4d;");

            // big circle
            big.setStyle("-fx-fill: #88ff4d;" +
                    "-fx-stroke-width: 12;" +
                    "-fx-stroke: #3399ff;");
            big.setCenterX(370);
            big.setCenterY(400);
            big.setRadius(150);
            p.getChildren().addAll(big, bigRec, circ, r);
            // transition for small circle and rectangle

            PathTransition pt = new PathTransition();
            pt.setDuration(Duration.millis(2000));
            pt.setPath(bigRec);
            pt.setNode(bigRec);
            pt.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
            pt.setCycleCount(Timeline.INDEFINITE);
            pt.setAutoReverse(false);
           // if you comment the play method it shows the rectangle
             // but not any transitions obviously
           pt.play();

             PathTransition pt2 = new PathTransition();
            pt2.setDuration(Duration.millis(2000));
            pt2.setPath(circ);
            pt2.setNode(r);
            pt2.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
            pt2.setCycleCount(Timeline.INDEFINITE);
            pt2.setAutoReverse(false);
             // if you comment the play method it shows the rectangle
             // but not any transitions obviously
           pt2.play();

        });
        p.getChildren().add(b);
        p.setStyle("-fx-background-color: #88ff4d;");
        Scene s = new Scene(p, 750, 650);
        stage.setScene(s);
        stage.show();
    }
    // launch Application
    public static void main(String[] args) {
        Application.launch(args);
    }
}

A:

In your first PathTransition, you have set both the path and the node as bigRec. Set the path as big instead of bigRec.
PathTransition pt = new PathTransition();
pt.setDuration(Duration.millis(2000));
pt.setPath(big); // Make this change
pt.setNode(bigRec);
pt.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
pt.setCycleCount(Timeline.INDEFINITE);
pt.setAutoReverse(false);

Also your transition is happening but at the coordinates you set for your rectangles. In order to see the rectangles on the circle, remove the layout values from the rectangle. I.e remove the below code
//Code to be removed
bigRec.setLayoutX(205);
bigRec.setLayoutY(375);

r.setLayoutX(362);
r.setLayoutY(335);


Q:

What is the best way to have all the timezones as choices for a Django model?

I am creating model which needs to store a timezone value. Right now, I am generating the timezones using pytz in another file, converting that into a tuple, and calling that tuple into my models.py. Like this:
timezones.py
import pytz
TIMEZONE_CHOICES = []
for tz in pytz.all_timezones:
    TIMEZONE_CHOICES.append((tz, tz))
TIMEZONE_CHOICES = tuple(TIMEZONE_CHOICES)

models.py
from .timezones import TIMEZONE_CHOICES

class MyModel(models.Model):
    timezone = models.CharField(max_length=255, default='UTC', choices=TIMEZONE_CHOICES)

This honestly seems a bit hack-y. Would generating the timezones this way cause problems in the future? What would be the ideal way to do something like this?

A:

If Django allowed choices to accept callables you could simply pass a lambda function. But since it doesn't (yet), you should be able to simply define the choices list within your model class and use the zip function to dynamically generate the tuples. For example:
import pytz

class MyModel(models.Model):
    TIMEZONE_CHOICES = zip(pytz.all_timezones, pytz.all_timezones)

    timezone = models.CharField(max_length=255, default='UTC', choices=TIMEZONE_CHOICES)

The only issue I can see is that if a timezone is removed from the tz database in the future, the select box would be empty when you try to edit such a record.


Q:

Let $f(z)=2ize^{(i+1)z^2+2i}$. Find $\max_{z\in \bar{B}(0,2)}|f(z)|$.

Let $f(z)=2ize^{(i+1)z^2+2i}$. Find $\max_{z\in \bar{B}(0,2)}|f(z)|$.

My attempt:
Let $z=re^{i\theta}, 0\le r\le 2, \theta\in[0,2\pi[.$ Then $f(z)=2ire^{i\theta}e^{(i+1)r^2e^{2i\theta}+2i }$ and thus, $$ |f(z)|=2re^{r^2\cos(2\theta)}.$$
I'm not sure how to continue. I think that I have to find $(r,\theta)$ that maximizes the value of $|f(z)|$. Now, $\cos(2\theta)$ with $\theta\in[0,2\pi[$ reaches a maximum for $\theta = \pi/2$. This means that $z=ri, 0\le r\le 2$ and $|f(z)|=2re^{r^2}$. And this is maximized for $r=2$. In conclusion, $\max_{z\in\bar{B}(0,2)}|f(z)|=4e^4$.
Is this a correct approach? Thanks.

A:

Assuming $\overline B(0,2) = \{z \in \mathbb{C} : |z| \le 2\} $, thanks to the maximum modulus principle we can say the maximum of $|f(z)|$ is reached for $z=2e^{i\theta}$ for $\theta \in [0,2\pi)$.
Evaluating $|f(z)|$ for $z=2e^{i\theta}$ we get $|f(2e^{i\theta})| = 4e^{4(\cos(2\theta) - \sin(2\theta))}$
which is maximized when $\cos(2\theta) - \sin(2\theta)$ reaches his max: $$\max(\cos(2\theta) - \sin(2\theta)) = \sqrt{2} \quad \text{for} \quad  \theta = \pi n + \arctan(1-\sqrt2) \approx_{n=1} 2.74 \in [0,2\pi)$$
In conclusion: $$\max|f(z)| = 4e^{4\sqrt2}$$
Edit:
\begin{split}
|f(z)| & = |2ir|\cdot |e^{i\theta}| \cdot |e^{ir^2e^{2i\theta}}| \cdot |e^{r^2e^{2i\theta}}| \cdot |e^{2i}| \\
& = 2r \cdot |e^{ir^2[\cos(2\theta) +i\sin(2\theta)]}| \cdot |e^{r^2[\cos(2\theta) +i\sin(2\theta)]}| \\
& = 2r \cdot |e^{ir^2\cos(2\theta)}| \cdot |e^{-r^2\sin(2\theta)}| \cdot |e^{r^2cos(2\theta)}| + \cdot |e^{ir^2\sin(2\theta)]}| \\
& =2r \cdot |e^{-r^2\sin(2\theta) +r^2 \cos(2\theta)}|
\end{split}


Q:

What does #arr[*] mean in bash?

I came across a script with some code like this:
arr=($p)
np=${#arr[*]}

p is a string of integer pairs: "0,1 2,4 3,5" etc. First of all, I'm not 100% sure what the () do in the first line, but I think it just turns the things into an associative array of sorts? That may not be correct either .... But more than that, I'm at a complete loss as to what the second line does.

A:

The parentheses in the first turn the result into an array, and it will be assigned indexes starting from 0 and split according to IFS (which by default includes whitespace). The ${#arr[*]}} gives the number of elements in the array.


Q:

Android VideoView: Video view is much darker in a dialog view

Hi all
I have a problem with embedding a video view inside a dialog view
everything works fine except that the video displayed in the Dialog is much darker that if displayed in the rest of the activity
any ideas ?
here is some code
button1main.setOnClickListener(new OnClickListener() {

                public VideoView videoView = null;
                @Override
                public void onClick(View v) {
                    //set up dialog
                    Dialog dialog = new Dialog(CustomDialog.this);
                    dialog.setContentView(R.layout.maindialog);
                    //dialog.setTitle("This is my custom dialog box");
                    dialog.setCancelable(true);

                    this.videoView = (VideoView) dialog.findViewById(R.id.video);
                    VideoPlayer vp = new VideoPlayer(this.videoView, null);
                    vp.playVideo();

                    //set up button
                    Button button = (Button) dialog.findViewById(R.id.Button01);
                    button.setOnClickListener(new OnClickListener() {
                    @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    //now that the dialog is set up, it's time to show it
                    dialog.show();
                }
            });

A:

it seems that the VideoView gets dimmed because it is created behind the window.
Jason Rogers solution works but means that the area behind the dialog will not get dimmed.
I used
mVideoView.setZOrderOnTop(true);

to bring the VideoView to front, so that it does not get dimmed, but still everything behind the dialog will.

A:

I actually found the solution to this (or at least in my case)
it seems its a bug from android where the Video View is created behind the Dialog and when the Dialog opens it dims the background views including the video
the "quick fix" I applied is
WindowManager.LayoutParams a = dialog.getWindow().getAttributes();
a.dimAmount = 0;
dialog.getWindow().setAttributes(a);

they might be a solution better solution like passing the context of the Dialog box instead of using the same context for creating the Dialog and the Video View (I'll check later if I get sone time)


Q:

How to create multiple reg files using linux regex

I have one data file and one reg template file:
data file contain:
c01218 172.20.13.50
c01203 172.20.13.35
c01204 172.20.13.36
c01220 172.20.13.52
c01230 172.20.13.55

reg template:
[HKEY_USERS\S-1-5-21-2000478354-2111687655-1801674531-230160\Software\SimonTatham\PuTTY\Sessions\name]
"Present"=dword:00000001
"HostName"="172.28.130.0"

I want to create loop which to create new reg files from the template with the name from the first colum and to change "name" located in HKEY_USERS also with the first column and to change the IP address with the second column.
For example:
sed -e "s/name/name1/g" -e "s/172.28.130.0/172.28.130.1/g" 1.reg

Expected view after the command:
#cat c01218.reg

[HKEY_USERS\S-1-5-21-2000478354-2111687655-1801674531-230160\Software\SimonTatham\PuTTY\Sessions\c01218]
"Present"=dword:00000001
"HostName"="172.20.13.50"

A:

Try:
$ while read a b; do sed "s/^\"HostName.*$/\"HostName\"=\"$b\"/" template > $a; done < data

A little messy since " has to be used for the shell to expand the variables in the sed-substitution and all additional " need to be escaped.
output:
$ ls
c01203  c01204  c01218  c01220  c01230  data  template

$ cat c*
[HKEY_USERS\S-1-5-21-2000478354-2111687655-1801674531-230160\Software\SimonTatham\PuTTY\Sessions\name]
"Present"=dword:00000001
"HostName"="172.20.13.35"
[HKEY_USERS\S-1-5-21-2000478354-2111687655-1801674531-230160\Software\SimonTatham\PuTTY\Sessions\name]
"Present"=dword:00000001
"HostName"="172.20.13.36"
[HKEY_USERS\S-1-5-21-2000478354-2111687655-1801674531-230160\Software\SimonTatham\PuTTY\Sessions\name]
"Present"=dword:00000001
"HostName"="172.20.13.50"
[HKEY_USERS\S-1-5-21-2000478354-2111687655-1801674531-230160\Software\SimonTatham\PuTTY\Sessions\name]
"Present"=dword:00000001
"HostName"="172.20.13.52"
[HKEY_USERS\S-1-5-21-2000478354-2111687655-1801674531-230160\Software\SimonTatham\PuTTY\Sessions\name]
"Present"=dword:00000001
"HostName"="172.20.13.55"


Q:

CHaMP Topo Processing Menu not active in ArcMap 10.1

After converting a .tiff file to TIN, I have now installed the CHaMP Topo Processing Add-In which should allow me to convert Topo TIN to DEM. However, after installation, the entire toolbar is grey and inactive (including Convert Topo TIN to DEM from drop down). Any advice on why this might happen?

A:

The toolbar is designed to work with a "SurveyGeodatabase", which is created in the first step of the Toolbar workflow. Unless you are working with a set of total station data, I think the toolbar is not the right fit for your needs/task.
This step in the toolbar actually relies on ESRI's "TIN to Raster" Geoprocessing tool, which can be accessed from ArcToolbox if you have the 3D analyst extension installed.


Q:

A-Frame: Default value 'true' does not match type 'boolean' in browser.js

I've been fighting with this for a while. The console seems to populate with incorrect match types, when it's actually getting the right type.
    Default value `true` does not match type `boolean` in component `nav-panel`
    Default value `false` does not match type `boolean` in component `nav-panel`
    Default value `0` does not match type `number` in component `nav-button`

It does get annoying to see this happening.

A:

The problem here is that those defaults are string values, and they are not defined in their types per se.
When defined in the schema, if you have a number or a Boolean they cannot be wrapped in quotes "" (If you do so, you're telling A-Frame that those are strings!)
This means:
Change "true" to true, and '0' to 0:
AFRAME.registerComponent('nav-panel', {
 schema : {
  active: {type: "boolean", default: "true"},
  textOffset: {type: 'number', default: '0'},

 },

}

Correct:
AFRAME.registerComponent('nav-panel', {
 schema : {
  active: {type: "boolean", default: true},
  textOffset: {type: 'number', default: 0},

 }
}


Q:

Basic complex number class

As part of my C++ training, I wanted to create a basic complex number class for basic complex number calculations.
The class should have the following:

constructor (non explicit, for implicit conversions)
<< and >> operators to stream with cout and cin
==, != operators to compare complex numbers
+, +=, -, -=, *, *=, /, /= operators for simple arithmetics
GetR(), GetI(), SetR(), SetI() functions to access the real and imaginary parts of the number

I am going to work in a place that uses an underscore at the end of every function parameter, so I am sorry in advance for any discomfort it may cause while reviewing my code.
This is really a part of my baby steps in C++, so any feedback about style, design and coding will be appreciated. Attached are both the header file and the cpp file:

//  complex.h
//  Written by me on Jan 28, 2015

namespace exercises
{

class Complex;

std::ostream& operator<<(std::ostream&, const Complex&);
std::istream& operator>>(std::istream&, Complex&); // assumes (a,bi) format

bool operator==(const Complex, const Complex);
bool operator!=(const Complex, const Complex);

Complex operator+(const Complex, const Complex);
Complex operator-(const Complex, const Complex);
Complex operator*(const Complex, const Complex);
Complex operator/(const Complex, const Complex);

class Complex
{
public:
    Complex(const double r_=0, const double i_=0);// non explicit on purpse

    // using generated ~tor, cctor, c=tor

    Complex& operator+=(const Complex);
    Complex& operator-=(const Complex);
    Complex& operator*=(const Complex);
    Complex& operator/=(const Complex);

    double GetR()const;
    double GetI()const;

    void SetR(const double);
    void SetI(const double);

private:
    double m_r;
    double m_i;
};

} // namespace exercises

//  complex.h
//  Written by me on Jan 28, 2015

#include <iostream>
#include <cassert>
#include "complex.h"

namespace exercises
{

// ---------- global funcs ----------

bool operator==(const Complex a_, const Complex b_)
{
    return (a_.GetR() == b_.GetR() && a_.GetI() == b_.GetI());
}

bool operator!=(const Complex a_, const Complex b_)
{
    return (a_.GetR() != b_.GetR() && a_.GetI() != b_.GetI());
}

Complex operator+(const Complex a_, const Complex b_)
{
    Complex ret(a_.GetR()+b_.GetR(), a_.GetI()+b_.GetI());
    return ret;
}

Complex operator-(const Complex a_, const Complex b_)
{
    Complex ret(a_.GetR()-b_.GetR(), a_.GetI()-b_.GetI());
    return ret;
}

Complex operator*(const Complex a_, const Complex b_)
{
    double a=a_.GetR(), b=a_.GetI();
    double c=b_.GetR(), d=b_.GetI();

    Complex ret(a*c-b*d, b*c+a*d);

    return ret;
}

Complex operator/(const Complex a_, const Complex b_)
{
    double a=a_.GetR(), b=a_.GetI();
    double c=b_.GetR(), d=b_.GetI();
    assert(c || d);

    Complex ret((a*c+b*d)/(c*c+d*d), (b*c-a*d)/(c*c+d*d));

    return ret;
}

std::ostream& operator<<(std::ostream& os_, const Complex& comp_)
{
    return os_ << '(' << comp_.GetR() << ',' << comp_.GetI() << "i)";
}

std::istream& operator>>(std::istream& is_, Complex& comp_) // assumes (a,bi) format
{
    char ch = 0;
    double r = 0;
    double i = 0;

    is_ >> ch >> r >> ch >> i >> ch >> ch;

    comp_.SetR(r);
    comp_.SetI(i);

    return is_;
}

// ---------- interface funcs ----------

Complex::Complex(const double r_, const double i_): m_r(r_), m_i(i_)
{}

Complex& Complex::operator+=(const Complex o_)
{
    m_r += o_.m_r;
    m_i += o_.m_i;

    return *this;
}

Complex& Complex::operator-=(const Complex o_)
{
    m_r -= o_.m_r;
    m_i -= o_.m_i;

    return *this;
}

Complex& Complex::operator*=(const Complex o_)
{
    double a=m_r, b=m_i, c=o_.m_r, d=o_.m_i;
    m_r = a*c - b*d;
    m_i = b*c + a*d;

    return *this;
}

Complex& Complex::operator/=(const Complex o_)
{
    assert(o_.m_r || o_.m_i);
    double a=m_r, b=o_.m_r, c=m_i, d=o_.m_i;
    m_r = (a*c+b*d)/(c*c+d*d);
    m_i = (b*c-a*d)/(c*c+d*d);

    return *this;
}

double Complex::GetR()const
{
    return m_r;
}

double Complex::GetI()const
{
    return m_i;
}

void Complex::SetR(const double r_)
{
    m_r = r_;
}

void Complex::SetI(const double i_)
{
    m_i = i_;
}

} //namespace exercises

A:

To avoid bugs like one mentioned by @janos, a common recommendation is to express operator!= in terms of operator==:
bool operator!=(const Complex a_, const Complex b_) {
    return !(a_ == b_);
}

The same recommendation goes for many other operators, for example operator+ can and should be expressed in terms of operator+=:
Complex operator+(Complex a_, const Complex b_) {
    return a_ += b_;
}

This enforces an important invariant (a = b + c must have the same effect as a = b; a += c), and removes the need to call getters and setters.
Speaking of getters and setters, in your case they serve no purpose other than hiding names. The access to private members is still unrestricted.
As a mathematician, I would expect Complex to have at least more methods,
namely norm and conjugate.
const qualification of pass-by-value parameters is pointless.

A:

Bug
The != operator returns true if both the real and imaginary parts are different.
That's clearly a bug.
Instead of this:

bool operator!=(const Complex a_, const Complex b_)
{
    return (a_.GetR() != b_.GetR() && a_.GetI() != b_.GetI());
}

You probably meant this:
bool operator!=(const Complex a_, const Complex b_)
{
    return (a_.GetR() != b_.GetR() || a_.GetI() != b_.GetI());
}

Coding style, readibility
A common writing style is to put spaces around operators. For example instead of this:

double a=a_.GetR(), b=a_.GetI();
double c=b_.GetR(), d=b_.GetI();

Complex ret(a*c-b*d, b*c+a*d);

Complex ret(a_.GetR()+b_.GetR(), a_.GetI()+b_.GetI());

Write this way:
double a = a_.GetR(), b = a_.GetI();
double c = b_.GetR(), d = b_.GetI();

Complex ret(a * c - b * d, b * c + a * d);

Complex ret(a_.GetR() + b_.GetR(), a_.GetI() + b_.GetI());

The difference may be subtle, but it makes the code easier to read.


Q:

Separate policy from mechanism: What does it mean?

I've often heard the mantra of "separating policy from mechanism", especially in the context of the Unix philosopy.  What does this mean and what are some concrete examples of it?  When/why is/isn't it a good thing?

A:

It is basically the separation of requirements or business function from technical implementation.  The mechanism is the technical implementation.  The implementation allows and supports the ability for the business to implement its business policy.
Example:  A security mechanism may be set up allow for users to be attached to groups and for users and groups to be attached to permissible actions.  The policy specifies who is in the groups and which groups and users will be allowed to perform which actions.  It may specify who is allowed to assign users and actions.


Q:

Seeking an STM32 with wifi, BT, display and on-board debugger

I am seeking an STM32 with wifi, BT, display and on-board debugger (I think that they all have that, but am not 100% sure; I don't want to use a JTAG probe). Does anyone know of one?

A:

There is a series called STM32WB with integrated WiFi and Bluetooth, there is a STM32WB Nucleo available.
There is also an F413 discovery board but it doesn't have Bluetooth, WiFi only.


Q:

code works on dev pc but not server

The below code correctly processes data for my gridview on my dev machine but not my server.
I am simply trying to add hours to a time parameter that appears in the gridview. It works fine on my dev PC, but posts this error on server....
String was not recognized as a valid DateTime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: String was not recognized as a valid DateTime.
Here is the code for the template field in my gridview...
<ItemTemplate>
   <asp:Label ID="Label1" runat="server" Text='<%# String.Format("{0:hh:mm:ss tt}", Convert.ToDateTime(Eval("eventTime").ToString).AddHours(-5)) %>' ></asp:Label>
</ItemTemplate>

How can I check for Null with inline code?
Any suggestions would be greatly appreciated.

A:

It sounds like a data issue between local dev and the server; I would check what is being pushed to eventTime. I bet it is not a valid DateTime.
EDIT
Per your edit, you can use the ternary operator (?:) to perform an inline null check:
<asp:Label ID="Label1" runat="server" Text='<%# Eval("eventTime") != null ? String.Format("{0:hh:mm:ss tt}", Convert.ToDateTime(Eval("eventTime").ToString).AddHours(-5)) : "No time specified" %>' ></asp:Label>


Q:

Renewenvironment verbatim as lstlisting

I am using pandoc to convert some HTML into LaTeX. pandoc converts code (<pre>) into verbatim, which does not handle line breaks.
As I found on this website, the recommended solution is to switch to lstlisting, however I'm not really fan of modifying pandoc for that, so I thought I would just replace the verbatim environment to lstlisting, which I fully configured with lstset in my document.
I tried, and I failed.
Here is my simple attempt:
\renewenvironment{verbatim}{\begin{lstlisting}}{\end{lstlisting}}

which produces this error:

Emergency stop. No legal \end found

A:

You should use \lstnewenvironment to define new listings environments. As it is only for new environments you must first undefine verbatim:
\documentclass[]{article}
\usepackage{listings}

\begin{document}

\begin{verbatim}
\section{}
\end{verbatim}

\let\verbatim\someundefinedcommand
\lstnewenvironment{verbatim}
{}{}

\begin{verbatim}
\section{}
\end{verbatim}

\end{document}


Q:

Importing CSV made in iPhone application

I am making a simple CSV file in my application, and I use characters such as 'æøå'. When I open the file on my Mac with BBEdit it opens the file correctly, but if I import the file in Excel (MS Office 2011) with Unicode UTF-8 it does not show the characters correctly. How do I fix this?
Some of the code:
NSString *tmpPath = NSTemporaryDirectory();
NSString *fullPath = [tmpPath stringByAppendingPathComponent:@"log_export.csv"];
[csvComplete writeToFile:fullPath atomically:YES encoding:NSUTF8StringEncoding error:NULL];

I am mailing the csv.
[mailController addAttachmentData:data mimeType:@"text/csv" fileName:@"sertifikat-loggbok.csv"];

A:

CSV is a text format that does not specify the character encoding. Different applications assume different encodings.
My experience is that Microsoft Excel assumes it's in the default encoding which happens to be CP1250 (similar to ISO 8859-1 / Latin 1 encoding) on my machine. Maybe it always assumes CP1250.
So try to switch from UTF-8 to CP1250. But I cannot guarantee it'll always work because there simply is no encoding specified for CSV.


Q:

How to add something to a linked list

I'm just a little bit confused about an error I'm getting.  I've made a class called "SensorNode", and each SensorNode has a linked list of sensors.  One data member of SensorNode is a SensorBlock(the linked list) pointer called mySensors.  mySensors is supposed to point to the first sensor in the linked list of sensors owned by the sensor node it's in.  Here's the class declaration for SensorNode:
class SensorNode {
    char* NodeName;
    int NodeID;
    LOCATION Node1;
    float batt;
    int func;
    SensorBlock *mySensors;

public:
    SensorNode(char *n, float x, float y, float z, int i, float ah);
    void print();
    void setOK(int o);
    int getOK();
    void setLOC(float longi, float lat, float h);
    int amIThisSensorNode(char *n);
    void addSensorToNode(sensor *s);
};

and here's the class declaration for SensorBlock:
class SensorBlock {

    friend class SensorNode;
    SensorBlock * LLelement;
    sensor * SensEl;
};

my problem is with my void addSensorToNode(sensor *s) function.  Argument s points to a sensor which is supposed to be added to the end of the list of sensors that belong to that node.  And I can't figure out how to do that since it's not a new sensor that I'm creating and adding, but a pointer to a sensor that I'm adding.
Here's what I have so far:
void SensorNode::addSensorToNode(sensor *s) {
    if(mySensors == '\0') //mySensors is first initialized to NULL
    {
        mySensors = s; //I get an error on this line.
    }
    else {

    }
}

I don't know how to fix the error I get on that above line, and I don't know what to put in the "else" when mySensors is no longer equal to null.  If I solved the above error I might be able to better understand the addition process for a new sensor.  Thank you in advance for any help you can offer!!

A:

mySensors = s should be mySensors.SensEl= s
Because mySensors  is of type SensorBlock while s is a sensor
void SensorNode::addSensorToNode(sensor *s) {
    if(mySensors == NULL) //mySensors is first initialized to NULL
    {
        mySensors = new SensorBlock();
        mySensors->SensEl = s; //I get an error on this line.
        mySensors->LLelement = NULL;
    }
    else {

       SensorBlock newBlock = new SensorBlock();
       newBlock->SensEl = s;
       newBlock->LLelement = NULL;
       mySensors->LLelement = newBlock;

    }
}


Q:

How to store multiple value in single variable in uitableview didselect method

I'm new to swift I don't know how to pass the multiplevalues in single value. I can use multiple selection when to passinto the next page.so how to store the mutiple values in singlevalue.any one help me?? my code is
var strRoomType = ""
var strroomtype = []
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    let proModel = arrSpaceData[indexPath.row] as? RoomPropertyModel
    let propertyView = self.storyboard?.instantiateViewController(withIdentifier: "DepartureLocationVC") as! DepartureLocationVC
    propertyView.strRoomType = (proModel?.property_id as String?)!
  //  propertyView.strroomtype = (proModel?.property_id as String?)!
    self.navigationController?.pushViewController(propertyView, animated: true)
}

A:

You will have to collect the indexpaths of all the selected rows. Get the array objects/models of selected indexpaths and store them in a single array. Then you can pass that entire array to the next viewcontroller or wherever you want to use. If you are going to navigate to next viewcontroller on row selection, you will always have one object/model and so you won't need an array. You can simply pass entire object/model to the next viewcontroller.

A:

Say that you have two Controllers where one displays a list of students inside a TableView, then the other controller gets pushed and only displays a single student info.
First, you'd need to group all needed info into either a struct or class, I'll use struct since it's value type. (look up reference vs value type if you don't know it)
struct Student {
   let name: String  // using let prevent your fields from being changed or mutated
   let age: Int
}

Assume that we're into the first Controller that contains the UITableView

This would be how you'd go about setting the your tableView:
1) The array that populate the tableView will look like arr = [Student]()
2) Say that you are using a default UITableViewCell, you'd set the fields like  cell.textLabel.text = arr[indexPath.row].name, and cell.detailTextLabel?.text = String(arr[indexPath.age])
3) numberofitemsinsection would be arr.count
I mean you get the gist...
   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        /* here you have many options
           on how to pass the **selected data** to the detail controller.
         1) injecting the data into the detail controller via the initializer/ constructor
         2) via property
         3) injecting via method such as func setStudent(_ student: Student)
         4) etc...
        */

       let vc = DetailViewController(student: arr[indexPath.row])
       self.navigationController?.pushViewController(vc, animated: true)
    }

DetailViewController

final class DetailViewController: UIViewController {
   private let student:Student
   private let nameLabel:UILabel ....

   init(student: Student) { //<--- injecting the student object into the controller
     self.student = student
     self.init(nibName: nil , bundle: nil)
   }

  // now you have the student do whatever you want with it
  override func viewDidLoad() {
      super.viewDidLoad()
       nameLabel.text = student.name
   }
}


Q:

How do you name 'back-reference' properties?

I'm working on a project which has a rich domain-model.
Some of my classes have collections of other types, and those other types have a property that refers back to their 'owner'.
This sounds maybe a bit cryptic, so a code example would help:
public class Product
{
    private IList<ProductPrice> _prices = new List<ProductPrice>();

    public void AddPrice( ProductPrice price )
    {
       price.Product = this;
       _prices.Add (price);
    }
}

public class ProductPrice
{
    public DateTime ValidationDate {get; set;}
    public Decimal  Price {get; set;}
    public Product Product {get; set;}
}

The question is: what name do you prefer for the 'Product' property of the ProductPrice class ?
Would you name it:
- Product (like it is now)
- Owner
- BelongsTo
- something else ?

A:

Product - there's no ambiguity and the naming is consistent - Product stays Product everywhere.
If accessing the property from outside, I'd prefer having this:
price.Product.Name

than this:
price.Owner.Name


Q:

A Game of Dice and Logic II

Part 1, same game rules, slightly different cards
This question is broken - my program for proper analysis failed in some catastrophic way, and the question does not work as planned.
The intended solution is below in spoilers.

A friend and I are playing a cooperative game. He has two D7 dice and 5 cards in front of him. They read;
HIDDEN IS < SHOWN
HIDDEN IS EXACTLY ONE AWAY FROM SHOWN
HIDDEN IS ONE OF 1/4/7
HIDDEN PLUS SHOWN IS A MULTIPLE OF 4
THIS DIE CANNOT BE PLACED ANYWHERE ELSE

The game works as thus; my friend rolls two dice and looks at both of them. He then places one of those two dice on one card (thereby revealing it to me). That die is the SHOWN die, and the one he did not place is the HIDDEN die. He may only play a die on a card if that placement would make a true statement.
He paused as he looks at his dice.
"Well, either of my dice could only go on one card."
He paused again, deep in thought. He revealed a die and placed it on a card.
"That still isn't enough for me to know what your other die is," I said, exasperated.
"Yeah, but if I had placed the other die, you would have said the same thing!" he exclaimed.
"Well, why didn't you?" I questioned.
"Because at least this way, you had a better chance of guessing my hidden die."
What die did he place, where did he place it, and what is the hidden die?

Very mild aid (as said in comments below);

The order in which the statements were said aloud are NOT the same order they logically evaluate, and it makes a difference.

There seems to he confusion, so here is the restated problem, proper logic chronologicality intact.
My friend has two dice and tells me that his first die could only go on one card, and his second die can only go on one card. These cards may but need not be the same card.
He then thinks for a moment, and realizes that no matter which die he plays, I still wont know which die he has hidden, so decides to place the die that grants me the highest odds of guessing correctly, given that I only saw what die he placed on which card, and he hadn't given me any additional clues at that point (except the one-card clue)
If there is still confusion tomorrow, I will post my analysis then as a top-level with the full patterned reasoning.

Intented, but faulty solution below;

First of all, why did this question not work? For some reason, the language I was using the the analysis did not see 5+7 as a divisble-by-four pair, so 2-7 with 2 being played was the "intended" solution - as I was on the bus today, looking over the answers, I couldn't see the fault in logic. Then I checked my program, and it *also8 seemed correct.

For some weird reason, when I ran 5+7%4 by itself, it did not pop out zero, which is particularly odd.
Apologies for the error, I'll leave this up simply as a testament to this failure of a question.

A:

I can only uniquely determine the pair of dice that the friend rolled, but I am unable to determine conclusively which of those two dice he showed to the narrator, because the odds of guessing the other seem to me THE SAME in either case.
First, I believe that the rolled dice are:

 2 and 7

My reasoning is as follows:

 from all the possible pairs that may be rolled, because of the single-card rule, we can eliminate all of the following for the following reasons:-pairs that are one apart, as the Greater (G) die can be placed on both cards 1 and 2.-non-identical pairs that sum to a multiple of 4, as the G can be placed on both cards 1 and 4-non-identical pairs in which both dice are among 1/4/7, as the G die can be placed on both cards 1 and 3-non-identical pairs where the Lesser (L) die is 1, as the G die can be placed on both cards 1 and 3.-non-identical pairs where the L die is 4, as the G die can be placed on both cards 1 and 3.-the combination 4,4, as both dice can go on cards 3 and 4.That leaves the following combinations:1,1  2,2  2,4  2,5  2,7  3,3  3,6  3,7  5,5  6,6  7,7Both players know this information, as the friend tells the narrator that each die can only go on one card.Now, from the statement that the friend chooses to place the die that gives the highest odds of guessing, we can assume that the friend did not role an identical pair combo, which means the friend only rolled 2,4  2,5  2,7  3,6  or 3,7.Specifically, these dice in these combos could be placed on the following cards:-2,4 (L on card 3, G on card 1)-2,5 (L on card 5, G on card 1)-2,7 (L on card 3, G on card 1)-3,6 (L on card 5, G on card 1)-3,7 (L on card 3, G on card 1)For four of these five possibilities, it is possible to show one die and have the other be conclusively determined, because there is only one outcome which would not violate the single-card rule:2,4: if the 4 is shown on card 1, the narrator can conclude the pair must be 2,42,5: if the 5 is shown on card 1, the narrator can conclude the pair must be 2,53,6: if the 6 is shown on card 1, the narrator can conclude the pair must be 3,63,7: if the 3 is shown on card 3, the narrator can conclude the pair must be 3,7From this, we can conclude that the friend must have rolled 2,7.At this point, it seems to me that no matter which of these dice is shown, the narrator will have exactly two valid guesses:If the 2 is shown on card 3, the narrator can determine that either 2,4 or 2,7 was rolled.If the 7 is shown on card 1, the narrator can determine that either 2,7 or 3,7 was rolled.To me, it seems that the odds of the narrator guessing correctly are the same in either case.


Q:

When italicizing a noun to emphasize, italicize the article or not?

When I want to emphasize a noun by italicizing, do I need to italicize the article of the noun or not? For example, is this correct?

"Is it an apple?"
"No, it is an orange."

Or, is this correct?

"Is it an apple?"
"No, it is an orange."

A similar question for the.

It is called the curse of dimensionality.

Or

It is called the curse of dimensionality.

A:

Because italicizing for emphasis can select any word as well as parts of words, italicizing an article means that you are emphasizing that article for some purpose. Compare:

"Is it a orange?"
"No, it is an orange."  (An emphasized in contrast to "a.")

"Is it an apple?"
"No, it is an orange." (Orange emphasized in contrast to "apple.")

Stylistically, it is better to omit italics if they aren't necessary for a given purpose, since emphasis is watered down with frequent use. That is one reason why both MLA and APA recommend minimizing the use of italics for emphasis, and why more colloquial guides recommend against overuse ("but don't overwork this device"). So there's no strict rule that demands you include the article, and an expectation that you have a deliberate reason for italicizing something. The rest is your decision.


Q:

nvarchar & varchar with Oracle & SQLServer

I need to upload some data from an Oracle table  to a SQL Server table. The data will be uploaded to the SQL server using a Java processing utilising JDBC facilities.
Is there any benefit in creating the SQL server columns using nvarchar instead of varchar?
Google suggests that nvarchar is used when UNICODE characters are involved but i am wondering does nvarchar provide any benefit in this situation? (i.e. when the source data of the SQL Server table comes from an Oracle database running a Unix environment?)
Thanks in advance

A:

As you have found out, nvarchar stores unicode characters - the same as nvarchar2 within Oracle. It comes down to whether your source data is unicode - or whether you anticipate having to store unicode values in future (e.g. internationalized software)