Q:

All of my pages have class "page--node-" on the body element. This doesn't seem right

I'm trying to track down the source of some CSS issues I'm having on my site and I noticed that every page has class "page--node-" added to the <body> element. The theme hook suggestions seem to include page__node__%.
This looks weird. Is it supposed to be like this, or is there a problem in a theme hook suggestion generated somewhere? I'm using a subtheme of Zen 5.

A:

Classes beginning with page generally come from drupal core in template_preprocess_html(), which calls theme_get_suggestions() to do the heavy lifting.
That function makes a bunch of suggestions for the classes or template suggestions based on the path of the current page. The % is used as a wildcard for numeric arguments (in this case the node id).
Then back in template_preprocess_html() it passes the suggestions through drupal_html_class(), which in turn runs them though drupal_clean_css_identifier(), which strips out characters not allowed in a class, including the %, so you get a class of page-node- (this seems like a bug but there is a use for it I will explain below).
This theme_get_suggestions() code is the same reason you have the template suggestion with the percent symbol.
This means you can affect all node pages by using the template name page--node--%.tpl.php.
That might not seem necessary because you also have page--node.tpl.php, however if you want a different template for the path /node than you do for individual node pages you need to use both page--node.tpl.php and page--node--%.tpl.php.
This same reason is why the unusual class is useful.
If you want to style the /node page differently from individual node pages you can style page--node differently from page--node-
I agree it is a silly looking class though with pretty limited (or maybe none) documentation.
Also, something I found after writing this that is useful is How Drupal determines page theme hook suggestions based on path, from the "Drupal 7 Template (Theme Hook) Suggestions" documentation page.


Q:

How to find only SD card movable applications on the market?

As I do not have more free space on my HTC Desire, I am interested only in applications which can be moved to the SD card. How to find them on the market (via web interface, or on the device, does not matter) ?

A:

The Market doesn't support this (or any search filters aside from price and "safe search", really) on either the website or the native app. It has been requested a handful of times on the Google support forums, but never really received much of a response.
AppBrain does support this, however (example search), so you could use that to search and then install from the Market if you wanted. Inconvenient, but at the moment there's not much else you can do about that.


Q:

can't get frame of collectionViewCell item for transition

I am trying to transition a view into the imageView of a  collectionViewCell of another viewController.  In order to do that I need the frame of the imageView in the collectionViewCell converted to Window.
I am trying to do that using the following in viewWillAppear:
let indexPath = IndexPath(item: 0, section: 0)
let cell = collectionView.cellForItem(at: indexPath) as! ImageCollectionViewCell
let boundingRect = cell.imageView.convert(cell.imageView.bounds, to: nil)

The size of the boundingRect is correct however the origin is at 0,0 for some reason and not where it should be.
I'm wondering if the problem is that the collectionView is not laid out yet and thus the origin is wrong.  If that's the case, how can I force it to layout.  I have tried:
collectionView.setNeedsLayout()
collectionView.layoutIfNeeded()

But that also didn't change the origin.
How could I force the layout of the collectionView and get the frame of a particular cell (or imageView in that cell) prior to viewDidAppear.  I would like to avoid doing it in viewWillLayoutSubviews or viewDidLayoutSubviews to prevent this from constantly being run.

A:

According to https://developer.apple.com/documentation/uikit/uiview/1622498-convert we need:

view (collectionView.superview), where we want to get subview's
location,
subview's frame (cell.imageView.frame)
and subview's superview or superview.superview etc, any view that contains subview's frame (cell)

and we get
let boundingRect = collectionView.superview.convert(cell.imageView.frame, from: cell)


Q:

WinAPI: How to get the caps lock state?

How can get whether Caps Lock is on or off?
I tried to search it but all I'm finding is how to toggle or turn it on/off which is exactly opposite of what I'm looking for.
I'm trying to do that in both C++ and Delphi.
Please help

A:

I found this link and the code snippet below that might help you
if ((GetKeyState(VK_CAPITAL) & 0x0001)!=0)
  AfxMessageBox("Caps Lock ON!");
else
  AfxMessageBox("Caps Lock OFF!");

A:

You want the GetKeyState() function:
http://msdn.microsoft.com/en-us/library/ms646301(VS.85).aspx
with the VK_CAPITAL key code. Rest of the virtual key codes are here:
http://technet.microsoft.com/en-us/subscriptions/index/dd375731(v=vs.85).aspx


Q:

'MKPinAnnotationView' is not convertible to '()'

I'm trying to translate/convert piece of Objective-C code to Swift.
Here's the Objective-C original:
#pragma mark - MKMapViewDelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKPinAnnotationView *annotationView = nil;
    if ([annotation isKindOfClass:[PlaceAnnotation class]])
    {
        annotationView = (MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:@"Pin"];
        if (annotationView == nil)
        {
            annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Pin"];
            annotationView.canShowCallout = YES;
            annotationView.animatesDrop = YES;
        }
    }
    return annotationView;
}

Here's the Swift:
func mapView(mapView:MKMapView, annotation:MKAnnotation) {

    var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("Pin") as? MKPinAnnotationView

    if annotationView == nil {
        annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "Pin")
        annotationView!.canShowCallout = true
        annotationView!.animatesDrop = true
    }

    return annotationView
}

Here's the error:

I don't fully understand what the compiler is trying to say to me.
'annotationView'class is a subclass to the function's return type: MKAnnotationView.

A:

Your func signature is missing the return type:
func mapView(mapView:MKMapView, annotation:MKAnnotation) -> MKPinAnnotationView {

without an explicit return type, swift defaults to an empty tuple, which means no return type - that is what the error message says,  maybe not in an explicit way :)


Q:

how to use codebehind with a Hub in XAML?

I want to create a Hub in XAML that contains a Grid of my construction
I then want to use code behind to set the values
Mikael Koskinen created a great blog entry (http://mikaelkoskinen.net/winrt-xaml-hub-control-getting-started-tutorial-semanticzoom)
The below sample is 100% his (thanks for the blog) - my question is - is there a better way?
<HubSection Header="Trailers">
    <DataTemplate>
        <ListView x:Name="MovieTrailers">

        </ListView>
    </DataTemplate>
</HubSection>

Even though we’ve given the ListView a name, we cannot access it from
  the code-behind:
This is because the control is inside a DataTemplate. One easy way to
  get around this limitation is to hook into the ListView’s
  Loaded-event. Here’s the XAML:

<ListView x:Name="MovieTrailers" Loaded="MovieTrailers_Loaded">

</ListView>

And the code behind:

private void MovieTrailers_Loaded(object sender, RoutedEventArgs e)
{
    var listView = (ListView)sender;
    listView.ItemsSource = trailers;
}

A:

I had the same problem and ended up following the XAML Hub control sample to solve it. It uses CollectionViewSource, and I think it's a better way than binding on the Loaded event.
First, define the CollectionViewSource.
<Page.Resources>
  <CollectionViewSource x:Name="YourCVS" />
</Page.Resources>

On the Hub's ListView bind it to the ItemsSource:
<Hub>
  <HubSection Header="ListView">
    <DataTemplate>
      <ListView ItemsSource="{Binding Source={StaticResource YourCVS}}">
        <!-- Your code to actually show things -->
      </ListView>
    </DataTemplate>
  </HubSection>
</Hub>

Add the data on code behind:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
   // code to populate the data...
   YourCVS.Source = yourListWithData;
}

I followed this instructions for my project, but I ended up doing the binding like this:
// View constructor
public HubView()
{
  this.InitializeComponent();
  this.WhenActivated(d =>
  {
    // ViewModel is a property of this view
    d(this.OneWayBind(ViewModel, x => x.MyListWithData, x => x.YourCVS.Source));
  });
}


Q:

C++ class naming convention for interface classes with a concrete and namespace subclasses

A convention is the letter "I" proceeding pure virtual interface classes. Often, I find that I also need a partial concrete class with some share functionality for subclasses. So,
class IFoo {...}
class Foo : public IFoo {...}

I run into naming conundrums when I want subclasses derived from Foo differentiated by namespaces. E.g.,
Bar::Foo
Baz::Foo

Because when I code
namespace Bar { class Foo : public Foo {} }

Not surprisingly, VS gives the error "a class cannot be its own base class". (Not an issue when there's no "intermediate class, because the naming is Bar::IFoo, and Baz::IFoo.) I can get around this with
class MyFoo : public IFoo
namespace Bar { class Foo : public MyFoo {} }

or
namespace base { class Foo : public IFoo {} }
namespace Bar { class Foo : public base::Foo {} }

But would prefer not to muddle naming.
I get that having classes Foo, Bar::Foo, and Baz::Foo is bad because of the obvious confusion. (E.g., adding "using Bas;" would introduce ambiguity.) Is there a naming convention or syntax that clearly relates what I'm trying to do?

A:

Acknowledging your comment that having all of these same-named types is a bad idea, you can specifically refer to a type in the global namespace by prefixing it with ::. In this case, that means you can refer to the type Foo from the global namespace, while in the context of a naming scope that defines its own Foo, by referring to the global one as ::Foo.  So this works:
class IFoo {};
class Foo : public IFoo {};

namespace Bar { class Foo : public ::Foo {}; }


Q:

The Web server is configured to not list the contents of this directory

Using Visual Studio 2012:

I created an "ASP.NET Empty Web Application" (using C#).
I used NuGet to install the FubuMVC package.
When I run the application (using IIS Express), I get the "Welcome to FubuMVC!" page which tells me to delete the FubuMVC.GettingStarted.dll file and to set the home page.
So I do both of those things, implementing a HomeController that simply returns "Hello World" from Index.

Rather than the expected "Hello World", I get an IIS error: The Web server is configured to not list the contents of this directory.
What have I done wrong?

A:

Just tried reproducing your problem with a brand new project; it turns out that problem is that the instructions in the example haven't kept up with the changes in FubuMVC.
The instructions tell you to create a class called 'MyHomeController' and add the Index() method to it. This used to work, because one of the default rules for routes was to use any class with a name that ends in 'Controller'.
But the default has been changed in more recent versions, and the rule now looks for classes ending in 'EndPoint'.
So if you change the name of the class from 'MyHomeController' to 'MyHomeEndpoint', it should work.
Also, remember that the application pool needs to restart for the new configuration to take effect, so you might have to touch your web.config (or force IISExpress to restart).


Q:

Speeding up MATLAB code for FDR estimation

I have 2 input variables:

a vector of p-values (p) with N elements (unsorted)
and N x M matrix with p-values obtained by random permutations (pr) with M iterations. N is quite large, 10K to 100K or more. M let's say 100.

I'm estimating the False Discovery Rate (FDR) for each element of p representing how many p-values from random permutations will pass if the current p-value (from p) will be the threshold.
I wrote the function with ARRAYFUN, but it takes lot of time for large N (2 min for N=20K), comparable to for-loop.
function pfdr = fdr_from_random_permutations(p, pr)
%# ... skipping arguments checks
pfdr = arrayfun( @(x) mean(sum(pr<=x))./sum(p<=x), p);

Any ideas how to make it faster?
Comments about statistical issues here are also welcome.
The test data can be generated as p = rand(N,1); pr = rand(N,M);.

A:

First of all, tr to analyze this using the profiler. Profiling should ALWAYS be the first step when trying to improve performance. We can all guess at what is causing your performance drop, but the only way to be sure and focus on the right part is to inspect the profiler report.
I didn't run the profiler on your code, as I don't want to generate test data to do so; but I have some ideas about what work is being carried out in vain. In your function mean(sum(pr<=x))./sum(p<=x), you are repeatedly summing over p<=x. All in all, one call includes N comparisons and N-1 summations. So for both, you have behavior that is quadratic in N when all N values of p are calculated.
If you step through a sorted version of  p, you need less calculations and comparisons, as you can keep track of a running sum (i.e. behavior that is linear in N). I guess a similar method could be applied to the other part of the calculation.
edit:
The implementation of my idea as expressed above:
function pfdr = fdr(p,pr)
[N, M] = size(pr);
[p,   idxP] = sort(p);
[pr] = sort(pr(:));

pfdr = NaN(N,1);

parfor iP = 1:N
    x = p(iP);
    m = sum(pr<=x)/M;
    pfdr(iP) = m/iP;
end

pfdr(idxP) = pfdr;

If you have access to the parallel computing toolbox, the parfor loop will allow you to gain some performance. I used two basic ideas: mean(sum(pr<=x)) is actually equal to sum(pr(:)<=x)/M. On the other hand, since p is sorted, this allows you to just take the index as the number of elements (in the assumption that every element is unique, otherwise you'll have to work with unique to do the full rigorous analysis).
As you should already know very well by running the profiler yourself, the line m = sum(pr<=x)/M; is the main resource hog. This can be tackled similarly to p by making use of the sorted nature of pr.
I tested my code (both for identical results and for time consumption) against yours. For N=20e3; M=100, I get about 63 seconds to run your code and 43 seconds to run mine on my main computer (MATLAB 2011a on 64 bit Arch Linux, 8 GiB RAM, Core i7 860). For smaller values of M the gain is larger. But this gain is in part due to parallelization.
edit2: Apparently, I came to very similar results as Andrey, my result would have been very similar had I pursued the same approach.
However, I realised that there are some built-in functions that do more or less what you need, i.e. quite similar to determining the empirical cumulative density function. And this can be done by constructing the histogram:
function pfdr = fdr(p,pr)
[N, M] = size(pr);
[p, idxP] = sort(p);

count = histc(pr(:), [0; p]);
count = cumsum(count(1:N));

pfdr = count./(1:N).';

pfdr(idxP) = pfdr/M;

For the same M and N as above, this code takes 228 milliseconds on my computer. It takes 104 milliseconds for Andrey's parameters, so on my computer it turns out a bit slower, but I think this code is far more readable than intricate for loops (as was the case in both our examples).

A:

Well, the trick was indeed sorting the vectors. I give credit to @EgonGeerardyn for that. Also, there is no need to use mean. You can just divide everything afterwards by M. When p is sorted, finding the amount of values that are less than current x, is just a running index. pr is a more interesting case - I used a running index called place to discover how many elements are less than x.
Edit(2):  Here is the fastest version I come up with:
 function Speedup2()
    N = 10000/4 ;
    M = 100/4 ;
    p = rand(N,1); pr = rand(N,M);

    tic
    pfdr = arrayfun( @(x) mean(sum(pr<=x))./sum(p<=x), p);
    toc

    tic
    out = zeros(numel(p),1);
    [p,sortIndex] = sort(p);
    pr = sort(pr(:));
    pr(end+1) = Inf;
    place = 1;
    N =  numel(pr);
    for i=1:numel(p)
        x = p(i);
        while pr(place)<=x
            place = place+1;
        end
        exp1a = place-1;
        exp2 = i;
        out(i) = exp1a/exp2;
    end
    out(sortIndex) = out/ M;
    toc
    disp(max(abs(pfdr-out)));

end

And the benchmark results for N = 10000/4 ; M = 100/4 :

Elapsed time is 0.898689 seconds.
  Elapsed time is 0.007697 seconds.
     2.220446049250313e-016

and for N = 10000 ; M = 100 ;

Elapsed time is 39.730695 seconds.
  Elapsed time is 0.088870 seconds.
     2.220446049250313e-016


Q:

Pandas Time Series - add a value to the first value in each year

I have a Pandas time series with unevenly spaced dates/datapoints. I want to add 1 to the value of each data point that is the first value for each year.
The time series is very sparse and the data is sorted.
Is there a better way to do this then by looping through all data points and checking when the year changes?
Example:
dates = [datetime(2012, 1, 1, 1, 1), datetime(2012, 1, 1, 1, 2), datetime(2012, 1, 2, 0 ,0), datetime(2013, 1, 2, 0, 0), datetime(2014, 1, 3, 1, 1)]

ts = Series(np.random.randn(len(dates)), dates)

Using the example above I want to add 1 to value on 2012-01-01 01:01:00, 2013-01-02 00:00:00 and 2014-01-03 01:01:00

A:

Sure. You can extract the year:
ts.index.year

Find where the adjacent difference is nonzero:
np.diff(ts.index.year) != 0

Remember that you also want to select the very first data point:
np.concatenate(([True], np.diff(ts.index.year) != 0))

And then modify those data points:
ts[np.concatenate(([True], np.diff(ts.index.year) != 0))] += 1


Q:

Validate if a property in my model is higher than another property

I have this model which contains the two following properties:
public int m_ID
public int m_NbrInStock
public int m_QtyToShow

Here is I actually render my view:

    @using (Html.BeginForm("SendItems", "Inventory"))
    {

            Select / UnSelet All Items @Html.CheckBox("selectAll", true)

                Obj Name
                Number In Stock
                (...)
                Quantity

            @for (int i = 0; i < Model.Count(); i++)
            {

                    @Html.DisplayFor(x => x[i].m_Card.m_CardName)
                    @Html.DisplayFor(x => x[i].m_NbInStock)
                    (...)

                        <input type="checkbox" name="itemSending" class="divChckBox" checked="true" value="@Model[i].m_ID"/>

                    @Html.TextBoxFor(x => x[i].m_QtyToShow

            }

            <input type="submit" value="Send"/>

    }

I have many problems here:

First of all, I need to keep the QtyToShow as it will later be used for data managing, but the data does not survive the model because of the HTTPPost;
I also need to validate that QtyToShow is never higher than m_NbrInStock or show an error message if that's the case.

This is not a simple task and since I don't have much experience in MVC development I don't know how I could do this. Can you help me out? Thank you.

A:

Two ways to do this:

Validate the data manually in the controller
Write a custom validator

The first one is the easiest, the second is a better practice.
To get you off the ground and get your app working, you can implement the first way, and then come back and refactor when you're more comfortable with mvc.
So add a property to your viewModel
public string QuantityValidationMsg {get; set}

Then in your view display the message
@Html.TextBoxFor(x => x[i].m_QtyToShow
 @Html.DisplayFor(x => x[i].m_QuantityValidationMsg)

Then in your post action (which needs to accept a List<yourViewModel>, not a List<int>, btw)
viewModel.QuantityValidationMsg = null;
if (viewModel.QtyToShow > viewModel.NbrInStock)
{
  viewModel.QuantityValidationMsg = "Error Message!";
}

For the second approach, you would create a new class that implements ValidationAttribute
and define something along the lines of:
public class ValidateQuantity : ValidateAttribute
{
  private const string MESSAGE = "Error Message";
  public ValidateQuantity (int qtyInput, int qtyConfirm)
      : base( MESSAGE )
  {
     Input = qtyInput;
     Confirm = qtyConfirm;
  }

  public int Input {get; private set;}
  public int Confirm {get; private set;}

  public override bool IsValid (object value)
  {
    var properties = TypeDescriptor.GetProperties(value);
    var input = properties.Find(Input, false).GetValue(value);
    var confirm = properties.Find(Confirm, false).GetValue(value);
    if( input > confirm)
    {
      return false;
    }
    return true;
  }
}

Then decorate the model property with the new attribute
public int m_ID
public int m_NbrInStock

[ValidateQuantity]
public int m_QtyToShow

And add the validation message in the view
@Html.ValidationMessageFor(m => m.m_QtyToShow)


Q:

Extracting a nested tuples from list (Python)

I have a list that has nested tuples.
nested = [['53062423-690f-4923-8f65-db710c038566', [('12253996-b2f7-46c7-b49f-09ca87cac84f', 'AFC_PoCv1.0'), ('b17bd025-611f-4728-9396-e59388ee59f6', 'Customer Profitability Sample'), ('b4a5d199-2c6f-4f8d-9fcb-5e4971254f73', 'Jammers vs Floaty Pants')]], ['988f64ea-14b2-4ad7-a899-ae40974c9139', [('9137e0f9-4063-479a-baff-8566c91302ff', 'DailySalesDashboard13Azure')]]]

I want to flatten the list into a pandas dataframe.
df = pd.DataFrame(nested, columns =('id', 'This column of tuples needs to split into two'))
df

results in,

but doesn't split the tuples into two columns with one tuple per row (with the associated id as the 3rd column).  Feels like a simple list comprehension- but I have come up blank.
Any help would be greatly appreciated.

A:

We do explode
s = pd.DataFrame(nested,columns=['c1','c2']).explode('c2').reset_index(drop=True)
# if only need to split the tuple , you do not need to do the next steps

Split the tuple into single columns
s = s.join(pd.DataFrame(s['c2'].tolist()))
s
Out[162]:
                                     c1  ...                              1
0  53062423-690f-4923-8f65-db710c038566  ...                    AFC_PoCv1.0
1  53062423-690f-4923-8f65-db710c038566  ...  Customer Profitability Sample
2  53062423-690f-4923-8f65-db710c038566  ...        Jammers vs Floaty Pants
3  988f64ea-14b2-4ad7-a899-ae40974c9139  ...     DailySalesDashboard13Azure
[4 rows x 4 columns]


Q:

Access Data Management issue

I am facing problem in Data Management in MS Access.I have two coloumn i.e sku and child sku.Each parent sku have child sku in front and same child sku exist in parent column on some other sequence/Place.What i require is to display child sku value along with parent sku.Present data is given below.
Parent SKU    Child Sku
vou1          adf1
vou2          adf2
vou3          adf3
tu1
tu2
tu3
adf1
adf2
adf3

What i require is to display data in below mentioned format
Parent SKU    Child Sku
vou1          adf1
vou2          adf2
vou3          adf3
adf1
adf2
adf3
tu1
tu2
tu3

If possible please help to resolve this data Sort/Management issue--thanks.

A:

I think I understand what you are getting at.  You want to link the Child Sku record to the Parent Sku record so you can access the data from both.  You can do a self join to accomplish this:
SELECT ct.*, pt.*
FROM MyTable pt
INNER JOIN MyTable ct ON ct.[Child Sku] = pt.[Parent Sku]

Then change ct.* and  pt.* to the actual fields you want.


Q:

Probe in Linux DevFreq Driver Not Being Called

I am trying to set up a devfreq driver for a peripheral on Linux. My init method for the driver looks as follows:
  static struct platform_driver zynq_csortfreq_driver = {
    .probe  = zynq_csortfreq_probe,
    .driver = {
        .name   = "ZYNQ_CSORT_DEVFREQ",
        .owner  = THIS_MODULE,
    },
  };

static int __init zynq_csortfreq_init(void)
{
    return platform_driver_register(&zynq_csortfreq_driver);
}
late_initcall(zynq_csortfreq_init);

However, the probe function (zynq_csortfreq_probe) in my driver never seems to get called. I've read that in order for the probe call to work correctly, the .name value of the driver must match the name of the device - where can I find the name of the device?

A:

In order for the probe function to be called, you must add a device from a machine file or via the device tree. This is typically done with platform_device_register() or platform_add_devices() in machine files.  Alternatively, of_platform_populate() is used for the device tree model, but code does not use this directly.  The platform device documentation has information for your Linux kernel version.  It seems that your Linux uses the device tree model.  The documentation in the cpufree devicetree will have some helpful information on activating your driver for this board with device trees.
The dtsi file needs something like,
 soc {
     zyncfreq@addr {
          compatible="xxxx"
          /* Other platform data */

Which will define the device for your machine.  I would suggest that first you modify your machine files init_machine entry and use platform_device_register() to associate your driver with a device.  Then you can later attempt to get the device tree mechanism working if you wish.
If you can view this closed question, my answer might be helpful if the Linux device-model documentation is not completely clear.  However, I think for your case the Linux docs are sufficient.


Q:

How to change value of a selection using Python on Tryton

Is there a way to change selection field value using Python and I didn't find any documentation to use .
The state field is a field that describe a treatment state
I wish to do something like :
state=fields.Selection([
        ('stopped', 'Stopped'),
        ('wait', 'Wait'),
        ('finished', 'finished'),
        ], 'State', readonly=True)

def changeselectionvalue(self,state)
    self.state=state #something to do this

Help me please I am a new user of a Tryton

A:

Just use the write API:
records = Model.search([]) #Get all the records you wan to write.
Model.write(records, {'state': 'new_state'})

Or the ActiveRecord pattern:
self.state = 'new_state'
self.save()

'new state' must be one of the internal values of the selection.
The first is recomended when you have to update more than one record in a bunch.
If you're model subclasses the Workflow class, It's recommended to use the @Workflow.transition(new_state) decorator in order to change the state of the records, as it only updates the records for which the transition is valid.


Q:

why do CPU architectures use a flags register (advantages?)

Some CPUs have a flags register (ARM,x86,...), others don't (MIPS,...). What's the advantage of having a CMP instruction to update the flags register followed by a branch instruction instead of using a zero register and conditional branches to check for sign, overflow etc?

A:

In modern micro-architectures with register renaming the implementation cost for flags or not flags is pretty similar.  The main difference I can think of is that some flags indicate the characteristics of a value (Is the value negative?  Is the value zero?  Does the value have even or odd parity?), while some represent an event that occurred during a previous operation (did the add instruction have a carry out or an overflow?)  This led to a less-than-ideal situation on the MIPS when you wanted to simulate 64-bit addition on the 32-bit architecture (or 128-bit addition on the 64-bit architecture.)  On most architectures with a carry flag there is a special add-with-carry instruction, that includes the carry flag from the previous add instruction.  This makes simulating multi-precision arithmetic relatively inexpensive on many architectures with flags registers.
On the flip side, testing an N-bit register for zero or not-zero is actually surprisingly expensive.  To test an N-bit register for zero you need to perform an N-bit NOR operation, which requires $O(\log N)$ levels of logic to calculate.  On architectures with flags registers the extra logic for the zero/not-zero calculation at the end of the ALU stage can cause the clock to run slower (or force the ALU to have two cycle operations.)  For this reason, I think, some architectures, like SPARC had two versions of each arithmetic operation, one that set flags and one that didn't.
But MIPS doesn't save anything here.  They just moved the problem somewhere else.  On MIPS there is a branch-on-equal instruction.  This means that the branch instruction must actually have an ALU stage (including something like a bitwise xor operation followed by a nor to reduce down to the single equal/not-equal bit) before determining which way the branch goes.
The DEC Alpha architecture tried to split the difference by using a trick.  DEC Alpha had no flags registers, but also didn't have a branch-on-equal instruction.  Instead the branch instructions all look at the state of a single general purpose register.  There is branch-on-zero, branch-on-not-zero, branch-on-less-than-zero, etc.  The trick is that you can give every general purpose register an extra 65th bit that tells you whether the other 64 bits are all zero or not.  This makes it more like having a flags register: all the branch instructions look at a single bit (that is already calculated) to make their decision, but now you are back to figuring out how to calculate that extra zero indicator bit during a normal ALU cycle.  (And you still can't do multi-precision arithmetic just by looking at the carry flag from the previous operation.)

A:

1 From an ISA perspective

Having test instructions which set only the flags is just a way to reduce the register pressure in register starved architectures.  If you have enough registers, just modify one of them and ignore the result. The trick of having a register 0 with input value 0 is just an encoding trick convenient when you have enough registers that fixing one of them to 0 is better than increasing the number of instructions.  It is then convenient to use it as a target as well (it reduces the number of false dependencies).
Encoding again.  If you encode the condition in jumps, you'll have jumps with 3 operands (the two to be compared and the jump target), two of which you'd like to be immediate values, one you'd like to be as big as possible (jumps have often their own encoding format so that the target can use as many bits as possible). Or you drop possibilities.
Using flags gives you more opportunities to set them.  It is not just the comparison operations which can set the flags, but whatever you want. (With the caveat that the more operations you have which set flags, the more careful you have to be to ensure that the last operation which set the flags is the one you want).  If you have flags, you are able to test the number of conditions (often 16) multiplied by the number of instructions which are able to set the flags (If you are not using flags, you end up with about as many conditional jumps as you have things to test or there are things you don't allow to test as easily (carry or overflow for instance).

2 From an implementer perspective

Testing flags is easy and can be done quickly.  The more complex your test is, the more effect it will have on the cycle time (or the pipeline structure if you are pipelined).  That's especially true for simpler implementations, when you get to a high end processor using all the tricks of the book, the effect is pretty minimal.
Having flags means that a lot of instructions have multiple results (the natural result and each of the modified flags).  And from a micro-architecture POV, multiple results are bad (you have to keep track of their association).  When you have just one set of flags, that introduce dependencies (unneeded if the flag is not then used) you have to handle way or another. Again that's especially true for simpler implementations, when you get to an high end processor using all the tricks of the book, the additional difficulties are dwarfed by the rest of the processor.


Q:

Error pushing flow to REST ODL API with Postman

I am trying to push this flow to the REST API of the Nytrogen distribution of ODL with this URL:

http://192.168.21.144:8181/restconf/config/opendaylight-inventory:nodes/node/openflow:1/flow-node-inventory:table/0/flow/100/instructions/instruction/3

..and this body:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<flow xmlns="urn:opendaylight:flow:inventory">
<flow-name>push-mpls-action</flow-name>
<instructions>
    <instruction>
        <order>3</order>
        <apply-actions>
            <action>
                <push-mpls-action>
                    <ethernet-type>34887</ethernet-type>
                </push-mpls-action>
                <order>0</order>
            </action>
            <action>
                <set-field>
                    <protocol-match-fields>
                        <mpls-label>27</mpls-label>
                    </protocol-match-fields>
                </set-field>
                <order>1</order>
            </action>
            <action>
                <output-action>
                    <output-node-connector>2</output-node-connector>
                </output-action>
                <order>2</order>
            </action>
        </apply-actions>
    </instruction>
</instructions>
<strict>false</strict>
<id>100</id>
<match>
    <ethernet-match>
        <ethernet-type>
            <type>2048</type>
        </ethernet-type>
    </ethernet-match>
    <in-port>1</in-port>
    <ipv4-destination>10.0.0.1/32</ipv4-destination>
</match>
<idle-timeout>0</idle-timeout>
<cookie_mask>255</cookie_mask>
<cookie>401</cookie>
<priority>8</priority>
<hard-timeout>0</hard-timeout>
<installHw>false</installHw>
<table_id>0</table_id>
</flow>

And the REST API give to me this:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Error 415 Unsupported Media Type</title>

HTTP ERROR 415

Problem accessing /restconf/config/opendaylight-inventory:nodes/node/openflow:1. Reason:

    Unsupported Media Type

        Powered by Jetty://

The xml was from opendaylight examples so I think that I am doing something wrong writting the URL.

A:

try with just this URL:
http://192.168.21.144:8181/restconf/config/opendaylight-inventory:nodes/node/openflow:1/flow-node-inventory:table/0/flow/100
(basically removing the "instructions/instruction/3")


Q:

Strangely slow: what happened when TakeWhile met AsParallel?

I know that wrong usage of linq may cause lower performance but this time it's too strange.
When i call "AsParallel.TakeWhile.AsParallel.ForAll", it's MUCH slower than "AsParallel.TakeWhile.ForAll". Can somebody explain why?
using System;
using System.Diagnostics;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Action<int> doNothing = i => { };

            var stopwatch = Stopwatch.StartNew();
            Enumerable.Range(1, 100).AsParallel().TakeWhile(m => m < 10)
                .ForAll(doNothing);
            var ticks1 = stopwatch.ElapsedTicks;

            stopwatch.Restart();
            Enumerable.Range(1, 100).AsParallel().TakeWhile(m => m < 10)
                .AsParallel() // spend much more time with this AsParallel
                .ForAll(doNothing);
            var ticks2 = stopwatch.ElapsedTicks;

            Console.WriteLine("ticks without AsParallel: {0}\r\n with AsParallel: {1}", ticks1, ticks2);
            //ticks without AsParallel: 87956
            //with AsParallel: 6688708
            Console.Read();
        }
    }
}

A:

When you call AsParallel, the framework starts to divide the work into smaller parts which can be scheduled on different cores. These parts later needed to be merge back into the result. This causes some overhead.
You have already made the query parallel by the first "AsParallel" and when you call it the second time the partition happens again, causing even more overhead but giving you no performance boost.
See Understanding Speedup in PLINQ for more information.


Q:

Redirecting to route with text AND variables?

I'm currently using Laravel 4 and Sentry 2 for developing a pretty simple authentication system with throttling enabled. That said, when an exception is thrown as the user attempts to log in because he has been suspended, he should be redirected back to the login view with a message saying "This user has been suspender for $time minutes."
Problem is: I can't return both a variable and a text message to the view. Maybe I'm missing the correct syntax, I don't know. This has been driving me insane as I need to do it for many other exceptions. It seems to be a newbie issue an the solution should be pretty simple.
This is the part of my code which matters:
catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
{
    $throttle = Sentry::findThrottlerByUserLogin(Input::get('username'));
    $time = $throttle->getSuspensionTime();

     return Redirect::route('account-sign-in-get')
                    ->with('message','This user has been suspended for [$time] minutes.');

}

Thanks in advance.

A:

Just replace
->with('message','This user has been suspended for [$time] minutes.');
with
->with('message', "This user has been suspended for {$time} minutes.");
What was actually going on:
In PHP when you use single quote around a string, it does not parse the variable embedded in that string, but when you use double quote, it parses it.


Q:

Application of Lévy Zero-One Law

Question
  Let $(X_n)$ be a sequence of random variables taking values in $[0, \infty)$. Let $D=\{X_n=0\; \text{for some $n\geq 1$}\}$ and assume that
  $$
P(D\mid X_{1}, \dotsc, X_n)\geq \delta(x)>0
 \quad \text{a.s. on $\{X_n\leq x\}$}.\tag{0}$$
  Use Lévy's Zero-One Law to conclude that $P(D\cup \{\lim_{n} X_n=\infty\})=1$.

My attempt Let $\mathcal{F}_n=\sigma(X_1, \dotsc, X_n)$ and $\mathcal{F}_{\infty}=\bigcup \mathcal{F}_n$. Since $D\in \mathcal{F}_{\infty}$, Lévy Zero-One Law implies that
$$
P(D\mid \mathcal{F}_n)\to I(D)\tag{1}
$$
where $I$ is the indicator function. For $m\geq 1$ let  $A_m$ be the set on which $X_n\leq m$ eventually. By $(0)$ and $(1)$ it follows that $I(D)=1$ on the set $\bigcup_{m=1}^\infty A_m=\{\limsup X_n<\infty\}$ i.e.
$$
\bigcup_{m=1}^\infty A_m=\{\limsup X_n<\infty\}\subset D.
$$
Since $D\cup D^c\subset D\cup \{\limsup X_n=\infty\}$, it follows that $P(D\cup \{\limsup X_n=\infty\})=1$.
My problem
Assuming that everything above is correct, I have only been able to show that $P(D\cup \{\limsup X_n=\infty\})=1$. But ostensibly this is not enough since $P(D\cup \{\lim_{n} X_n=\infty\})\leq P(D\cup \{\limsup X_n=\infty\})$. Unless there is a typo in the question. But I got the question from Durrett.

A:

Hint: Let $B_m$ be the event that $X_n\le m$ infinitely often, and replace $A_m$ with $B_m$ in your proof.


Q:

Unexpected T_STRING error CURLOPT_CUSTOMREQUEST

I'm trying to POST data to an external URL using Curl, and am getting the error
Parse error: syntax error, unexpected T_STRING, expecting ')' in send.php on line 8

This is what send.php looks like:
<?php
    // Initialize curl
    $curl = curl_init();

    // Configure curl options
    $opts = array(
        CURLOPT_URL             => 'https://zapier.com/hooks/catch/n/abcd/'
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_CUSTOMREQUEST   => 'POST',
        CURLOPT_POST            => 1,
        CURLOPT_POSTFIELDS      => 'guid='+ echo $_POST["guid"]; + '&video_title=' + echo $_POST["video_title"]; + '&email=' + echo $_POST["email"];
    );

    // Set curl options
    curl_setopt_array($curl, $opts);

    // Get the results
    $result = curl_exec($curl);

    // Close resource
    curl_close($curl);

    echo $result;
?>

I'm still a noob in php, so any help much appreciated :)

A:

You need to learn how to READ and debug error messages. Everything you needed to solve the problem was in the error message.
Look at line 8 and then look at the end of the line before it.
You are missing a comma to separate items in an array after
CURLOPT_URL             => 'https://zapier.com/hooks/catch/n/abcd/'

Use
CURLOPT_URL             => 'https://zapier.com/hooks/catch/n/abcd/',


Q:

Build custom map like gothere.sg

I am looking for a reference on how custom map like gothere.sg is built. As far as I can figure out from understanding their architecture, they are using their own map server (their visual map looks so beautiful). On geocoding and much other functionalities, they're still reliant on Google Maps API.
Please post what you understand from seeing gothere.sg or provide similar reference for:

Building custom map like gothere.sg
Custom plotting of the map

A:

Looks like they are using a custom tileset to host there own map tiles and use the Google Maps API to do the panning/zooming stuff:
From there source (the code is obfuscated, but there are some easily recognizable bits):
var Ag=new google.maps.TileLayer(
                new google.maps.CopyrightCollection("gothere.sg"),
                10,22,{isPng:true,opacity:1});

This is one of the first things you have do do when you are setting up your own TileLayer.
I have answered a question previously which included a HowTo for implementing this sort of thing.  You can find it here:
Marking streets in Google Maps
They are also setting up there own GUI elements on top of the map to customize their look and feel.
Response to comment:
In the other answer I show a simple example of a custom tileset implementation.  You can find the doco for it here:
http://code.google.com/apis/maps/documentation/overlays.html#Tile_Layer_Overlays.
You can put anything you like in your custom tilesets, you certainly aren't limited to cities that Google has mapped.  Here are a few other examples of custom tilesets:

World of Warcraft tileset
Batmud tileset
Tower of the Hand tilset


Q:

git: Show message of last commit in commit template

git commit opens the text editor and displays some information about the changes to be committed:
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#

#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#

I would like to extend this template to display

the first line of the N last commit messages and/or
the complete message of the last commit

of the current branch. How can I do that?

A:

This will use git hooks.

In your project root directory navigate to .git/hooks/
Now create the file prepare-commit-msg
Add the following bit of code:

#!/bin/sh
ORIG_MSG_FILE="$1"  # Grab the current template
TEMP=`mktemp /tmp/git-msg-XXXXX` # Create a temp file
trap "rm -f $TEMP" exit # Remove temp file on exit

MSG=`git log -1 --pretty=%s` # Grab the first line of the last commit message

(printf "\n\n# Last Commit: %s \n\n" "$MSG"; cat "$ORIG_MSG_FILE") > "$TEMP"  # print all to temp file
cat "$TEMP" > "$ORIG_MSG_FILE" # Move temp file to commit message

chmod +x prepare-commit_message

Idea borrowed from Enhancing git commit messages
You can grab the whole commit message by using %b and %B, but could run into issues with multiline commits.  Might be able to get fancy with %-b and %-B, or just read more in the Documentation (scroll to format)


Q:

Github and Fogbugz

So we have integrated fogbugz and github, the actual mechanism seems to work.  (i.e. when pushing the "test" button on github, the message "payload delivered" is shown)  Unfortunately, cannot find the documentation on what to put in the commit message to tie the bug to the commit.
I have tried
git commit -am 'fixing 97047'
git push origin

and
git commit -am 'fixing #97047'
git push origin

Neither seems to work.  Would love to know what I'm missing - links to documentation would be most appreciated!

A:

The case number should be of the form:
\b((FogBug[sz]|Case|Bug[zs]*(?:ID)*):(\d+)

so
   FogBugz:1234
   FogBugs:1234
   Case:1234
   Bugz:1234

should all work.
I use  FogBugzId:1234


Q:

How convert Timezone into specified format?

my java program want TimeZone like GMT(+0530) instead of getting IST
Actually my java code like...
      String date1=null;
      String formate="IST";
      SimpleDateFormat sourceFormat = new SimpleDateFormat("z");

       SimpleDateFormat gmtFormat = new SimpleDateFormat("Z");
       date1 = gmtFormat.format(sourceFormat.parse(formate));
       System.out.println(date1);//output +0530

Problem 1:but Actually i want this format GMT(+0530)
Problem 2:The above code working only passing IST giving +0530 and any zone like EAT,PST also giving  +0530 only,... but the time will changed PST = (GMT - 8:00)
Please give suggestions...

A:

To Print format like GMT(+0530)  use pattern 'GMT('Z')' instead of Z.
SimpleDateFormat gmtFormat = new SimpleDateFormat("'GMT('Z')'");


Q:

MSBuild inline Task does not work (not caused by program logic)

I have created an inline Task which will return the latest two version-strings of a list of version-strings.
Task:
<UsingTask TaskName="GetLatestVersions" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
    <ParameterGroup>
        <AllVersions ParameterType="System.String" Required="true" />
        <CurrentVersion ParameterType="System.String" Output="true" />
        <LastVersion ParameterType="System.String" Output="true" />
    </ParameterGroup>
    <Task>
        <Using Namespace="System" />
        <Code Type="Fragment" Language="cs">
            <![CDATA[
        var currentVersion = "0.0.0.0";
        var lastVersion = "0.0.0.0";

        var compareWithCurrent = new Func<string, string, bool>((toCompare, with) =>
        {
            var convertToIntArray = new Func<string, int[]>(version =>
            {
                int mayor, minor, build, revision;
                var parts = version.Split('.');

                if (int.TryParse(parts[0], out mayor) &&
                    int.TryParse(parts[1], out minor) &&
                    int.TryParse(parts[2], out build) &&
                    int.TryParse(parts[3], out revision))
                {
                    return new[] {mayor, minor, build, revision};
                }
                return new[] {0, 0, 0, 0};

            });
            var current = convertToIntArray(with);
            var toCompareArr = convertToIntArray(toCompare);

            return toCompareArr[0] > current[0] ||
                    toCompareArr[0] == current[0] && toCompareArr[1] > current[1] ||
                    toCompareArr[0] == current[0] && toCompareArr[1] == current[1] && toCompareArr[2] > current[2] ||
                    toCompareArr[0] == current[0] && toCompareArr[1] == current[1] && toCompareArr[2] == current[2] && toCompareArr[3] > current[3];

        });

        foreach (var version in AllVersions.Replace("\\", "").Split(';'))
        {
            if (compareWithCurrent(version, currentVersion))
            {
                lastVersion = currentVersion;
                currentVersion = version;
            }
        }

        CurrentVersion = currentVersion;
        LastVersion = lastVersion;
    ]]>
        </Code>
    </Task>
</UsingTask>

Call:
    <GetLatestVersions AllVersions="@Versions">
        <Output PropertyName="CurrentVersionProperty" TaskParameter="CurrentVersion" />
        <Output PropertyName="LastVersionProperty" TaskParameter="LastVersion" />
    </GetLatestVersions>

@Versions contains a string like this (dumped via Message):
\3.7.1.3846;\3.7.2.3884;\3.7.3.3962;\3.7.4.4112;\3.8.0.4274;\3.9.0.4362;\3.9.0.4386
The variables CurrentVersionProperty and LastVersionProperty are both 0.0.0.0
What I tried
Normally you would say "The code inside the Task must be false" - thats what I expected.
I have created and debugged the following source code (Console Program) and the Codelogics seem to work well.
class Program
{
    static void Main(string[] args)
    {
        var versions =
             @" \1.8.19.0;\1.9.23.0;\2.1.3.0;\2.10.0.2304;\2.10.0.2326;\2.10.0.2367;\2.11.0.2422;\2.12.0.2543;\2.14.0.2716;\2.15.0.2779;\2.16.0.2881;\2.16.0.2888;\2.17.0.2977;\2.18.0.3093;\2.2.19.0;\2.2.27.0;\2.2.29.0;\2.3.7.0;\2.3.8.568;\2.4.0.941;\2.5.0.1448;\2.6.0.1642;\2.8.0.2008;\2.8.0.2045;\2.9.0.2176;\2.9.0.2222;\3.0.0.3174;\3.0.0.3174-Prof;\3.0.0.3229;\3.1.0.3255;\3.10.0.4470;\3.10.0.4480;\3.10.1.4538;\3.11.0.4656;\3.12.0.4769;\3.12.1.4872;\3.13.0.4985;\3.13.0.5009;\3.13.0.5019;\3.13.1.5094;\3.13.1.5171;\3.14.0.5217;\3.2.0.3342;\3.2.0.3370;\3.3.0.3408;\3.4.0.3546;\3.5.0.3602;\3.6.0.3664;\3.7.0.3794;\3.7.1.3846;\3.7.2.3884;\3.7.3.3962;\3.7.4.4112;\3.8.0.4274;\3.9.0.4362;\3.9.0.4386";

        string current, last;
        GetLatestVersions(out current, out last, versions);

    }

    public static void GetLatestVersions(out string CurrentVersion, out string LastVersion, string AllVersions)
    {
        //EXACTLY the same code as in Task - omitted to save space
    }
}

I have also tried changing Variablenames.
My Guesses:
The problem has to be somwhere inside MSBuild. Maybe there's a Problem with the Outparameters or what ever. I'd appreciate any help! Thank you.

A:

Seems like a simple typo:
<GetLatestVersions AllVersions="@Versions">

should of course be a proper ItemGroup expansion so
<GetLatestVersions AllVersions="@(Versions)">

Instead of reinventing the wheel I'd also suggest you use the Version class since that already provides parsing/less than/greater than/... so your compareWithCurrent can be rewritten as
var compareWithCurrent = new Func<string, string, bool>( ( toCompare, with ) =>
{
  return new Version( toCompare ) > new Version( with );
} );

Btw if I input 1.5.0.0;1.2.0.0;1.3.0.0 into your code it tells me currentVersion is 1.5.0.0 and lastVersion is 0.0.0.0. Not exactly what I'd expect - then again, I'm not sure what the code is supposed to do exactly.


Q:

A efficient way to store formula to calculate financial reports?

We are developing a system that will do financial statements and other financial-related things.  We are developing the app in Java/Java EE, specifically in JBoss Seam (Richfaces, a4j) + Javascript and other technologies.
Now we have a lot or formulas to calculate the financial statement accounts.  We need to build something that can be used to store formulas and use them in a simple way, or in a data structure so the formulas don't kill the app with fixed numbers/references in all the code.  (Maintainability concern.)
Now we have the formulas in a MS Excel sheet. There we have the common formulas from Excel (=A30+B40).  Each row in excel is an account which we will store ultimately in a SQL server db table (account), but the main point here is how to storage/manage the formulas for a better use than hardcoded somewhere.
I know financial system do it, but I couldn't find to much information about it.

A:

If your primary concern is maintainability of formulas, I can think of two different approaches that might help.

Keep the formulas in Excel and use something like Apache POI to write values to the spreadsheet, then read back the evaluated formulas.  (See http://poi.apache.org/spreadsheet/eval.html.)  Not sure how well that scales or performs, but the distinct advantage is that if your client is constantly tweaking formulas in the Excel sheet, the changes take effect right away rather than constantly playing catch-up.
Translate the formulas into Java POJOs, but keep them all consolidated in a single class or package of pure business logic with no Java EE, Seam or JSF dependencies.  Even though you'll have to re-translate to Java every time the Excel version changes, at least it's all in one place with a clear mapping between the original Excel source.  You could also use a scripting language to let you change the formulas without a restart/redeploy cycle.


Q:

'NSInternalInconsistencyException' - unable to push uitableviewcontroller on uinavigationcontroller ios 6

I am simply pushing a UITableviewController to navigation stack. Code works fine in both iOS 4.3 and 5 but crashes in iOS 6. Exception is:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "MenuController" nib but the view outlet was not set.'
I know this exception is raised when view outlet is not set. Outlet is set automatically by IB as you can see in figure, but still the same. What am I doing wrong?
Simple code pushing the controller:
MenuController *menu = [[MenuController alloc] initWithStyle:UITableViewStylePlain];
    menu.title = @"Watches";
    menu.MenuToBeDisplayed = @"main menu";
    [self.navigationController pushViewController:menu animated:YES];

Stack trace is:
 0   CoreFoundation                      0x01f3e02e __exceptionPreprocess + 206
    1   libobjc.A.dylib                     0x01a12e7e objc_exception_throw + 44
    2   CoreFoundation                      0x01f3ddeb +[NSException raise:format:] + 139
    3   UIKit                               0x00a3af18 -[UIViewController _loadViewFromNibNamed:bundle:] + 505
    4   UIKit                               0x00a3b418 -[UIViewController loadView] + 302
    5   UIKit                               0x00b8934e -[UITableViewController loadView] + 80
    6   UIKit                               0x00a3b648 -[UIViewController loadViewIfRequired] + 73
    7   UIKit                               0x00a3b882 -[UIViewController view] + 33
    8   UIKit                               0x00a3bb2a -[UIViewController contentScrollView] + 36
    9   UIKit                               0x00a52ef5 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 36
    10  UIKit                               0x00a52fdb -[UINavigationController _layoutViewController:] + 43
    11  UIKit                               0x00a53286 -[UINavigationController _updateScrollViewFromViewController:toViewController:] + 254
    12  UIKit                               0x00a53381 -[UINavigationController _startTransition:fromViewController:toViewController:] + 72
    13  UIKit                               0x00a53eab -[UINavigationController _startDeferredTransitionIfNeeded:] + 386
    14  UIKit                               0x00a544a3 -[UINavigationController pushViewController:transition:forceImmediate:] + 1030
    15  UIKit                               0x00a54098 -[UINavigationController pushViewController:animated:] + 62
    16  Tick                                0x000e5f02 -[MarketWatchViewController openMenu] + 274
    17  libobjc.A.dylib                     0x01a26705 -[NSObject performSelector:withObject:withObject:] + 77
    18  UIKit                               0x0095d920 -[UIApplication sendAction:to:from:forEvent:] + 96
    19  UIKit                               0x00b99b24 -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 139
    20  libobjc.A.dylib                     0x01a26705 -[NSObject performSelector:withObject:withObject:] + 77
    21  UIKit                               0x0095d920 -[UIApplication sendAction:to:from:forEvent:] + 96
    22  UIKit                               0x0095d8b8 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61
    23  UIKit                               0x00a1e671 -[UIControl sendAction:to:forEvent:] + 66
    24  UIKit                               0x00a1ebcf -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 578
    25  UIKit                               0x00a1dd38 -[UIControl touchesEnded:withEvent:] + 546
    26  UIKit                               0x0098d33f -[UIWindow _sendTouchesForEvent:] + 846
    27  UIKit                               0x0098d552 -[UIWindow sendEvent:] + 273
    28  UIKit                               0x0096b3aa -[UIApplication sendEvent:] + 436
    29  UIKit                               0x0095ccf8 _UIApplicationHandleEvent + 9874
    30  GraphicsServices                    0x0291adf9 _PurpleEventCallback + 339
    31  GraphicsServices                    0x0291aad0 PurpleEventCallback + 46
    32  CoreFoundation                      0x01eb3bf5 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 53
    33  CoreFoundation                      0x01eb3962 __CFRunLoopDoSource1 + 146
    34  CoreFoundation                      0x01ee4bb6 __CFRunLoopRun + 2118
    35  CoreFoundation                      0x01ee3f44 CFRunLoopRunSpecific + 276
    36  CoreFoundation                      0x01ee3e1b CFRunLoopRunInMode + 123
    37  GraphicsServices                    0x029197e3 GSEventRunModal + 88
    38  GraphicsServices                    0x02919668 GSEventRun + 104
    39  UIKit                               0x0095a65c UIApplicationMain + 1211
    40  Tick                                0x00002dc5 main + 197
    41  Tick                                0x00002cb5 start + 53

EDIT:
I have removed nib file, and also initWithNibName: method, but I am still getting this stupid exception since yesterday. This will drive me crazy :(

A:

With
MenuController *menu = [[MenuController alloc] initWithStyle:UITableViewStylePlain];
You aren't using your xib file at all becouse for initing contreoller with xib you need to use
initWithNibName:bundle: instead of initWithStyle:
and then set your controller's class on xib like this


Q:

Combine index-based and logical addressing in Matlab

Consider a matrix X. I have to update a submatrix of X, X(row1:row2, col1:col2), with a matrix Z (of size row2-row1+1, col2-col1+1) but only on those positions where a logical matrix L (of size row2-row1+1, col2-col1+1) is true.
E.g. if
 X=[ 1  2  3  4  5  6
    11 12 13 14 15 16
    21 22 23 24 25 26
    31 32 33 34 34 36]
 Z=[31 41
    32 42]
 L=[ 1 0
     0 1]
 row1 = 2; row2 = 3; col1 = 3; col2 = 4

then after the update I should get:
 X=[ 1  2  3  4  5  6
    11 12 31 14 15 16
    21 22 23 42 25 26
    31 32 33 34 34 36]

Currently I do the following:
Y = X(row1:row2, col1:col2);
Y(L) = Z(L);
X(row1:row2, col1:col2) = Y;

This code is in a tight loop and according to Matlab's (v2019a) profiler is the main bottleneck of my program. In the real code X is a 2000x1500x3 cube; row1, row2, col1, col2, Z and L change in the loop.
The question is whether it can be rewritten into a single / faster assignment.
Thanks.

A:

Honestly, without seeing your actual code, I get the sense that your solution may be as fast as you can get. The reason I say that is because I tested a few different solutions by creating some random sample data closer to your actual problem. I assumed X is an image of type uint8 with size 2000-by-1500-by-3, Z is size N-by-N (i.e. we will only be modifying the first page of X), L is an N-by-N logical array, and the row and column indices are randomly chosen:
X = randi([0 255], 2000, 1500, 3, 'uint8');
N = 20;  % Submatrix size
Z = randi([0 255], N, N, 'uint8');
L = (rand(N, N) > 0.5);
row1 = randi([1 2000-N]);
row2 = row1+N-1
col1 = randi([1 1500-N]);
col2 = col1+N-1;

I then tested 3 different solutions: your original solution, a solution using find and sub2ind to create a linear index for X, and a solution that creates a logical index for X:
% Original solution:
Y = X(row1:row2, col1:col2, 1);
Y(L) = Z(L);
X(row1:row2, col1:col2, 1) = Y;

% Linear index solution:
[rIndex, cIndex] = find(L);
X(sub2ind(size(X), rIndex+row1-1, cIndex+col1-1)) = Z(L);

% Logical index solution
[R, C, ~] = size(X);
fullL = false(R, C);
fullL(row1:row2, col1:col2) = L;
X(fullL) = Z(L);

I tested these repeatedly with randomly-generated sample data using timeit and found that your original solution is consistently the fastest. The linear index solution is very close, but slightly slower. The logical index solution takes more than twice as long.


Q:

Replace a clustered index with a non-clustered one on primary key using SQL Server Management Studio UI without generating a script

When you designate a column as the primary key in SQL Server Management Studio, it automatically creates a clustered index on the column. How do you replace the index with a non-clustered one using the SQL Server Management Studio user interface, but without generating or writing a script to drop the index and create the non-clustered one?
I know how to do it with a script (ALTER TABLE and then DROP CONSTRAINT), whether hand-written or generated using Management Studio. I am asking how to do it using only the Management Studio user interface. Because I remember I did it in the past. Only, I've forgotten how to do it because it has been a few months now.
I am using SQL Server Management Studio v17.9.1.

A:

Alright, with some more poking around, I found out what I had done earlier. This is the way.

Right-click on the primary key column when it is open in the designer and select the menu command Indexes/Keys.
Set Create as Clustered to the value No in the ensuing dialog.

See the pictures below.


Q:

Magento 2 grid structure

I have started looking into Magento 2 grid. I have developed one simple module but I didn't understand the structure of grid.
In Magento 1.9.X, the way was clear for adding grid but in Magento 2 there is structure is different. How do I add a grid in Magento 2?

A:

In Magento 2, you can create a grid by XML (see here)
However, you can create a grid by PHP like Magento 1: Extending your grid class to "Magento\Backend\Block\Widget\Grid\Extended"
<?php

namespace Yourpackage\Yourmodule\Block\Adminhtml\Sample;

class Grid extends \Magento\Backend\Block\Widget\Grid\Extended
{
    protected $_yourmodelFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Backend\Helper\Data $backendHelper,
        \Yourpackage\Yourmodule\Model\YourmodelFactory $yourmodelFactory,
        array $data = []
    ) {
        parent::__construct($context, $backendHelper, $data);
        $this->_yourmodelFactory = $yourmodelFactory;
    }

    protected function _construct()
    {
        parent::_construct();
        $this->setId('sample_grid');
        $this->setDefaultSort('id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
    }

    protected function _prepareCollection()
    {
        $collection = $this->_yourmodelFactory->create()->getCollection();
        $this->setCollection($collection);

        return parent::_prepareCollection();
    }

    protected function _prepareColumns()
    {
        $this->addColumn(
            'id',
            [
                'header' => __('ID'),
                'align'  => 'right',
                'width'  => '50px',
                'index'  => 'id',
            ]
        );

        // Some columns

        return parent::_prepareColumns();
    }
}

You can see more at: /vendor/magento/module-cms/Block/Adminhtml/Page/Grid.php.


Q:

Nest-API Thermostat device not showing in REST request

I'm using Chrome's Postman extension to determine why the NestDK iOS app isn't showing the thermostat after we sign in and decided to try a REST request to see what was returned.  I input https://developer-api.nest.com?auth= into the Postman interface and do a GET.
I get back the response below, with a thermostat defined in the structures data element, but there is no devices data element.  I know the device is connected because when I change from home to away, the 'away' setting is modified. Why are there no devices?
{
    "structures": {
        "<structure_id>": {
            "name": "Home",
            "country_code": "US",
            "time_zone": "America/New_York",
            "away": "away",
            "thermostats": [
                "<thermometer_id>"
            ],
            "structure_id": "<structure_id>"
        }
    },
    "metadata": {
        "access_token": "<accessToken>",
        "client_version": 1
    }
}

A:

Check your client permissions. Make sure that you have either Thermostat read or Thermostat read/write selected.
Available Permissions


Q:

Xamarin - SignaturePad BackgroundImageView trouble

Having trouble getting this to work - I must be missing something:
signaturePad2.BackgroundImageView = new ImageView(Context)
{
   Id = GenerateId(this),
   LayoutParameters = new RelativeLayout.LayoutParams (RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent)
};

signaturePad2.AddView(BackgroundImageView);
signaturePad2.BackgroundImage = MyGlobals.FileNameOfPhotoTaken;

A:

BackgroundImage is of type ImageSource
padView.BackgroundImage = ImageSource.FromUri(new Uri(
    "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/Xamarin-logo.svg/220px-Xamarin-logo.svg.png"));


Q:

Parse JSON with Apex

I am trying to deserialize below JSON . Problem is that sometimes message is returned as an object and sometimes as an array .
In this JSON , I have combined three HTTP responses into one so as to get a complete set. It is a valid json per JSONLint.
{
  "LineStatus": [
    {
      "line": "1.00",
      "ConfigStatus": "E",
      "ConfiguratorMessages": {
        "message": {
          "MessageType": "E",
          "message": "PRODUCT REQUIRED."
        }
      }
    },
    {
      "line": "2.00",
      "ConfigStatus": ""
    },
    {
      "line": "3.00",
      "ConfigStatus": "W",
      "ConfiguratorMessages": {
        "message": [
          {
            "message": "COUPON EXPIRED",
            "MessageType": "W"
          }
        ]
      }
    },
    {
      "line": "4.00",
      "ConfigStatus": "W",
      "ConfiguratorMessages": {
        "message": [
          {
            "message": "COUPON EXPIRED",
            "MessageType": "W"
          }
        ]
      }
    },
    {
      "line": "5.00",
      "ConfigStatus": "W",
      "ConfiguratorMessages": {
        "message": [
          {
            "message": "COUPON EXPIRED",
            "MessageType": "W"
          },
          {
            "message": "COUPON RESTRICTED FOR ANOTHER PRODUCT",
            "MessageType": "W"
          }
        ]
      }
    }
  ]
}

Below is the apex to deserialize the above JSON but I don't know how to check when the data type of message changes from {} to [].
public class ConfigMessages {

    public List<LineStatus> LineStatus;

    public class LineStatus {
        public String line;
        public String ConfigStatus;
        public ConfiguratorMessages ConfiguratorMessages;
    }

    public class ConfiguratorMessages {
        public Message message;
    }

    public class Message {
        public String MessageType;
        public String message;
    }

    public static ConfigMessages parse(String json) {
        return (ConfigMessages) System.JSON.deserialize(json, ConfigMessages.class);
    }
}

//I have further tried to go the deserialize/serialize/deserialize again route as below but I have no clue how to take this further.
Map<String, Object> responseMap = (Map<String, Object>) JSON.deserializeUntyped(JsonString);
List<Object> lineStatusObjectList = (List<Object>) responseMap.get('LineStatus');
List<Map<String, Object>> lineStatusResponseMapList = new List<Map<String, Object>>();

for (Object obj : lineStatusObjectList) {
    lineStatusResponseMapList.add((Map<String, Object>)obj);
}//for

String serializedLineStatusJson = JSON.serializePretty(lineStatusResponseMapList);
 for( Map<String, Object> mapObj : lineStatusResponseMapList ){
     for (String attributeName : mapObj.keyset()) {
         Map<String, Object> configuratorMessagesResponseMap =(Map<String, Object>) mapObj.get('ConfiguratorMessages');
         System.debug('** configuratorMessagesResponseMap ' + configuratorMessagesResponseMap);
      }
}

A:

Pretty ugly, but less work than blank's approach:
Object o = JSON.deserializeUntyped(JsonString);
try {
    // See if an object
    Map<String, Object> m = (Map<String, Object>) o;
    ...
} catch(TypeException e) {
    // Not an object, must be an array
    List<Object> a = (List<Object>) o;
    ...
}


Q:

How to get actual CSS value with jQuery?

I am adjusting the height of a couple of DIVs with contenteditable = true to fix box model issues when in IE Quirksmode.
The style of the DIVs are:
height: 14px;
padding: 6px;
border: 1px solid black;
overflow: hidden;

So far I've been fetching the CSS height value using $("selector").css("height") and used that value for further calculations, but recently updated my jQuery library to the newest version and this method is now broken.
To elaborate; in jQuery 1.4.2 .css("height") would return '14px' whereas jQuery 1.6.2 returns '0px' if the element and all of its ancestors are visible and otherwise '14px'.
I'm guessing the former is calculated using IE Quirksmode box model (14px height - 2x 6px padding - 2x 1px border = 0px) and the latter is grabbed directly from the stylesheet. I would like to get the former regardless of visibility - is there any "pretty" way to get the actual CSS value ("pretty" meaning not looking it up in the document.styleSheets array)?
Edit:
First off, I forgot an important style property on the DIVs: overflow: hidden (now corrected).
Also I think it is worth to emphasize, this problem only occurs in Internet Explorer while in Quirks Mode. As far as I am aware it is not a problem in any other (current) browser/mode (I haven't tested all, so not 100% sure).
To further elaborate on the problem (and answer some suggestions on possible solutions) I ran a little test on the fields and the values returned by different functions in jQuery:
jQuery 1.4.2:
Element visible: true
.css('height'): 14px
.height(): 0
.outerHeight(): 14

Element visible: false
.css('height'): 14px
.height(): 0
.outerHeight(): 0

jQuery 1.6.2:
Element visible: true
.css('height'): 0
.height(): 0
.outerHeight(): 14

Element visible: false
.css('height'): 14px
.height(): 14
.outerHeight(): 28

.outerHeight(true) is of no use to me, as the margin has no effect regardless of box model. Element visibility was tested using $("selector").is(":visible").
Right, so how to use those numbers? To fix the box model height I have to do the following calculation:
newHeight = oldHeight + borderWidth (top & bottom) + padding (top & bottom)

In other words, I need the 14px value. One could argue that the solution to the problem is to grab the value of .outerHeight() when the element is visible while grabbing the value of .css('height') when it is not (which is what I am currently planning on doing), but that does not actually answer the original question; how do I get the actual CSS value?
For the sake of completeness, here is an example HTML/script that will replicate my numbers from the test (I did not do the actual test on this, but the end result is the same - also remember to set IE to Quirksmode before testing):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

test

test

A:

Does :
$("selector").height();

or
$("selector").outerHeight();

fix your problem ?


Q:

Как сделать сортировку свойств в классе?

Есть класс DB. Через intellisense отображение свойств идет по алфавиту, но хочется сделать чтобы я сам мог задавать ее.
class DB
{
    public string Url { get; set; } //2
    public string Category { get; set; } //1
}

A:

Сортировка и фильтрация Intellisense списка в Visual Studio не предусматривает установку своего порядка отображения списка стандартными средствами. (На каком-то форуме натыкался на статью, где обсуждался данный функционал. Даже был запрос, на добавление такого функционала, но он не появился).
Для примера, для Visual Studio есть хороший инструментарий, плагин ReSharper, который вносит полезные дополнения кода и помогает повысить продуктивность работы в Visual Studio. Но и в нем нет такой возможности.
Если у Вас имеются необходимые знания и опыт написания плагинов, то Вы можете написать плагин, подобный ReSharper, который можно будет встроить в Visual Studio для индивидуального отображения Intellisense списка.


Q:

HTML/CSS question: Part of div being floated to next line, I want it on the same line

I am loading names/grades from a database which happens perfectly... however, the grade assosciated with the person is for some reason getting floated down to the next line and I can't figure out why, as you can see in this picture: http://i.stack.imgur.com/rqhjp.png
I want that number grade to be on the same line, aligned on the right, but I cant figure out why it's getting pushed down to the next line. Here is my php:
echo '
' . $firstname . " "  . $lastname . "" . '
' . $avg . '

';

And the CSS it refers to:
}
#content .name{
    background: #FFF;
    float:left;
    width: 220px;
    padding: 0px;
    position: relative;
    margin: 0px;
    font-size: 1.4em;
    border: 2px solid #CCC;
    border-radius: 10px;
}

A:

Instead of using p and align, put the grade in a span and float it to the right. You can see it working in this fiddle.


Q:

Renaming a bunch of files using Command-line

Suppose I have a folder with thousands of photos named all randomly. How can one rename them as photo1, photo2,...,photo1000 from the command-line/terminal?

A:

I will assume that you want to keep a proper suffix on the filenames:
c=1; for f in *.jpg ; do mv "$f" "photo$c.jpg" ; c=$(($c+1)) ; done

Notes

c=1:  This initalizes the counter.  You can set it to any number you like.
for f in *.jpg ; do:  This signifies the beginning of a shell for-loop.  While much of shell-scripting can be difficult to make work when file names can contain spaces, newlines or other difficult characters, this construction is safe against even the most hostile file names.
mv "$f" "photo$c.jpg":  This uses the counter c and does the actual renaming of files.  The file name $f is in double-quotes to protect the name from the various possible shell expansions.
c=$(($c+1)): This increments the counter for the next loop
done:  The signifies the end of the for loop.

A:

You can use this code :
for i in *.jpg; do let j+=1 ; mv "$i" "photo$j.jpg" ; done


Q:

What environment variables control dyld?

There are a bunch of environment variables that control dyld launch, several of them very useful for debugging performance problems. Not all of them are documented.

A:

These ones are explained in the dyld man page (at least on macOS 10.13)
DYLD_FRAMEWORK_PATH
DYLD_FALLBACK_FRAMEWORK_PATH
DYLD_VERSIONED_FRAMEWORK_PATH
DYLD_LIBRARY_PATH
DYLD_FALLBACK_LIBRARY_PATH
DYLD_VERSIONED_LIBRARY_PATH
DYLD_PRINT_TO_FILE
DYLD_SHARED_REGION
DYLD_INSERT_LIBRARIES
DYLD_FORCE_FLAT_NAMESPACE
DYLD_IMAGE_SUFFIX
DYLD_PRINT_OPTS
DYLD_PRINT_ENV
DYLD_PRINT_LIBRARIES
DYLD_BIND_AT_LAUNCH
DYLD_DISABLE_DOFS
DYLD_PRINT_APIS
DYLD_PRINT_BINDINGS
DYLD_PRINT_INITIALIZERS
DYLD_PRINT_REBASINGS
DYLD_PRINT_SEGMENTS
DYLD_PRINT_STATISTICS
DYLD_PRINT_DOFS
DYLD_PRINT_RPATHS
DYLD_SHARED_CACHE_DIR
DYLD_SHARED_CACHE_DONT_VALIDATE

This one is documented in man dyld, but isn't listed in the list at the top:
DYLD_PRINT_STATISTICS_DETAILS

These are undocumented:
DYLD_ROOT_PATH
DYLD_PATHS_ROOT
DYLD_DISABLE_PREFETCH
DYLD_PRINT_LIBRARIES_POST_LAUNCH
DYLD_NEW_LOCAL_SHARED_REGIONS
DYLD_NO_FIX_PREBINDING
DYLD_PREBIND_DEBUG
DYLD_PRINT_TO_STDERR
DYLD_PRINT_WEAK_BINDINGS
DYLD_PRINT_WARNINGS
DYLD_PRINT_CS_NOTIFICATIONS
DYLD_PRINT_INTERPOSING
DYLD_PRINT_CODE_SIGNATURES
DYLD_USE_CLOSURES
DYLD_IGNORE_PREBINDING
DYLD_SKIP_MAIN

DYLD_ROOT_PATH and DYLD_PATHS_ROOT appear to be synonyms and allow you to reset the "root" for searching for libraries/frameworks/etc. This is available on macOS/iPhoneSimulator but not iOS.
DYLD_DISABLE_PREFETCH disables the pre-fetching of the content of __DATA and __LINKEDIT segments.
DYLD_PRINT_LIBRARIES_POST_LAUNCH is the same as DYLD_PRINT_LIBRARIES but prints them right after launch has finished.
DYLD_NEW_LOCAL_SHARED_REGIONS and DYLD_NO_FIX_PREBINDING are ignored and don't do anything anymore.
DYLD_PREBIND_DEBUG prints out debug information on why prebinding was not used.
DYLD_PRINT_TO_STDERR only applies to iOS and forces output to stderr (instead of stdout) to help it show up on console logs.
DYLD_PRINT_WEAK_BINDINGS prints debug information on weak bindings.
DYLD_PRINT_WARNINGS prints a bunch of warnings (mostly regards to closures and how they are being used).
DYLD_PRINT_CS_NOTIFICATIONS prints information about the core symbolicator.
DYLD_PRINT_INTERPOSING prints details about interposes that occur.
DYLD_PRINT_CODE_SIGNATURES prints details about code signatures (specifically successes and failures).
DYLD_USE_CLOSURES is a dyld3 feature, but doesn't appear to work for anybody non-internal (need CSR_ALLOW_APPLE_INTERNAL set).
DYLD_IGNORE_PREBINDING has three values ("all", "app", "nonsplit") with nonsplit being the default if a value is not supplied.
DYLD_SKIP_MAIN is an apple only feature used for testing dyld (need CSR_ALLOW_APPLE_INTERNAL set).


Q:

How printf work in c when one of the argument is a function call

Can anybody tell me how this program execute internally
#include<stdio.h>

typedef int (* afp)(int a, int b);

int abc(int x, int y)
{
    return x+y;
}

int main()
{
    afp ab;
    ab = &abc;
    printf("\n%d - %d - %d", ab(20, 13));
    return 0;
}

and the output obtained is

33 - 20 - 4195712

as you can see first %d is replaced with expected result 20+13 but the next %d is always replaced by the first argument to the function and the last %d is replaced by a garbage..
--EDIT
I have added three %d 's but passing only one arguments to printf, but how the second %d is always get replaced by the first argument to the function ??

A:

You are causing undefined behavior. You specify three parameters "\n%d - %d - %d", yet you only pass one ab(20, 13).
The first output is what that function call ab(20, 13) returns, the rest is not meaningful.
Since you pass one parameter you should call it like this:
printf("\n%d", ab(20, 13));

A:

As other answers have already said, this is undefined behaviour, so the C standard allows a conforming C implementation to do anything.
But if you are asking what really happens in this case: When printf sees the three %d's, it will look for three arguments, in the places where they would have been, if they existed. The first one is the return value from the function call. The second one seems to be one of the arguments to that function call, that happened to be left in the place where printf looks for its second argument. And the third is some garbage. You will need to look at the details of your particular environment, and how your compiler lays out variables in memory, to know more.


Q:

How can l import an input?

I created a file
#name file ask.py
def ask_name():
    user = input("What is your name?: ")

and i imported it
import ask
ask.ask_name()
print(user)

but python tells me that "user" is not defined.

A:

It's not: user is a variable internal to ask_name, not an attribute of ask.  Try this:
#name file ask.py
def ask_name():
    user = input("What is your name?: ")
    return user

# Main file
import ask
local_input = ask.ask_name()
print(local_input)


Q:

Kant and Theodicy

I am looking for some general overview on Immanuel Kant's theodicy.
I need resources, such as an SEP page, on the topic of Kant's theodicy.

Did Kant discuss theodicy at all?
What possible explanations did Kant supply for good things happening to bad people and bad things happening to good people?

Prior Research:--

(https://www.degruyter.com/view/j/agph.2018.100.issue-1/agph-2018-0003/agph-2018-0003.xml)
(https://www.tandfonline.com/doi/abs/10.1080/09608788.2012.718860)
(https://www.iep.utm.edu/kant-rel/)

A:

Wayne P. Pomerleau writes in the Internet Encyclopedia of Philosophy article already referenced in the question:

Kant deals with the problem of evil more impressively in his “On the Miscarriage of All Philosophical Trials in Theodicy” (1791).  He analyzes possible attempts at theodicy into three approaches:  (a) it can argue that what we consider evil actually is not, so that there is really no conflict; (b) it can argue that the conflict between evil and God is naturally necessitated; and (c) it can argue that evil, though contingent, is the result of someone other than God.  Kant’s own earlier work attempted to combine the second and third strategies; but here he concludes that all of these approaches must fail.  More specifically, attempts to show that there is no pernicious conflict between moral evil and God’s holiness,   between the physical evils of pain and suffering and God’s goodness,  and, finally, between the disproportion of happiness and misery to virtue and vice and God’s justice, all fail using all three approaches.  Thus Kant’s considered conclusion is negative:  the doubts that are legitimately raised by the evil in our world can neither be conclusively answered nor conclusively refute God’s infinite moral wisdom.

This would answer the first question:

Did Kant discuss theodicy at all?

He did discuss theodicy in “On the Miscarriage of All Philosophical Trials in Theodicy” (1791).
One might be able to answer the second question as well:

What possible explanations did Kant supply for good things happening to bad people and bad things happening to good people?

Based on the above quote he did not provide an explanation, however, he found "no pernicious conflict between moral evil and God’s holiness". He leaves this to faith.
Lawrence Pasternack and Philip Rossi give an explanation for Kant's reliance on faith:

So, while Kant does deny the possibility of religious knowledge (as well as opinion), he considers this denial necessary to safeguard faith, as the proper mode of religious assent. One must, therefore, understand the negative elements in his philosophy of religion, such as his infamous objections to the traditional proofs for God's existence, in this context.

One needs faith for "religious assent".

Pasternack, Lawrence and Rossi, Philip, "Kant's Philosophy of Religion", The Stanford Encyclopedia of Philosophy (Fall 2014 Edition), Edward N. Zalta (ed.), URL = https://plato.stanford.edu/archives/fall2014/entries/kant-religion/.
Pomerleau, W. P. "Emmanuel Kant: Philosophy of Religion" Internet Encyclopedia of Philosophy https://www.iep.utm.edu/kant-rel/


Q:

matplotlib: empty area appears on the figure when plotting many subplots

I am plotting a few dozen of subplots with matplotlib. At the bottom of the figure, between the last row of plots and the legend, an empty area appears. The empty area grows larger when I add more subplots. Any idea how to get rid of this empty space?
Here's the working code:
import textwrap
import matplotlib.pyplot as plt
from collections import OrderedDict

rlen = 31 # number of plots
figsize = (11, 3) # matrix of subplots
fig = plt.figure(figsize=(figsize[1]*4, figsize[0]*4))

plots = []
for f_ind in range(rlen):
   plots.append(fig.add_subplot(figsize[0], figsize[1], f_ind))

fig.subplots_adjust(wspace=0.5, hspace=0.5)

for ax in plots:
   atitle = 'Aaa bbb ccc ' * 10
   ax.set_title('\n'.join(textwrap.wrap(atitle, 45)), fontsize=10)
   ax.plot(range(10), range(10), 'o', color='red', label='LABEL_1')
   revlist = list(reversed(range(10)))
   ax.plot(revlist, range(10), 'o', color='blue', label='LABEL_2')
   ax.set_xlabel('Train set size', fontsize=9)
   ax.set_ylabel('Accuracy (%)', fontsize=9)

handles, labels = plt.gca().get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
lgd = fig.legend(by_label.values(), by_label.keys(), loc='lower center', ncol=4)
fig.savefig('ZZZ.png', dpi=fig.dpi, bbox_extra_artists=(lgd,), bbox_inches='tight')

You can also view the example result here. Thanks!

A:

You can use the bottom keyword for subplots_adjust to set the point to which the subplots should be drawn with respect to the figure.
So for example:
fig.subplots_adjust(wspace=0.5, hspace=0.5, bottom=0)

The legend will then be close to the 'lowest' subplots. Here is a crop from the bottom of the resulting image:

Besides bottom, there are also left, right and top keywords.


Q:

Guidance, VBA - SELECT CASE clean up

This SELECT CASE scenario is working for me but I think the code can be more friendly ... any advice would be very helpful.
Select Case True 'select case where worker name and action is true then in each case RSworkhours.addnew

    Case Me.Worker1.Value <> "" And Me.fw1a1 = 1
        With RsWorkHours
            .AddNew
            !WorkerID = Me.Worker1
            !Date = Me.TxtDate
            !StandardTime = Me.w1a1s
            !Overtime = Me.w1a1o
            !Doubletime = Me.w1a1d
            !ScaffoldID = Me.cboScaffnum
            .Update
        End With
        Me.fw1a1 = 0
        GoTo WorkerHours
   Case Me.Worker1.Value <> "" And Me.fw1a2 = 1
        With RsWorkHours
            .AddNew
            !WorkerID = Me.Worker1
            !Date = Me.TxtDate
            !StandardTime = Me.w1a2s
            !Overtime = Me.w1a2o
            !Doubletime = Me.w1a2d
            !ScaffoldID = Me.cboScaffnum
            .Update
        End With
        Me.fw1a2 = 0
        GoTo WorkerHours

The Code iterates through this Select Case 80 times, if there are 16 workers and each have 5 actions.
I was thinking maybe having a loop that modifies the number within the arguments like:
for each x to 16
    for each y to 5
        If Me.worker & x & .Value <> "" And Me.fw & x & a & y Then
            With Recordset
                .AddNew
                'insert stuff
                .Update
            End With
        End If
    Next y
Next x

Does anyone have any insight?
Thank you in advance.
-Matt

A:

You can access all controls by their name from the Controls collection.
Just pass the name of a control and you will get to that control - the name is a string and can of course be dynamic.
Dim x As Long, y As Long
Dim WorkerX As Control, wXaYs As Control, wXaYo As Control, wXaYd As Control

For x = 1 To 16
    For y = 1 To 5
        Set WorkerX = Me.Controls("Worker" & x)
        Set wXaYs = Me.Controls("w" & x & "a" & y & "s")
        Set wXaYo = Me.Controls("w" & x & "a" & y & "o")
        Set wXaYd = Me.Controls("w" & x & "a" & y & "d")
        If WorkerX.Value > "" And wXaYs.Value > "" Then
            With Recordset
                .AddNew
                !WorkerID = WorkerX.Value
                !Date = Me.TxtDate
                !StandardTime = wXaYs.Value
                !Overtime = wXaYo.Value
                !Doubletime = wXaYd.Value
                !ScaffoldID = Me.cboScaffnum
                .Update
            End With
        End If
    Next y
Next x


Q:

Ionic row has width of 0px

I'm trying to use the example from this link (Most of the code is not very important but rather the minor change I added is all the difference):
http://codepen.io/psutherland/pen/seiwE

angular.module('ionic.example', ['ionic'])

    .controller('MapCtrl', function($scope, $ionicLoading, $compile) {
      function initialize() {
        var site = new google.maps.LatLng(55.9879314,-4.3042387);
        var hospital = new google.maps.LatLng(55.8934378,-4.2201905);

        var mapOptions = {
          streetViewControl:true,
          center: site,
          zoom: 18,
          mapTypeId: google.maps.MapTypeId.TERRAIN
        };
        var map = new google.maps.Map(document.getElementById("map"),
            mapOptions);

        //Marker + infowindow + angularjs compiled ng-click
        var contentString = "
Click me!
";
        var compiled = $compile(contentString)($scope);

        var infowindow = new google.maps.InfoWindow({
          content: compiled[0]
        });

        var marker = new google.maps.Marker({
          position: site,
          map: map,
          title: 'Strathblane (Job Location)'
        });

        var hospitalRoute = new google.maps.Marker({
          position: hospital,
          map: map,
          title: 'Hospital (Stobhill)'
        });

        var infowindow = new google.maps.InfoWindow({
             content:"Project Location"
        });

        infowindow.open(map,marker);

        var hospitalwindow = new google.maps.InfoWindow({
             content:"Nearest Hospital"
        });

        hospitalwindow.open(map,hospitalRoute);

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open(map,marker);
        });

        $scope.map = map;

        var directionsService = new google.maps.DirectionsService();
        var directionsDisplay = new google.maps.DirectionsRenderer();

        var request = {
            origin : site,
            destination : hospital,
            travelMode : google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });

        directionsDisplay.setMap(map);

      }

      google.maps.event.addDomListener(window, 'load', initialize);

      $scope.centerOnMe = function() {
        if(!$scope.map) {
          return;
        }

        $scope.loading = $ionicLoading.show({
          content: 'Getting current location...',
          showBackdrop: false
        });
        navigator.geolocation.getCurrentPosition(function(pos) {
          $scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
          $scope.loading.hide();
        }, function(error) {
          alert('Unable to get location: ' + error.message);
        });
      };

      $scope.clickTest = function() {
        alert('Example of infowindow with ng-click')
      };

    });
#map {
  width: 100%;
  height: 100%;
}

.scroll {
  height: 100%;
}

    <meta charset="utf-8">
    <title>Map</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

    <link href="//code.ionicframework.com/1.0.0-beta.12/css/ionic.css" rel="stylesheet">

    <ion-header-bar class="bar-dark" >

Google Maps Example

    </ion-header-bar>
    <ion-content>

    </ion-content>
    <ion-footer-bar class="bar-dark">
      Find Me
    </ion-footer-bar>

But when I add
 around the div with the "map" id as follows:

The map becomes invisible and I see that the width is 0. I can't understand why the "row" class would have this affect.

A:

The issue is not specifically about the class "row" (any other class would have the same effect). The cause seems to be, that the content of the div has position: absolute, and therefore the containing div does not stretch automatically with the content. To fix it, just add explicit width and height properties:
.row {
  width: 100%;
  height: 100%;
}

See http://codepen.io/ramtob/pen/jbwbjZ


Q:

Linked List manual Alphabetical sorting

I am working with linkedlists at the moment in java. Our assignment was to create one from scratch, that sorts user input(Strings) into alphabetical order. I have been trying a lot of things, but none of the concepts I come up with seem to work. Any Advice/tips would be appreciated.
package linkedlist;
public class Linked {

    Node head;
    int listCount;

    public Linked(){
        head = new Node(null);
        listCount = 0;
    }
    public void add(String data){
        Node linkedTemp = new Node(data);
        Node linkedCurrent = head;
        while (linkedCurrent.getNext() != null) {
                linkedCurrent = linkedCurrent.getNext();
                }
        linkedCurrent.setNext(linkedTemp);
        listCount++;

    }

    public void add2(String data){
        Node linkedTemp = new Node(data);
        Node linkedCurrent = new Node(get(1));

        if(listCount >= 1){

          while (linkedCurrent.getNext() != null){

              if(linkedCurrent.getData().compareTo(linkedTemp.getData()) <= 0){
                  linkedCurrent.setNext(linkedTemp);
                  listCount++;
                  break;
              }
              if(linkedCurrent.getData().compareTo(linkedTemp.getData()) >= 0)
                linkedCurrent = linkedCurrent.getNext();
        }
    }
    }

     public String toString() {
        Node linkedCurrent = head.getNext();
        String output = "";
        while (linkedCurrent != null) {
            output += "[" + linkedCurrent.getData().toString() + "]";
            linkedCurrent = linkedCurrent.getNext();
        }
        return output;
    }
     public String get(int index)
    {
        if (index <= 0)
            return null;

        Node linkedCurrent = head.getNext();
        for (int i = 1; i < index; i++) {
            if (linkedCurrent.getNext() == null)
                return null;

            linkedCurrent = linkedCurrent.getNext();
        }
        return linkedCurrent.getData();
    }
}

A:

Except that the sort does not work, I think your code is OK. For example,
public static void main(String[] args) {
    Linked linked = new Linked();
    linked.add("data3");
    linked.add("data2");
    linked.add("data1");
    System.out.println( linked );

    System.out.println( linked.get(1) );
    System.out.println( linked.get(2) );
    System.out.println( linked.get(3) );
    System.out.println( linked.get(4) );
}

Above test code gives the output that meets our expectation.
[data3][data2][data1]
data3
data2
data1
null

But as I told you, the thing is that the sorting part of the problem is not solved. To solve the problem, I think you should modify the 'add' part of the code. Your add method does not consider the order of the inserted items.
public void add(String data){
    Node linkedTemp = new Node(data);
    Node linkedCurrent = head;
    Node linkedPrev = head;
    while ( linkedCurrent != null ) {
        if ( linkedCurrent.getData() != null && linkedCurrent.getData().compareTo(data) > 0 ) {
            break;
        }
        linkedPrev = linkedCurrent;
        linkedCurrent = linkedCurrent.getNext();
    }
    linkedTemp.setNext( linkedPrev.getNext() );
    linkedPrev.setNext(linkedTemp);
    listCount++;
}

As your code using a 'null head' which contains a meaningless data, the added if block inside of the while statement checks if linkedCurrent.getData() is not null.
After the above modification to the add method, the output becomes:
[data1][data2][data3]
data1
data2
data3
null


Q:

Optimize the query of weekday statistics between two dates

I have a table with two fields: start_date and end_date. Now I want to count the total number of work overtime. I have created a new calendar table to maintain the working day status of the date.
table: workdays
id                  status
2020-01-01          4
2020-01-02          1
2020-01-03          1
2020-01-04          2

4: holiday, 1: weekday, 2: weekend
I created a function to calculate the weekdays between two dates (excluding weekends, holidays).
create or replace function get_workday_count (start_date in date, end_date in date)
return number is
    day_count int;
begin
    select count(0) into day_count from WORKDAYS
    where TRUNC(ID) >= TRUNC(start_date)
    and TRUNC(ID) <= TRUNC(end_date)
    and status in (1, 3, 5);
    return day_count;
end;

When I execute the following query statement, it takes about 5 minutes to display the results, erp_sj table has about 200000 rows of data.
select count(0) from ERP_SJ GET_WORKDAY_COUNT(start_date, end_date) > 5;

The fields used in query statements are indexed.
How to optimize? Or is there a better solution?

A:

First of all, optimizing your function:
1.adding pragma udf (for faster execution in sql
2. Adding deterministic clause(for caching)
3. Replacing count(0) to count(*) (to allow cbo optimize count)
4. Replacing return number to int
create or replace function get_workday_count (start_date in date, end_date in date)
return int deterministic is
    pragma udf;
   day_count int;
begin
    select count(*) into day_count from WORKDAYS w
    where w.ID >= TRUNC(start_date)
    and w.ID <= TRUNC(end_date)
    and status in (1, 3, 5);
    return day_count;
end;

Then you don't need to call your function in case of (end_date - start_date) < required number of days. Moreover, ideally it would be to use scalar subquery instead of function:
select count(*)
from ERP_SJ
where
case
   when trunc(end_date) - trunc(start_date) > 5
      then GET_WORKDAY_COUNT(trunc(start_date) , trunc(end_date))
   else 0
 end > 5

Or using subquery:
select count(*)
from ERP_SJ e
where
case
   when trunc(end_date) - trunc(start_date) > 5
      then (select count(*) from WORKDAYS w
    where w.ID >= TRUNC(e.start_date)
    and w.ID <= TRUNC(e.end_date)
    and w.status in (1, 3, 5))
   else 0
 end > 5