text:
Q: How to Remove ListView Selection after Selecting an ListView item Could we set a ListView to not retain a selection after a user click on a ListViewItem?
Could it possibly been done?
Note: it is not about changing the style on 'IsSelected' but actually to not having the selection after the user click it.
I have try the following but it was not successful.
In the View:
<ListView Grid.Row="1"
          ItemsSource="{Binding Models}"
          SelectedItem="{Binding SelectedModel}"
          DisplayMemberPath="DisplayContent"/>

In the ViewModel whom having the View DataContext:
public LookupItemWrapper SelectedModel
{
    get { return _selectionModel; }
    set
    {
        _selectionModel = value;

        OnPropertyChanged();

        if (value != null)
        {
            _eventAggregator.GetEvent<OnRequisitionSelectionInRequisitionProjectNavigationEvent>().Publish(
                new OnRequisitionSelectionInRequisitionProjectNavigationEventArgs
                {
                    Requisitionid = _selectionModel.Id
                });
        }

        _selectionModel = null;

        OnPropertyChanged();
    }
}

I guess I know a way to imitate that by having ItemsControl with Button as its item.
However I really like to know if I could do this with a ListView.
Update
I have written the following event handler wrt Clemens & Ed Plunkett suggestion. But where do I place the code? I should not place it inside the VM constructor as everytime SelectedModel is set to null, so does with this event handler logic.
SelectedModel.PropertyChanged += (s, e) =>
{
    if (SelectedModel != null)
    {
        ((ListView)s).SelectedItem = null;
    }
};

Update With Answer
I have try using ItemsControl.
I write the ItemsControl's ItemTemplate which has a Button that bind with a command for mouse click.This work fine.
I also write the ItemsControl's ItemTemplate which I intend to define the its style, however ItemContainerStyle can only has TargetType of ContentPresenter. Meaning I can't add Border, ScrollViewer, Grid or any other UI element inside the style. Sure, I can write it directly on the UserControl/MainWindow such as following:
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
    <Border BorderBrush="Black" BorderThickness="10">
        <ItemsControl Grid.Column="0"
                        ItemsSource="{Binding Friends}"
                        ItemContainerStyle="{StaticResource ItemContainerStyle}"
                        ItemTemplate="{StaticResource ItemTemplate}"/>
    </Border>
</ScrollViewer>

I found out ItemsControl is raw and not elegent.
So I come back to ListView.
What I have done is:

*

*I've defined style for the ListView which I add border, scrollviewer and ItemsPresenter (which represent the collection of ListViewItem).

*Then I've defined style for ListViewItem which consist of a Button, command, style trigger.

*Lastly, in the UserControl/MainWindow, I add the ListView.

*I have set the ListView Style property to the defined ListView style and set its ItemContainerStyle property to the defined style of ListViewItem.
I do not set or use ListView SelectedItem property.
I response to user click not by monitoring to the property bind to the SelectedItem rather by handling the button command binding.
This is easier and much elegent.
<ListView Grid.Row="1"
            ItemsSource="{Binding Models}"
            ItemContainerStyle="{StaticResource RequisitionNavigationItemListViewItemStyle}"
            Style="{StaticResource RequisitionNavigationListViewStyle}"/>

Here is both styles definition:
<Style x:Key="RequisitionNavigationItemListViewItemStyle" TargetType="{x:Type ListViewItem}">
    <Setter Property="Background" Value="{StaticResource ViewListBackgroundBrush}"/>
    <Setter Property="Foreground" Value="{StaticResource ViewListForegroundBrush}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListViewItem}">
                <Button Content="{Binding DisplayContent}"
                        Command="{Binding DataContext.OnSelectingRequisitionCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
                        CommandParameter="{Binding}">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Grid x:Name="grid">
                                <Border x:Name="BorderInButton" Background="{StaticResource RequisitionNavigationBackgroundBrush}"  Height="65" SnapsToDevicePixels="True">
                                    <ContentPresenter x:Name="ContentPresenterInButton" TextBlock.Foreground="{StaticResource RequisitionNavigationForegroundBrush}">
                                        <ContentPresenter.Resources>
                                            <Style TargetType="{x:Type TextBlock}">
                                                <Setter Property="TextWrapping" Value="Wrap"/>
                                                <Setter Property="FontSize" Value="12"/>
                                                <Setter Property="Margin" Value="10"/>
                                            </Style>
                                        </ContentPresenter.Resources>
                                    </ContentPresenter>
                                </Border>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter TargetName="BorderInButton" Property="Background" Value="{StaticResource RequisitionNavigationBackgroundHighlightedBrush}"/>
                                    <Setter TargetName="ContentPresenterInButton" Property="TextBlock.Foreground" Value="{StaticResource RequisitionNavigationForegroundHighlightedBrush}"/>
                                    <Setter Property="Cursor" Value="Hand"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="RequisitionNavigationListViewStyle" TargetType="{x:Type ListView}">
    <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
    <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
    <Setter Property="ScrollViewer.CanContentScroll" Value="true"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListView}">
                <Border x:Name="Bd" BorderBrush="{StaticResource ViewListBorderBrush}" BorderThickness="2 1 4 4" Background="{StaticResource ViewListBackgroundBrush}" Padding="0" SnapsToDevicePixels="True">
                    <ScrollViewer Style="{StaticResource ScrollViewerStyle}">
                        <ItemsPresenter/>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

A: Setting Focusable property to false in ListBoxItem style may help you:
<Style x:Key="{x:Type ListBoxItem}" TargetType="{x:Type ListBoxItem}">
  <Setter Property="Focusable" Value="False" />
</Style>


text:
Q: Android loading images efficient (out of memory) I just startet writing an app for Android. I have 3 activitys that use the same xml layout, an grid view. They also use all the same adapter to show an imageview and an textview in each grid item. When you select an object in the first activity, you get to the second and then to the third.
First I used the normal method "imageView.setImageResource(drawableid)". It wasn't really a problem, but when I put more images into the gridview, I got the outofmemory error.
So I search for a solution. I tried the thing from the android dev site with decode bitmap, resize and Async task and so on.
The other thing was the picasso library, wich would be very simple with "Picasso.with(mContext).load(imageURI).into(imageView);". But picasso ist to slow for the gridview. It looks messed up while scrolling. And sometimes some images weren't load.
All metodes fill the memory and the app crashes when I open the activities a couple times.
What am I doing wrong? Can I free up the memory by myself, when I leave the first activity to the second?

A: Best solution is use the RecyclerView in your app
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html

A: There was an answer in SO about freeing up memory manually. I couldn't find it now so I am pasting the answer I am implementing
Define the following function
    //To free up memory taken by adapterViews and others
private void unbindDrawables(View view) {
    if (view.getBackground() != null)
        view.getBackground().setCallback(null);

    if (view instanceof ImageView) {
        ImageView imageView = (ImageView) view;
        imageView.setImageBitmap(null);
    } else if (view instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup) view;
        for (int i = 0; i < viewGroup.getChildCount(); i++)
            unbindDrawables(viewGroup.getChildAt(i));

        if (!(view instanceof AdapterView))
            viewGroup.removeAllViews();
    }
}

then in your onDestroy method use
unbindDrawables(findViewById(R.id.view_to_unbind));
System.gc();

This has stopped my app from crashing on orientation change.

A: You load image thumbnail in grid view not the main image after clicking on gridview you make a request to load the main image. Store thumbnails on server also.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jar folder becomes class folder under 'Referenced Libraries' in eclipse I have a Java project in eclipse in which I would like to add 3 jar files to the build path:

However, when I select them and add them to the build path (right click / Build path / Add to build path), they are added to the 'Referenced Libraries' node along with the 'jars' folder that becomes a class folder:

Notice that the 'jars' folder directly under the project root can no longer expand as if it were empty.
Now this is fine for developing as the jars have been added to the build path, but problems appear when I try to export my project as a jar file (regular, not runnable):

The 'jars' folder appears empty and indeed is not exported with the class files when I check the resulting jar file. I have plenty of projects set up like this and it normally works. I switched versions to eclipse 4.3 but I still get the same behavior.
Can anyone help me out?

A: Juding by the icon for your jars-folder (note the tiny 010) you have configured it as a "class folder" on your build path. The contents of this don't seem to be exported into the jar-file.
To fix the issue got to your project's build-path configuration, under "libraries" you should find the jars-folder as class-file-folder. Select the entry, click "remove", export - and voila, everything should be there.

A: It's because that the particular jar file is added to build path as well as the folder containing the jar is added as Class Folder.
Eg: ABC/xyz.jar
xyz.jar is added to build path using the option Add to Build Path
and
ABC is added to library using the option Add Class Folder using the Configure Build path wizard.
You may remove the folder from class folder and it will be resolved.


text:
Q: Html Element Not Aligning All The Way To The Left I'm not new to HTML or CSS, but I really don't know why this is happening. I could just be dumb and this is an easy question something is really wrong. I'm really having trouble with this. I have a very simple web page with a div element. Not matter what I do I still have space at the top, side, and bottom of it. Here's a picture.

And Here's my HTML and CSS code.

 <!DOCTYPE html>

    <title>Home</title>

            asd

A: You should assign margin 0 and padding 0 to body element in your styling.

A: This happens because the  element has margin by default in some browsers. Different browsers can choose to apply some basic default styling to elements. Chrome, for example, adds 8px margin to  by default. If you set
body {
  margin: 0px;
}

This will dissappear.
A better way to go about it is to include Reset.css or Normalize.css in your code. Reset.css will unstyle absolutely everything, so that what you write is exactly what is displayed. This gives you greatest control but for most cases it's too much. For example,
 ,
 ,
.. tags will all look the same after applying Reset.css .
Normalize.css on another hand preserves useful styling but will make sure that your elements are rendered consistently across all browsers. This is preferred in most cases.
In Codepen you can even try these out. If you click 'Settings' you can choose to include 'Normalize' or 'Reset' in your CSS. You can play around with these to see how your elements are displayed under each.

A: As Frontend employee said just add
.body{
    margin: 0;
    padding: 0;
}

a lot of people employee CSS reset codes at the top of their stylesheets which includes this. Its basically a list of default overrides that clears any styling on elements allowing you to begin with a clean slate
See (http://cssreset.com/scripts/html5-doctor-css-reset-stylesheet/)


text:
Q: EF4 CTP5: DbContext inheritance I have a hierarchical DbContext structure, where I would like a specialized DbContext with its own DbSets to inherit the DbSets of a BaseDbContext.
While accessing the underlying ObjectContext with ((IObjectContextAdapter)this).ObjectContext it takes too long (several minutes) to receive the ObjectContext.
Is there an issue with DbContext in CT5, that getting an ObjectContext from derived DbContext is not performantly possible?
The structure is: DbContext(EF4) -> myBaseDbContext -> mySpecializedDbContext.
Does anyone have an idea of what´s going on in this scenario?
It´s just POCO (CF) with TPC and a little inheritance.

A: I didn't have performance issues with following and you don't have so many DbSets:
public class MyContext: DbContext
    {
       //your DbSets<> and other

       public ObjectContext ObjectContext()
       {
          return (this as IObjectContextAdapter).ObjectContext;
       }
    }


text:
Q: To check application status or not I have a application, I am trying to check the task is successful completed or not.
I am trying to collect the event message from the events, which state as completed.
Code:
$app1 = "###########" # application name
$sourcelocation = "$$$$$$$$$" # from location
$Destination = "@@@@@@@@@@@@"
$events = Get-SECEvent -MaxSamples 100 -Start (Get-Date).AddMinutes(-1)
if ($event.Message -match "Moving of application $app1 * completed") {
    Write-Host "The application is completed"
} else {
    Write-Host "The application is Not completed"
}

The below is the message event looks like.

Message : Moving of application "###########" from "$$$$$$$$$", &&&&&&&&&&& to
                       @@@@@@@@@@@@, &&&&&&&&&&& completed

Note: In the Message event, I can see other applications information too, but I want this particular $app1, $source location and $Destination identified and completed.


text:
Q: How to apply piecewise linear fit in Python? I am trying to fit piecewise linear fit as shown in fig.1 for a data set

This figure was obtained by setting on the lines. I attempted to apply a piecewise linear fit using the code:
from scipy import optimize
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15])
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

def linear_fit(x, a, b):
    return a * x + b
fit_a, fit_b = optimize.curve_fit(linear_fit, x[0:5], y[0:5])[0]
y_fit = fit_a * x[0:7] + fit_b
fit_a, fit_b = optimize.curve_fit(linear_fit, x[6:14], y[6:14])[0]
y_fit = np.append(y_fit, fit_a * x[6:14] + fit_b)

figure = plt.figure(figsize=(5.15, 5.15))
figure.clf()
plot = plt.subplot(111)
ax1 = plt.gca()
plot.plot(x, y, linestyle = '', linewidth = 0.25, markeredgecolor='none', marker = 'o', label = r'\textit{y_a}')
plot.plot(x, y_fit, linestyle = ':', linewidth = 0.25, markeredgecolor='none', marker = '', label = r'\textit{y_b}')
plot.set_ylabel('Y', labelpad = 6)
plot.set_xlabel('X', labelpad = 6)
figure.savefig('test.pdf', box_inches='tight')
plt.close()

But this gave me fitting of the form in fig. 2, I tried playing with the values but no change I can't get the fit of the upper line proper. The most important requirement for me is how can I get Python to get the gradient change point. In essence I want Python to recognize and fit two linear fits in the appropriate range. How can this be done in Python?

A: You can use numpy.piecewise() to create the piecewise function and then use curve_fit(), Here is the code
from scipy import optimize
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15], dtype=float)
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

def piecewise_linear(x, x0, y0, k1, k2):
    return np.piecewise(x, [x < x0], [lambda x:k1*x + y0-k1*x0, lambda x:k2*x + y0-k2*x0])

p , e = optimize.curve_fit(piecewise_linear, x, y)
xd = np.linspace(0, 15, 100)
plt.plot(x, y, "o")
plt.plot(xd, piecewise_linear(xd, *p))

the output:

For an N parts fitting, please reference segments_fit.ipynb

A: You are looking for Linear Trees. They are the best method to apply, in a generalized and automated way, a piecewise linear fit (also for multivariate and in classification contexts).
Linear Trees differ from Decision Trees because they compute linear approximation (instead of constant ones) fitting simple Linear Models in the leaves.
For a project of mine, I developed linear-tree: a python library to build Model Trees with Linear Models at the leaves.

linear-tree is developed to be fully integrable with scikit-learn.
from sklearn.linear_model import *
from lineartree import LinearTreeRegressor, LinearTreeClassifier

# REGRESSION
regr = LinearTreeRegressor(base_estimator=LinearRegression())
regr.fit(X, y)

# CLASSIFICATION
clf = LinearTreeClassifier(base_estimator=RidgeClassifier())
clf.fit(X, y)

LinearTreeRegressor and LinearTreeClassifier are provided as scikit-learn BaseEstimator. They are wrappers that build a decision tree on the data fitting a linear estimator from sklearn.linear_model. All the models available in sklearn.linear_model can be used as linear estimators.
Compare Decision Tree with Linear Tree:

Considering your data, the generalization is extremely straightforward:
from sklearn.linear_model import LinearRegression
from lineartree import LinearTreeRegressor
import numpy as np
import matplotlib.pyplot as plt

X = np.array(
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15]
    ).reshape(-1,1)
y = np.array(
    [5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03]
    )

model = LinearTreeRegressor(base_estimator=LinearRegression())
model.fit(X, y)

plt.plot(X, y, ".", label='TRUE')
plt.plot(X, model.predict(X), label='PRED')
plt.legend()

A: An example for two change points. If you want, just test more change points based on this example.
np.random.seed(9999)
x = np.random.normal(0, 1, 1000) * 10
y = np.where(x < -15, -2 * x + 3 , np.where(x < 10, x + 48, -4 * x + 98)) + np.random.normal(0, 3, 1000)
plt.scatter(x, y, s = 5, color = u'b', marker = '.', label = 'scatter plt')

def piecewise_linear(x, x0, x1, b, k1, k2, k3):
    condlist = [x < x0, (x >= x0) & (x < x1), x >= x1]
    funclist = [lambda x: k1*x + b, lambda x: k1*x + b + k2*(x-x0), lambda x: k1*x + b + k2*(x-x0) + k3*(x - x1)]
    return np.piecewise(x, condlist, funclist)

p , e = optimize.curve_fit(piecewise_linear, x, y)
xd = np.linspace(-30, 30, 1000)
plt.plot(x, y, "o")
plt.plot(xd, piecewise_linear(xd, *p))

A: You can use pwlf to perform continuous piecewise linear regression in Python. This library can be installed using pip.
There are two approaches in pwlf to perform your fit:

*

*You can fit for a specified number of line segments.

*You can specify the x locations where the continuous piecewise lines should terminate.

Let's go with approach 1 since it's easier, and will recognize the 'gradient change point' that you are interested in.
I notice two distinct regions when looking at the data. Thus it makes sense to find the best possible continuous piecewise line using two line segments. This is approach 1.
import numpy as np
import matplotlib.pyplot as plt
import pwlf

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59,
              84.47, 98.36, 112.25, 126.14, 140.03])

my_pwlf = pwlf.PiecewiseLinFit(x, y)
breaks = my_pwlf.fit(2)
print(breaks)

[ 1.          5.99819559 15.        ]
The first line segment runs from [1., 5.99819559], while the second line segment runs from [5.99819559, 15.]. Thus the gradient change point you asked for would be 5.99819559.
We can plot these results using the predict function.
x_hat = np.linspace(x.min(), x.max(), 100)
y_hat = my_pwlf.predict(x_hat)

plt.figure()
plt.plot(x, y, 'o')
plt.plot(x_hat, y_hat, '-')
plt.show()

A: Use numpy.interp which returns the one-dimensional piecewise linear interpolant to a function with given values at discrete data-points.

A: You could do a spline interpolation scheme to both perform piecewise linear interpolation and find the turning point of the curve. The second derivative will be the highest at the turning point (for an monotonically increasing curve), and can be calculated with a spline interpolation of order > 2.
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15])
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

tck = interpolate.splrep(x, y, k=2, s=0)
xnew = np.linspace(0, 15)

fig, axes = plt.subplots(3)

axes[0].plot(x, y, 'x', label = 'data')
axes[0].plot(xnew, interpolate.splev(xnew, tck, der=0), label = 'Fit')
axes[1].plot(x, interpolate.splev(x, tck, der=1), label = '1st dev')
dev_2 = interpolate.splev(x, tck, der=2)
axes[2].plot(x, dev_2, label = '2st dev')

turning_point_mask = dev_2 == np.amax(dev_2)
axes[2].plot(x[turning_point_mask], dev_2[turning_point_mask],'rx',
             label = 'Turning point')
for ax in axes:
    ax.legend(loc = 'best')

plt.show()

A: I think that UnivariateSpline from scipy.interpolate would provide the simplest and very likely the fastest way to do piecewise fit. To add a bit of context, spline is a function defined piecewise by polynomials. In your case, you are looking for a linear spline which is defined by k=1 in UnivariateSpline. Also, s=0.5 is a smoothing factor which indicates how good the fit should be (check out the documentation for more info on it).
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

# Solution
spl = UnivariateSpline(x, y, k=1, s=0.5)
xs = np.linspace(x.min(), x.max(), 1000)

fig, ax = plt.subplots()
ax.scatter(x, y, color="red", s=20, zorder=20)
ax.plot(xs, spl(xs), linestyle="--", linewidth=1, color="blue", zorder=10)
ax.grid(color="grey", linestyle="--", linewidth=.5, alpha=.5)
ax.set_ylabel("Y")
ax.set_xlabel("X")
plt.show()

A:
This approach uses Scikit-Learn to apply segmented linear regression.
You can use this, if your points are are subject to noise.
It is way faster, significantly more robust and more generic than performing a giant optimization task (anything from scip.optimize like curve_fit with more then 3 parameters).
import numpy as np
import matplotlib.pylab as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression

# parameters for setup
n_data = 20

# segmented linear regression parameters
n_seg = 3

np.random.seed(0)
fig, (ax0, ax1) = plt.subplots(1, 2)

# example 1
#xs = np.sort(np.random.rand(n_data))
#ys = np.random.rand(n_data) * .3 + np.tanh(5* (xs -.5))

# example 2
xs = np.linspace(-1, 1, 20)
ys = np.random.rand(n_data) * .3 + np.tanh(3*xs)

dys = np.gradient(ys, xs)

rgr = DecisionTreeRegressor(max_leaf_nodes=n_seg)
rgr.fit(xs.reshape(-1, 1), dys.reshape(-1, 1))
dys_dt = rgr.predict(xs.reshape(-1, 1)).flatten()

ys_sl = np.ones(len(xs)) * np.nan
for y in np.unique(dys_dt):
    msk = dys_dt == y
    lin_reg = LinearRegression()
    lin_reg.fit(xs[msk].reshape(-1, 1), ys[msk].reshape(-1, 1))
    ys_sl[msk] = lin_reg.predict(xs[msk].reshape(-1, 1)).flatten()
    ax0.plot([xs[msk][0], xs[msk][-1]],
             [ys_sl[msk][0], ys_sl[msk][-1]],
             color='r', zorder=1)

ax0.set_title('values')
ax0.scatter(xs, ys, label='data')
ax0.scatter(xs, ys_sl, s=3**2, label='seg lin reg', color='g', zorder=5)
ax0.legend()

ax1.set_title('slope')
ax1.scatter(xs, dys, label='data')
ax1.scatter(xs, dys_dt, label='DecisionTree', s=2**2)
ax1.legend()

plt.show()

how it works

*

*calculate slope at each point

*group similar slopes by using a decision tree (right plot)

*perform linear regression for each group in the original data

A: Extending @binoy-pilakkat's answer.
You should use numpy.interp:
import numpy as np
import matplotlib.pyplot as plt

x = np.array(range(1,16), dtype=float)
y = np.array([5, 7, 9, 11, 13, 15, 28.92,
          42.81, 56.7, 70.59, 84.47,
          98.36, 112.25, 126.14, 140.03], dtype=float)

yinterp = np.interp(x, x, y) # simple as that

plt.plot(x, y, 'bo')
plt.plot(x, yinterp, 'g-')
plt.show()

A: piecewise works too
from piecewise.regressor import piecewise
import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15,16,17,18], dtype=float)
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03,120,112,110])

model = piecewise(x, y)

Evaluate 'model':
FittedModel with segments:
* FittedSegment(start_t=1.0, end_t=7.0, coeffs=(2.9999999999999996, 2.0000000000000004))
* FittedSegment(start_t=7.0, end_t=16.0, coeffs=(-68.2972222222222, 13.888333333333332))
* FittedSegment(start_t=16.0, end_t=18.0, coeffs=(198.99999999999997, -5.000000000000001))

A: There are already good answers here, but here's another way to do it using a simple neural network. The basic idea is the same as some of the other answers; i.e.,

*

*create dummy variables that indicate whether the input variable is greater than some break point

*create dummy interactions by subtracting the break point from the input variable and then multiplying the result with the corresponding dummy variable

*train a linear model using the input variable and dummy interactions as features

The main difference is that here the break points are learned end-to-end via gradient descent rather than treated as hyperparameters. This approach naturally extends to more than one break point and can be used with any relevant loss function.
import torch
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59,
              84.47, 98.36, 112.25, 126.14, 140.03])

Define the model, optimizer, and loss function:
class PiecewiseLinearModel(torch.nn.Module):
    def __init__(self, n_breaks):
        super(PiecewiseLinearModel, self).__init__()
        self.breaks = torch.nn.Parameter(torch.randn((1,n_breaks)))
        self.linear = torch.nn.Linear(n_breaks+1, 1)
    def forward(self, x):
        return self.linear(torch.cat([x, torch.clamp_min(x - self.breaks, 0)],1))

plm = PiecewiseLinearModel(n_breaks=1)
optimizer = torch.optim.Adam(plm.parameters(), lr=0.1)
loss_func = torch.nn.functional.mse_loss

Train the model:
x_torch = torch.tensor(x, dtype=torch.float)[:,None]
y_torch = torch.tensor(y)[:,None]
for _ in range(10000):
    p = plm(x_torch)
    optimizer.zero_grad()
    loss_func(y_torch, p).backward()
    optimizer.step()

Plot the predictions:
x_grid = np.linspace(0,16,1000)
p = plm(torch.tensor(x_grid, dtype=torch.float)[:,None])
p = p.flatten().detach().numpy()
plt.plot(x, y, ".")
plt.plot(x_grid, p)
plt.show()

Inspect the model parameters:
print(plm.state_dict())
> OrderedDict([('breaks', tensor([[6.0033]])),
               ('linear.weight', tensor([[ 1.9999, 11.8892]])),
               ('linear.bias', tensor([2.9963]))])

The predictions of neural network are equivalent to:
def f(x):
   return 1.9999*x + 11.8892*(x - 6.0033)*(x > 6.0033) + 2.9963

A: The piecewise-regression python package handles exactly this problem.
import numpy as np
import matplotlib.pyplot as plt
import piecewise_regression

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15])
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

pw_fit = piecewise_regression.Fit(x, y, n_breakpoints=1)
pw_fit.plot()
plt.xlabel("x")
plt.ylabel("y")
plt.show()

It also gives the results of the fit:
pw_fit.summary()

It works by implementing Muggeo's iterative algorithm. More code examples here
Example with some noise. For a more interesting example, we can add some noise to the y data and fit it again:
y += np.random.normal(size=len(y)) * 5

pw_fit = piecewise_regression.Fit(x, y, n_breakpoints=1)
pw_fit.plot()


text:
Q: Is this interface thread-safe? I want to make a control loop interface.
It has should_stop() method to check if loop should break or continue.
It does listen to SIGINT signal(Ctrl+C) and after it gets the signal should_stop() method returns True.
Now it seems like this interface is working.
But I'm not sure this interface is thread-safe.
LoopInterface.h file
#include "signal.h"
#include "pthread.h"

#define LOCK(mutex)     pthread_mutex_lock(&mutex)
#define UNLOCK(mutex)   pthread_mutex_unlock(&mutex)

class LoopInterface {
public:
    LoopInterface(){
        LOCK(_lock_is_signal_registered);
        bool temp = _is_signal_registered;
        UNLOCK(_lock_is_signal_registered);
        if(!temp)
        {
            register_signal();
        }
    }

    bool should_stop()
    {
        LOCK(_lock_should_stop);
        bool temp = _should_stop;
        UNLOCK(_lock_should_stop);
        return _should_stop;
    }

private:

    static void register_signal()
    {
        LOCK(_lock_is_signal_registered);
        _is_signal_registered = true;
        UNLOCK(_lock_is_signal_registered);

        signal(SIGINT, &LoopInterface::signal_handler);
    }

    static void signal_handler(int sig){
        LOCK(_lock_should_stop);
        _should_stop = true;
        UNLOCK(_lock_should_stop);
    }

    static bool _should_stop;
    static bool _is_signal_registered;
    static pthread_mutex_t _lock_should_stop, _lock_is_signal_registered;
};

LoopInterface.cpp file
#include "LoopInterface.h"
bool LoopInterface::_should_stop = false;
bool LoopInterface::_is_signal_registered = false;
pthread_mutex_t LoopInterface::_lock_should_stop;
pthread_mutex_t LoopInterface::_lock_is_signal_registered;

And this is how it is used.
/************Threads*************/
#include "LoopInterface.h"
class A : public LoopInterface{

};

void threadX(){
    A a;
    while(!a.should_stop()){
        //do something...
    }
}

Can you tell me this interface would work thread-safely? or not?
If not, what is the problem?

Additional Problem
There is one more problem on my synchronized code.
Deadlock occurs quite frequently because of calling pthread_mutex_lock in signal_handler while should_stop method is locking the same mutex.
And I found an article stating that thread-related functions should not called in signal handler.
I think I should find another way to synchronize my member variables.

A: Clearly, this code is not thread-safe: the variable _should_stop is set by the signal in some uncontrolled thread and read in the LoopInterface running its own thread. There is no synchronization at all. This approach can only be thread-safe if there is exactly one thread.
You can make the code thread-safe (with respect to this specific variable) using
static std::atomic<bool> _should_stop;

Since you are not interested in any other values at this point, you can read the variable with the std::memory_order_relaxed flags.
If the constructor is of LoopInterface is called from multiple threads you also need to synchronize  access to _is_signal_registered, of course.


text:
Q: How to get paid invoice collection filter by payment method How can I get invoice collection filter by status paid & payment method ?
I know how to filter order collection by payment method
$orders = Mage::getModel('sales/order')->getCollection();
$orders->getSelect()->join(
    array('payment' =>  $orders->getResource()->getTable('sales/order_payment')),
    'payment.parent_id = main_table.entity_id',
    array('*')
);
$orders->addFieldToFilter('method','ccsave');

But I can't make it work with
Mage::getModel("sales/order_invoice")->getCollection();

where invoice status is also paid

A: Try this:
$collection = Mage::getResourceModel('sales/order_invoice_collection');
$collection->addFieldToFilter('state', Mage_Sales_Model_Order_Invoice::STATE_PAID);
$collection->getSelect()->join(array('P' => $collection->getResource()->getTable('sales/order_payment')),"P.parent_id = main_table.order_id",array('method'=>'P.method'));
$collection->addFieldToFilter('method', 'checkmo');
echo '<pre>';
foreach($collection as $invoice) {
    print_r($invoice);
}

A: As stated in Magento User Guide: "Invoice is a record of the receipt of payment for an order" there is no need to apply paid filter to invoice collection. Please refer Magento Guide for further details.
However, if you want to get invoice collection by payment method you can use below code.
$orders = Mage::getModel("sales/order_invoice")->getCollection();
$orders->getSelect()->join(
    array('payment' =>  $orders->getResource()->getTable('sales/order_payment')),
    'payment.parent_id = main_table.order_id',
    array('*')
);
$orders->addFieldToFilter('method','ccsave');  // Set you payment method here


text:
Q: Unable to send email from Ghost I have been wrestling with this for days. I am exasperated in extremis.
I have a hosted Ghost blog at umquhile.org/kelpie. It has been working fine. Somehow I locked myself out of my account. 75,000 posts say I need to set up email so I can click on "Forgotten Password". I have gone by 12,000 posts (okay, a SLIGHT exaggeration) that show how to do it. First, Ghost's tutorial flat does not work. I have tried vanilla sendmail (which is expected not to work), Mailgun, Sendgrid, and Gmail. I have gone over my configuration repeatedly.
I get different error messages depending on how I set it up. Sometimes I have gotten a 535 - invalid login credentials, sometimes all recipients rejected; right now I am getting "Cannot read property 'count' of undefined", whatever that one is. Can someone tell me if there is a problem with this configuration. Or how-the-deuce to get email to work in Ghost.
I should note that I have restarted node.js each time I made a change.
config = {
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
    url: 'http://umquhile.org/kelpie',
    mail: {
        service: 'Gmail',
        fromaddress: 'xxxx@gmail.com',
        transport: 'SMTP',
        options: {
            host: 'smtp.gmail.com',
            secureConnection: true,
            port: 465,
            auth:  {
                user: 'xxxx@gmail.com',
                pass: 'xxxxxxxxxxxxxx'
            }
        }
    },

For what is's worth, I read that Ghost uses Bcrypt hash for passwords. I have used an online Bcrypt generator to hash a password I provided. I copied the string and pasted it into the password field of my admin user in Mysql. That did not work because my account just flat remains locked.

A: And as soon as I post to stackoverflow, it hits me!!
I went into the database, via phpmyadmin, and found the field status
It was set to locked
I cleared the field, saved the change, and tadaaa! I am now able to access my blog once again. Sorry for the nuisance post! The answer JUST occurred to me.


text:
Q: C# Combobox (winforms) how can I make the values appear as percentage I've got a combo box with a set of values( 5, 10,15, 20).
When the user goes to select a value I want them to appear as percentages (5%, 10%, 15%, 20%).
I was playing with format string using a value of ##% but that did not work.

A: FormatString should work, but it will multiply the number by 100.
Probably want to add a 0 in front of your string to handle 0%.
This code worked for me.
    private void Form1_Load(object sender, EventArgs e)
    {
        this.comboBox1.FormatString = "##0%";
        comboBox1.Items.Add(0);
        comboBox1.Items.Add(0.33);
        comboBox1.Items.Add(0.50);
        comboBox1.Items.Add(0.67);
        comboBox1.Items.Add(1);
    }

A: You could set the value to 5, 10, 15, 20 and the display member as 5%, 10%, 15% etc

A: You could either create your own combo box based off of the masked text box control, or format them manually. If your user can't type in their own values, just enter them in pre-formatted. If they can, then manually format them when the combo box raises it's changed event.

A: Hmmm it's very strange problem, I could not solve this in any way. If you want to show normal numbers in your combobox and latter(after selection) change it's text. I did it in this way (looks really funny), and it does solve this problem :)
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    Thread th = new Thread(() => comboBox1.Invoke((Action)(() => comboBox1.Text += @"%"))){ IsBackground = true };
    th.Start();
}


text:
Q: SQL Time Attendance Query Recently I made a switch from MS Access to SQL Server. Due to this switch I am having issues with making one SQL query to work.
This is how the current table looks like in SQL.

This is what I am trying to get as result from the query:

Previously I was able to make it work in MS Access with the following query:
SELECT m.UserEnrollNumber, m.Checktime AS TimeIn, (SELECT Min(s.Checktime)
    FROM CheckInOut1 s
    WHERE s.UserEnrollNumber = m.UserEnrollNumber
    AND s.Checktime > m.Checktime
    AND s.Checktime <= Int(m.Checktime) + 1) AS TimeOut
FROM CheckInOut1 AS m
WHERE ((((SELECT COUNT(*)
    FROM CheckInOut1 s
    WHERE s.UserEnrollNumber = m.UserEnrollNumber
    AND s.Checktime <= m.Checktime
    AND s.Checktime >= INT(m.Checktime)) Mod 2)=1));

The following query as answer from @GMB:
select
        employee_id,
        min(time_in_out) check_in,
        max(time_in_out) check_out
    from (
        select t.*, row_number() over(partition by employee_id order by time_in_out) - 1 rn
        from mytable t
    ) t
    group by employee_id, floor(rn / 2)
    order by employee_id, floor(rn / 2)

from SQL table:

gives me the following result:

Seems like the minimum and maximum rows are shown, but the rows in between are not.
The following query from @Gordon Linoff:
SELECT cio.EmployeeID, cio.TimeInOut AS CheckIn,
       cio.TimeInOut as CheckOut
FROM (SELECT cio.*,
             ROW_NUMBER() OVER (PARTITION BY cio.EmployeeID, CONVERT(date, cio.TimeInOut) ORDER BY cio.TimeInOut) as seqnum,
             LEAD(cio.TimeInOut) OVER (PARTITION BY cio.EmployeeID, CONVERT(date, cio.TimeInOut) ORDER BY cio.TimeInOut) as next_TimeInOut
      FROM CheckInOut22 cio
     ) cio
WHERE seqnum % 2 = 1;

Gives me the following result:

Checkin is the same as CheckOut.
All help would be appreciated.

A: This is much simpler in SQL Server.  Use window functions:
SELECT cio.EmployeeID, cio.TimeInOut AS CheckIn,
       cio.next_TimeInOut as CheckOut
FROM (SELECT cio.*,
             ROW_NUMBER() OVER (PARTITION BY cio.EmployeeID, CONVERT(date, cio.TimeInOut) ORDER BY cio.TimeInOut) as seqnum,
             LEAD(cio.TimeInOut) OVER (PARTITION BY cio.EmployeeID, CONVERT(date, cio.TimeInOut) ORDER BY cio.TimeInOut) as next_TimeInOut
      FROM CheckInOut cio
     ) cio
WHERE seqnum % 2 = 1;


text:
Q: Adding punctuation to jquery results I am using JQuery to find all checked items in an HTML form and return a sentence including the checked items.  I have the sentence structure down, but am having a mental block figuring out how to append punctuation to the sentence, such as: "You have chosen "item1", Item2", and "Item3". Please click each link to learn more."
How can I add the comma between each item, and add an "and" before only the last one?
I've included a small snipped of my JQuery, if I need to show more I can.  Thanks!
$("#list").append("You have indicated an interest in ");
    $.each(linkValues, function(i, val) {
      $("#list").append("" + val + "   ");
    });
    $("#list").append("Please click on the links to learn more about these resources.");
    break;
}

A: Adding a comma is easy:
$.each(linkValues, function(i, val) {
  $("#list").append("" + val + ",   ");
//                                                              ^^^
});

Getting it not to show up after the last one is a bit harder.
You can detect if it's the last one by checking i and linkValues.length:
i == linkValues.length - 1

Then, we can use the ternary operator to only add things when it's the last one:
$.each(linkValues, function(i, val) {
  var isLast = i == linkValues.length - 1;
  $("#list").append((isLast ? "and " : "") + "" + val + "" + (isLast ? ", " : " "));
});


text:
Q: how to Save a bool to show its value after the application re-opens in Core Data I have a core data that saves parsed feed and stores it. It then shows that feed and i have a button in every table view cell that bookmarks the cell to show it even if the application is offline.
this is the code for the button.
- (void)clickedButton:(UIButton*)sender {

    NSLog(@"Row: %d", sender.tag);

    NSIndexPath* indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
    Stories *story = (Stories *)[self.fetchedResultsController objectAtIndexPath:indexPath];
    BOOL isSaved = [story.isBookmarked boolValue];
    story.isBookmarked = [NSNumber numberWithBool:!isSaved];

    [self.tableView reloadData];

my question is :
how do i save the bool value to show even when the application restarts.

A: you can use NSUserDefaults.
With this code you save your value
[[NSUserDefaults standardUserDefaults] setBool: forKey: ];
Using this approach, you can even make your own value appears in iOS device setting.
Just add Setting.bundle and define what you want.
Other way is to use NSCoding protocol. It is simpler but no end user can see your stored values.


text:
Q: C# winspool.drv call to WritePrinter not printing I'm using some code I found online which was a solution to someone else's similar printing problem. The code appears to run fine, and even errors out when I would expect it to (for example, when I purposefully enter in a bad printer name). The problem I'm having is that the interop call to winspool.drv's WritePrinter method does not seem to cause the printer to print anything, even though this method returns "true". Any ideas why the printer isn't actually printing???
public class PrintRaw
    {
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        public class DOC_INFO_1
        {
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDocName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pOutputFile;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDataType;
        }

        [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi,
          ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter,
                                              IntPtr pd);

        [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true,
          CallingConvention = CallingConvention.StdCall)]
        public static extern bool ClosePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi,
          ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level,
                                                  [In, MarshalAs(UnmanagedType.LPStruct)] DOC_INFO_1 di);

        [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true,
          CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndDocPrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true,
          CallingConvention = CallingConvention.StdCall)]
        public static extern bool StartPagePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true,
          CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndPagePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true,
          CallingConvention = CallingConvention.StdCall)]
        public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

        public void Print(String printerName, String filename)
        {
            IntPtr lhPrinter;
            OpenPrinter(printerName, out lhPrinter, new IntPtr(0));

            if (lhPrinter.ToInt32() == 0)
                return; //Printer not found!!

            var rawPrinter = new DOC_INFO_1() { pDocName = "My Document", pDataType = "RAW" };

            StartDocPrinter(lhPrinter, 1, rawPrinter);

            using (var b = new BinaryReader(File.Open(filename, FileMode.Open)))
            {
                var length = (int)b.BaseStream.Length;
                const int bufferSize = 8192;

                var numLoops = length / bufferSize;
                var leftOver = length % bufferSize;

                for (int i = 0; i < numLoops; i++)
                {
                    var buffer = new byte[bufferSize];
                    int dwWritten;

                    b.Read(buffer, 0, bufferSize);
                    IntPtr unmanagedPointer = Marshal.AllocHGlobal(buffer.Length);
                    Marshal.Copy(buffer, 0, unmanagedPointer, buffer.Length);
                    WritePrinter(lhPrinter, unmanagedPointer, bufferSize, out dwWritten);
                    Marshal.FreeHGlobal(unmanagedPointer);
                }

                if (leftOver > 0)
                {
                    var buffer = new byte[leftOver];
                    int dwWritten;

                    b.Read(buffer, 0, leftOver);
                    IntPtr unmanagedPointer = Marshal.AllocHGlobal(buffer.Length);
                    Marshal.Copy(buffer, 0, unmanagedPointer, buffer.Length);
                    var result = WritePrinter(lhPrinter, unmanagedPointer, leftOver, out dwWritten);
                    Marshal.FreeHGlobal(unmanagedPointer);
                }
            }

            EndDocPrinter(lhPrinter);
            ClosePrinter(lhPrinter);
        }
    }

A: In my case I found the solution changing the pDataType
For Win7 use RAW
For Win8+ use XPS_PASS
Example:
// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
private static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
    bool bSuccess = false; // Assume failure unless you specifically succeed.
    try
    {
        Int32 dwError = 0, dwWritten = 0;
        IntPtr hPrinter = new IntPtr(0);
        DOCINFOA di = new DOCINFOA();

        di.pDocName = "RAW Document";
        // Win7
        //di.pDataType = "RAW";

        // Win8+
        di.pDataType = "XPS_PASS";

        // Open the printer.
        if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
        {
            // Start a document.
            if (StartDocPrinter(hPrinter, 1, di))
            {
                // Start a page.
                if (StartPagePrinter(hPrinter))
                {
                    // Write your bytes.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
        // If you did not succeed, GetLastError may give more information
        // about why not.
        if (!bSuccess)
        {
            dwError = Marshal.GetLastWin32Error();
        }
    }
    catch { }
    return bSuccess;
}

A: Change your code like this:
 var rawPrinter = new DOC_INFO_1() { pDocName = "My Document", pDataType = "Text" };

A: You need to call StartPagePrinter after StartDocPrinter and before WritePrinter

A: [DllImport("winspool.drv", EntryPoint = "FlushPrinter", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool FlushPrinter(IntPtr hPrinter, IntPtr pBuf, Int32 cbBuf, out Int32 pcWritten, Int32 cSleep);

WritePrinter(lhPrinter, unmanagedPointer, bufferSize, out dwWritten);

after add:
FlushPrinter(hPrinter, pBytes, dwCount, out dwWritten,2);

A: Zebra ZPL printer
I had the same issue with Window 10 and updated the following setting to make it work:
Changed highlighted State (Please see below images) from "Not configured" to "Disabled"

A: We ran into an issue with the WritePrinter pinvoke call succeeding but no physical print happening and also no print job making it into the windows print queue.  This call was returning true for success and the number of bytes written was matching the number of bytes that needed to be written.
Solution:
Our problem turned out to be permissions related even though none of the pinvoke calls were failing.  We had to grant read/write access for the user issuing the request to the following folder before this would work:

*

*C:\Windows\System32\spool\PRINTERS

This request was being made by a windows service also for us.


text:
Q: Maximum number of work that can be done in given two time slots [Double Knapsack?] An array A of size N denotes the number of hours required to produce ith object (0 <= i < N). There are two factories that works for X and Y hours respectively.
Every object must be constructed using only one of these factories and only one object at a time can be produced on each factory .
Also, it is not possible to switch factories after starting the object's production.
What is the maximum number of different objects that can be produced in the factories.
Constraints:
1 <= N, A[i] <= 1000
1 <= X, Y <= 500
Example :

*

*A = [1,1,3] , X = 1 , Y = 1
Answer should be 2 as objects at idx 0 and 1 will be constructed

*A = [6,5,5,4,3] , X = 8 , Y = 9
Answer should be 4 as objects that requires 3 and 5 hrs will be produced in 1st factory and cars that require 4 and 5 will be produced in second factory.
What I have thought:

*Double Knapsack
Every object has 3 choices :

*

*To be produced in first factory

*To be produced in second factory

*Not produced at all

So, try all possible options and see which option gives max number of objects.
For this, I used  knapsack kind of approach
 dp[i][x][y] = max no. of objects that can be made using objects till index i in A array with x time remaining in first factory and y time remaining in second factory.

 Then dp[i][x][y] = max(dp[i-1][x-A[i]][y] + 1 , dp[i-1][x][y-A[i]] + 1, dp[i-1][x][y]).
 (with appropriate base cases which I'm not mentioning here).

 and the final ans will be just dp[N-1][X][Y]

This will work but the time Complexity would be O(NXY).
In worst case NXY = 1000* 500* 500 = 2.5*10^8 which will give TLE so it's not good enough.

*Binary Search with DFS
I also thought of doing Binary search on the max number of objects that can be produced.
And for each mid value in BS, check if it is possible to create that many object in X and Y time.
But, for checking I will have to do a DFS or simply put consider putting the object in both the factory for each object.
This checking step will give rise to 2^n time complexity itself.
Or is there any better way to check(some greedy way maybe).
Or, Is there any better algorithm altogether to solve this?

A: As I mentioned in a comment, this is an NP-hard problem, but only weakly NP-hard. A modification of your DP approach gives a pseudopolynomial time algorithm, running in time O(n * min(X, Y) + n * log n), where the n log n comes from sorting the array.
First, note that since we're maximizing the number of items used, if we sort the array, we can just look for placements of the k smallest items for each k. We're only trying to find the first item we can't place.
Your DP algorithm only really needs two variables: the current item, and the capacity remaining in factory/bin X. We can figure out the capacity remaining in the other factory by subtracting from the total capacity used so far:
dp[i][k] = True iff some valid partition of items A[0...i-1]
           leaves bin X with capacity exactly k

Let prefix_sum[i] be sum(A[0...i]).
Then after item i is placed, if we have capacity = k remaining in bin X,
we must have capacity = prefix_sum[i] - (X-k) being used in bin Y

Formula:
dp[i+1][k] = dp[i][k + A[i]] OR (dp[i][k] AND prefix_sum[i] - (X-k) <= Y)

This is valid for all 0 <= i <= n, 0 <= k <= X
with all out-of-range values being False,
and base cases: dp[0][X] = True, dp[0][0...X-1] = False

The final answer will be the maximum i such that dp[i] is not all False.

For your constraints, this means our dp has at most 500,000 subproblems, which is solvable in much less than a second by an implementation like the following Python.
def solve_dp(arr: List[int], X: int, Y: int) -> int:
    n = len(arr)
    arr.sort()

    # Ensure bin X is smaller than bin Y
    if X > Y:
        X, Y = Y, X

    # dp[k] = True iff some valid partition of all items processed so far
    # leaves bin X with capacity exactly k
    dp = [False] * (X + 1)
    dp[X] = True

    running_sum = 0

    for i, item_time in enumerate(arr):
        running_sum += item_time

        # Total extra capacity now allowed in both bins
        max_slack = X + Y - running_sum
        if max_slack < 0:
            return i

        # Largest extra capacity in bin X if we take this item
        first_item_cap = X - item_time

        upper_limit = min(X, max(max_slack, first_item_cap)) + 1
        for capacity in range(upper_limit):
            if capacity > max_slack:
                dp[capacity] = dp[capacity + item_time]
            elif capacity <= first_item_cap:
                dp[capacity] = dp[capacity] or dp[capacity + item_time]

        for capacity in range(upper_limit, X + 1):
            dp[capacity] = False

        if not any(dp):
            return i

    return n


text:
Q: How to map factors and their relative importance in ArcGIS 10.1 for Desktop? I want to know how I can calculate a map from a set of factors (in the form of raster layers) and Their relative importance for example:
slope 20%
lithology 10%
.
.
.

A: This type of geographic analysis can be best best approached imo with map algebra (since you are on ArcGIS). I would also look for the Weighted Overlay GP tool that I think would suit you nicely. It can help overlay analysis layers to solve multi-criteria analysis problems (in your case I guess it is site selection).


text:
Q: IE8 Compatibility Mode not working - debugging I am building a responsive infographic using media queries and respond.js.
Everything is working fine until I get down to IE8 with compatibility mode turned on and for some reason my navigation disappears and it seems like some media queries have stopped working.
Does anyone have a good way to debug IE8 while using browser stack - for some reason firebug lite is saying I don't have any styling on this content.


text:
Q: Selecting tuples with one certain entry (but not another certain entry) in join table Given the following data definition:
create table vikings(
  name varchar(256));

create table countries(
  name varchar(256));

create table homes(
  viking varchar(256),
  country varchar(256));

INSERT INTO vikings VALUES ('Rollo');
INSERT INTO vikings VALUES ('Floki');
INSERT INTO vikings VALUES ('Egill');
INSERT INTO vikings VALUES ('Eirikr');

INSERT INTO countries VALUES ('Iceland');
INSERT INTO countries VALUES ('Norway');
INSERT INTO countries VALUES ('Sweden');
INSERT INTO countries VALUES ('Faroes');

INSERT INTO homes VALUES ('Rollo', 'Norway');
INSERT INTO homes VALUES ('Floki', 'Norway');
INSERT INTO homes VALUES ('Floki', 'Sweden');
INSERT INTO homes VALUES ('Egill', 'Iceland');
INSERT INTO homes VALUES ('Egill', 'Sweden');
INSERT INTO homes VALUES ('Eirikr', 'Iceland');
INSERT INTO homes VALUES ('Eirikr', 'Faroes');

How would I phrase the following query in SQL?
"Give me all of the vikings that have homes in Norway or Iceland, but not Sweden or the Faroes"
I've set up a SQLFiddle where this can be played with here: http://sqlfiddle.com/#!2/aea39b/2

A: What you want is basically a set difference. Show all members of the set of vikings that have houses in Norway or Iceland, and subtract the set of vikings that have houses in either Sweden of Faroes.
Your SQL Fiddle was set up to use MySQL which I believe doesn't support the exceptoperator, but normally any of these queries should give the same result:
select viking from homes where country in ('Norway', 'Iceland')
except
select viking from homes where country in ('Sweden', 'Faroes')

select viking from homes
where country in ('Norway', 'Iceland')
and viking not in (
    select viking from homes where country in ('Sweden', 'Faroes')
    )

Both queries will get Rolloas the single match.


text:
Q: Shortest length of line segment that bisects triangle in two equal area A segment of a line $PQ$ with its extremities on $AB$ and $AC$ bisects a triangle $ABC$ with sides $a,b,c$ into two equal areas, then find the shortest length of the segment $PQ$.
I was looking for small hint as how to approach this question? I am not able to initiate.

A: Let $AP=:p\geq0$, $AQ=:q\geq0$. Then we have to mnimize
$$f(p,q):=p^2+q^2-2pq\cos\alpha$$
under a condition of the form $g(p,q):=pq-C=0$ for some $C>0$. As $p\to0+$ enforces $q\to \infty$ and therefore $f(p,q)\to \infty$, and vice versa, it follows that the minimum of $f$ is taken for certain $p>0$, $q>0$ found by using Lagrange's method.
We therefore have to set up the auxiliary function
$$\Phi(p,q,\lambda):=f(p,q)-2\lambda g(p,q)$$ and solve the system
$$\eqalign{\Phi_p&=2p-2q\cos\alpha-2\lambda q=0 \cr
\Phi_q&=2q-2p\cos\alpha-2\lambda p=0 \cr}\tag{1}$$
together with $g(p,q)=0$ for $p$ and $q$. Now $(1)$ implies
$$p=(\lambda+\cos\alpha)q\quad\wedge\quad q=(\lambda+\cos\alpha)p\ ,$$
hence $p=q$.
It follows that you have to choose $p=q$ such that the cut off triangle just has half the area of the original triangle, i.e.,
$$p=q=\sqrt{{|AB|\>|AC|\over2}}\ .$$

A: Hint: Consider the mid point theorem of a triangle slightly tweaked. Instead of the midpoint (this gives the ratio of the new small triangle $\frac{1}{4}$ times the original triangle), find the ratio at which you need the parallel(why parallel?) line to cut the sides $AB$ and $AC$.


text:
Q: How to handle Tap's Event on Google Maps in SwiftUI I'm new in iOS Development. I'm develop an app that have a maps inside it.
I want to know how to handle Tap gesture when the user clicks on the map.
My apps workflow is when user clicks somewhere in maps, a marker will be shown and when marker is tapped, the marker will show an overlay detail about that address.
Here is my code to show a maps
import SwiftUI
import GoogleMaps

struct GoogleMapsView: UIViewRepresentable {
    @ObservedObject var locationManager = LocationManager()
    private let zoom: Float = 15.0
    private let longitudeTest: CLLocationDegrees = 106.7587855
    private let latitudeTest: CLLocationDegrees = -6.2715794
    let marker : GMSMarker = GMSMarker()

    func makeUIView(context: Self.Context) -> GMSMapView {
        let camera = GMSCameraPosition.camera(withLatitude: latitudeTest, longitude: longitudeTest, zoom: zoom)

        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

        return mapView
    }

    func updateUIView(_ mapView: GMSMapView, context: Context) {
        marker.position = CLLocationCoordinate2D(latitude: latitudeTest, longitude: longitudeTest)
        marker.title = "hay"
        marker.snippet = "hello"
        marker.map = mapView

        mapView.animate(toLocation: CLLocationCoordinate2D(latitude: latitudeTest, longitude: longitudeTest))

    }
}

A: I found a solution for this. Just make a coordinator class and implement makeCoordinator function in UIViewRepresentable.
import SwiftUI
import GoogleMaps

struct GoogleMapsView: UIViewRepresentable {
    @Binding var streetLocation: String
    @Binding var isFocused: Bool
    @Binding var requestSearch: Bool
    @Binding var searchAddress: String
    @State var longitudeTest: Double = 106.7587855
    @State var latitudeTest: Double = -6.2715794
    @ObservedObject var locationManager = LocationManager()
    private let zoom: Float = 15.0

    @State var selectedMarker: GMSMarker? = GMSMarker()

    func makeCoordinator() -> MapCoordinator {
        return MapCoordinator(
            parent: self,
            marker: $selectedMarker,
            latitude: $latitudeTest,
            longitude: $longitudeTest)
    }

    func makeUIView(context: Self.Context) -> GMSMapView {
        let camera = GMSCameraPosition.camera(withLatitude: latitudeTest, longitude: longitudeTest, zoom: zoom)

        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        mapView.delegate = context.coordinator

        selectedMarker!.position = CLLocationCoordinate2D(latitude: latitudeTest, longitude: longitudeTest)
        selectedMarker!.title = "Address"
        selectedMarker!.snippet = ""
        selectedMarker!.map = mapView

        return mapView
    }

    func updateUIView(_ mapView: GMSMapView, context: Context) {
        //        let camera = GMSCameraPosition.camera(withLatitude: locationManager.latitude, longitude: locationManager.longitude, zoom: zoom)
        //        mapView.camera = camera
        selectedMarker!.position = CLLocationCoordinate2D(latitude: latitudeTest, longitude: longitudeTest)
        selectedMarker!.snippet = streetLocation

        mapView.animate(toLocation: CLLocationCoordinate2D(latitude: latitudeTest, longitude: longitudeTest))
        getAddress(latitude: latitudeTest, longitude: longitudeTest)

        if isFocused {
            mapView.animate(toLocation: CLLocationCoordinate2D(latitude: latitudeTest, longitude: longitudeTest))
        }

        if requestSearch {
            DispatchQueue.main.async {
                getLatLongFromAddress(address: searchAddress) { (result) in
                    if result {
                        selectedMarker!.position = CLLocationCoordinate2D(latitude: latitudeTest, longitude: longitudeTest)
                        selectedMarker!.snippet = streetLocation
                        mapView.animate(toLocation: CLLocationCoordinate2D(latitude: latitudeTest, longitude: longitudeTest))
                    } else {
                        print("no location found")
                    }
                }
            }
        }
    }

    func getAddress(latitude: Double, longitude: Double){

        let geocoder = GMSGeocoder()
        let coordinate = CLLocationCoordinate2DMake(Double(latitude), Double(longitude))

        geocoder.reverseGeocodeCoordinate(coordinate) { response , error in
            if let address = response?.firstResult() {
                streetLocation = address.lines![0]
            }
        }
    }

    func getLatLongFromAddress(address: String, completion: @escaping((Bool) -> ())) {
        let geoCoder = CLGeocoder()
        geoCoder.geocodeAddressString(address) {
            placemarks, error in

            if placemarks != nil {
                let placemark = placemarks?.first
                latitudeTest = (placemark?.location?.coordinate.latitude)!
                longitudeTest = (placemark?.location?.coordinate.longitude)!
                completion(true)
                // Use your location
            } else {
                print("no location found")
                completion(false)
            }
        }
    }

    func searchAddress(latitude: Double, longitude: Double){

        let geocoder = GMSGeocoder()
        let coordinate = CLLocationCoordinate2DMake(Double(latitude), Double(longitude))

        geocoder.reverseGeocodeCoordinate(coordinate) { response , error in
            if let address = response?.firstResult() {
                streetLocation = address.lines![0]
            }
        }
    }
}

class MapCoordinator: NSObject, GMSMapViewDelegate {
    // 1.
    let parent: GoogleMapsView       // access to owner view members,
    @Binding var selectedMarker: GMSMarker?
    @Binding var latitude: Double
    @Binding var longitude: Double

    init(parent: GoogleMapsView, marker: Binding<GMSMarker?>, latitude: Binding<Double>, longitude: Binding<Double>) {
        self.parent = parent
        _selectedMarker = marker
        _latitude = latitude
        _longitude = longitude

        print("init called")
    }

    deinit {
        print("deinit: MapCoordinator")
    }

    //    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    //
    //        print("A marker has been touched
    //        return true
    //
    //    }

    func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
        print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
        longitude = coordinate.longitude
        latitude = coordinate.latitude
    }

}


text:
Q: Plot a step function using initial and final x values as x axis and V as y axis I have a txt file set up as follows:
x0              x1              V
0              0.11            1.77
0.11           0.143           1.48
0.143          1               1.35

and I want to make a stepfunction plot where x axis is values from x0 to x1 and y axis is V.
Here is my attempt:
#!/bin/env/python
import numpy as np
import matplotlib.pyplot as plt
import csv

x=[]
y=[]

with open('voltage.txt','r') as csvfile:
    points = csv.reader(csvfile, delimiter=',')
    next(points)
    for row in points:
        x.append(float(row[0]))
        y.append(float(row[1]))
allpoints=np.loadtxt('voltage.txt',delimiter=',')
plt.step(x,y)
plt.show()

but it does not generate a step function plot that accounts two x values.

A: fake file i/o, then ravel and repeat slices for x, y
from io import StringIO   # StringIO behaves like a file object
from matplotlib import pyplot as plt

txt = '''x0              x1              V
0              0.11            1.77
0.11           0.143           1.48
0.143          1               1.35'''

dary = np.loadtxt(StringIO(txt), skiprows=1)

print(dary)

[[0.    0.11  1.77 ]
 [0.11  0.143 1.48 ]
 [0.143 1.    1.35 ]]

plt.step(np.ravel(dary[:,:2]), np.repeat(dary[:,2], 2))


text:
Q: Creating unnecessary string objects This is a bit of Java String 101.  I came across this recently in some existing code.  My initial reaction is that this is redundant
car.setDetails(new String(someStringBufferObj.toString));

In my opinion even this would be redundant...
car.setDetails(new String(someOtherStringObj));

because String is immutable so there is never a risk that the car details would be changed accidentally (by changing someOtherStringObj) in a later line of code
Are am I wrong?

A: The first snippet above looks unnecessary. However the second may be necessary. Consider the following.
The constructor String(String) is useful since it'll take a copy of the underlying character array of the original string.
Why is this useful ? You have to understand that a string object has a character array underlying it, and getting a substring() of an existing string actually uses that original character array. This is a flyweight pattern. Consider the following
String s = longstring.substring(2,4);

The string s points to the character array underlying longstring (somewhat unintuitively). If you want to bin longstring (using garbage collection) the underlying character array won't be binned since s still references it, and you end up consuming a potentially huge amount of memory for a 2 character string.
The String(String) constructor resolves this by creating a new character array from that referenced by the string being used to construct from. When the original string is removed via garbage collection its character array won't be referenced by the substring() result and hence that will be removed too.
Note that this behaviour has changed very recently in Java (release 7u4, I think) and strings don't support the above mode of operation anymore.

A: You're absolutely right Rob, there's no need to new up a String in this instance.  Just providing a call to someStringBufferObj.toString() should be sufficient!


text:
Q: WSL 2 cannot see NVIDIA GPU drivers I have Windows 10 along with Ubuntu 20.04.01 GNU/Linux 5.10.16.3-microsoft-standard-WSL2 x86_64 installed (latest for WSL2 - please see edits below- this has changed). I'm a Windows Insider user and my Win10 distribution is Dev 21376.1 (as required for the NVIDIA drivers to be recognized in WSL2 - please see the documentation in the link below).
My GPU is an NVIDIA Quadro RTX 4000 with the latest driver: 470.14 (latest - please see edits below - this has changed).
I have installed the Cuda-toolkit version 11.0.3-1 (latest) inside WSL2.
However, despite following the NVIDIA in WSL2 instructions, I can't say for sure that my NVIDIA card is being recognised by Ubuntu instructions in WSL2. For example, my distribution of Gromacs 2021.2 says it can't see a GPU.
Also, when I execute nvidia-smi in WSL2 I get:
ubuntu@DESKTOP-L2JG9M2:~$ nvidia-smi NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.

I have been following these instructions: https://docs.nvidia.com/cuda/wsl-user-guide/index.html#installing-nvidia-drivers
I'm really not sure where to go from here. How do I get WSL2 to recognise my Windows 10 NVIDIA driver (do not install a Linux display driver in WSL2, see the documentation in the link) and how do I know it works?
I have just finished installing Docker and NVIDIA docker etc as per the instruction. I'm not sure what the next step is. I still can't see nvidia drivers in WSL2 via nvidia-smi.
edit #1
wsl cat /proc/version
Linux version 5.10.16.3-microsoft-standard-WSL2 (oe-user@oe-host) (x86_64-msft-linux-gcc (GCC) 9.3.0, GNU ld (GNU Binutils) 2.34.0.20200220) #1 SMP Fri Apr 2 22:23:49 UTC 2021

edit #2
I followed the link provided in the comments below and adjust various packages and libraries according to a work around:
apt-get install nvidia-docker2:amd64=2.5.0-1 \
           libnvidia-container-tools:amd64=1.3.3-1 \
           nvidia-container-runtime:amd64=3.4.2-1 \
           libnvidia-container1:amd64=1.3.3-1 \
           nvidia-container-toolkit:amd64=1.4.2-1

Unfortunately, nvidia-smi still complains that a GPU is not present. I would assume this is nvidia driver related and has nothing to do with nvidia-docker or docker?
In essence, I just don't know how to get software installed in WSL to recognize my GPU despite following all the steps. I have the same card working on a neighboring pure Ubuntu machine without a problem. Also, the software I am trying to run (Gromacs), does not require anything to do with dockers or virtual environments etc. I don't want any of that, it's causing me and my system to drown in a sea of different versions etc. Here is a version update:

*

*Linux DESKTOP-L2JG9M2 5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

*NVIDIA Quadro RTX 4000 - Version 461.55 (I downgraded as recommended)
As for my docker version (do I even need this?)
Client: Docker Engine - Community
 Version:           20.10.6
 API version:       1.41
 Go version:        go1.13.15
 Git commit:        370c289
 Built:             Fri Apr  9 22:47:17 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.6
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       8728dd2
  Built:            Fri Apr  9 22:45:28 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.4
  GitCommit:        05f951a3781f4f2c1911b05e61c160e9c30eaa8e
 runc:
  Version:          1.0.0-rc93
  GitCommit:        12644e614e25b05da6fd08a38ffa0cfe1903fdec
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0


text:
Q: Stopped Process but heap is still changing I have stopped a process by tracing it with the ptrace() syscall. Which in effect sends a kill -sigstop <pid> to the process.
Now I inspect the [heap] region, which I got from /proc/<pid>/maps
But Reading out certain addresses in the heap memory range returns different values!
ptrace(PEEKDATA*, <pid>, <addr>, null) => 33
ptrace(PEEKDATA*, <pid>, <addr>, null) => 34
ptrace(PEEKDATA*, <pid>, <addr>, null) => 34

The values increase by one over time (not repeated calls) until the byte overflows at 63 and starts at 0 again!
I did a sanity test and read out the values directly from /proc/<pid>/mem
which returns the same value. It also was increasing over time.
More background:
I'm ptrace()ing a game, called Rogue Legacy, whose heap is about 200 Million addresses in size. The process hierarchie of the game looks like this:

*

*SteamChildMonit

*

*RogueLegacy

*

*RogueLegacy.bin  // <- im tracing this process, which stops the window animation and music

UPDATE: ptrace attaches to individual threads. It takes a pid as argument, but a pid can be both a process or thread. I was under the assumption that it is always a process, only now this inaccurate model broke for me. In my example, then, "RogueLegacy.bin" is just a traced thread and there is another thread, which is not stopped, who is causing the heap to change.
Multiple threads sharing the heap as a common resource. This also means that
we have to be careful with peekdata in mutlithreaded applications, as the data under scrutiny is subject to change through the sovereign of other running threads.

A: I think I narrowed it down to a solution:
Given a multithreaded application with the threads, who all share the same heap address-space

*

*foo-thread

*bar-thread

*qux-thread
And the process running our ptrace calls (in this case a single threaded process):

*tracer-thread
If we ptrace(PTRACE_ATTACH ..) to foo-thread, we make tracer-thread another parent of
foo-thread. In accordance with ptrace' documentation, a SIGSTOP is send, that stops
the thread. But this SIGSTOP send by tracer-thread only stops foo-thread not any
other thread!
But if we send a SIGSTOP to foo-thread directly, i.e. not through the means of the
attach ptrace call, then the whole process, and its threads foo- and bar-thread are
stopped.
This is an instance where the peculiarity of ptrace becoming a makeshift foster home
for threads has to be taken into account.


text:
Q: How do I use Hardware accelerated video/H.264 decoding with directx 11 and windows 7? I've been researching all day and not gotten very far. I'm on windows 7, using directx 11. (My final output is to be a frame of video onto a DX11 texture)
I want to decode some very large H.264 video files, and the CPU (using libav) doesn't cut it.
I've looked at the hwaccel capabilities of libav using DXVA2, but hit a road block when I need to create a IDirectXVideoDecoder, which can only be created with a D3D9 interface. (which I don't have using DX11)
Whenever I've looked up DXVA documentation, it doesn't reference DX11, was this removed in DX10 or 11? (Can't find any confirmation of this, nor anywhere that says DXVA2 is redundant, possibly that it's been superceeded by DXVA-HD?)
Then I've looked into the media foundation SDK as that looks like what I'm supposed to use for DX11... But none of the types exist in my headers (The docs say to just include <d3d11.h>, but this yields nothing). They also specify a minimum of windows 8 to use it.
I believe to use MF I need the windows 8 SDK, which now includes all the directx libs/headers.
So this leaves a gap with windows 7... Is it possible to get hardware accelerated video decoding? and if so, which API am I supposed to be using?
Edit: As another follow up, my MediaFoundation (and AVF, android, magic leap, etc etc) implementation is in my open source project
https://github.com/NewChromantics/PopH264
Edit2: But I don't know if it supports win7 :)

A: D3D11 features a video api which is basically DXVA2 with a slightly altered interface above.
You need a good understand of h.264 bitstreams to proceed (really!). i.e. make sure you have a h.264 parser at hand to extract fields of the SPS and PPS structures and all slices of an encoded frame.
1) Obtain ID3D11VideoDevice instance from your ID3D11Device, and ID3D11VideoContext from your immediate D3D11 device context
NOTE: On Win7, you have to create your device with feature level 9_3 to get video support! (In Win8 it just works)
2) Create a ID3D11VideoDecoder instance for h.264
Use ID3D11VideoDevice::GetVideoDecoderProfileCount, GetVideoDecoderProfile, CheckVideoDecodeRFormat...
to iterate through all supported profiles, and find one with GUID D3D11_DECODER_PROFILE_H264_VLD_NOFGT
for h264 without filmgrain. As OutputFormat your best bet is DXGI_FORMAT_NV12.
3) Decoding of the individual frames see Supporting Direct3D 11 Video Decoding in Media Foundation:

*

*ID3D11VideoContext::DecoderBeginFrame( decoder, outputView -> decoded frame texture )

*Fill buffers:

*

*D3D11_VIDEO_DECODER_BUFFER_PICTURE_PARAMETERS

*D3D11_VIDEO_DECODER_BUFFER_INVERSE_QUANTIZATION_MATRIX

*D3D11_VIDEO_DECODER_BUFFER_BITSTREAM

*D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL

The buffers are filled with the corresponding DXVA2 structures (see dxva2.h)
The full DXVA2 spec is here, you'll need it to map the h.264 sps/pps fields accordingly.
See:

*

*About DXVA 2.0

*https://software.intel.com/sites/default/files/m/b/4/7/DXVA_H264.pdf
Then:

*

*ID3D11VideoContext::SubmitBuffers to commit all filled buffers

*ID3D11VideoContext::DecoderEndFrame to finish the current frame

3) D3D11_VIDEO_DECODER_BUFFER_PICTURE_PARAMETERS buffer also contains info on all references frames/surface
- you need to manage them yourself, i.e. make sure the surfaces/textures are available to the GPU!
It's quite complicated, check ffmpeg and Media Player Classic, they both have DXVA2 (though not via DX11) support.
4) Convert from NV12 to RGB(A), some GPUs (D3D11 feature levels) allow to use NV12 as shader input, some don't. In case it's not possible to use NV12 directly, have a look at the D3D11VideoProcessor interfaces which feature NV12/YUV420->RGB conversion for all GPUs with D3D11 support.
The conversion could be performed in code like this:
// Setup ID3D11Video*
ID3D11VideoProcessor * d3dVideoProc = ...;
ID3D11VideoDevice    * d3dVideoDevice = ...;
ID3D11VideoProcessorEnumerator * d3dVideoProcEnum = ...;

ID3D11Texture2D * srcTextureNV12Fmt = ...;
ID3D11Texture2D * dstTextureRGBFmt = ...;

// Use Video Processor

// Create views for VideoProc In/Output
ID3D11VideoProcessorInputView * videoProcInputView;
ID3D11VideoProcessorOutputView * videoProcOutputView;

{

    D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC inputViewDesc = { 0 };
    inputViewDesc.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D;
    inputViewDesc.Texture2D.ArraySlice = arraySliceIdx;
    inputViewDesc.Texture2D.MipSlice = 0;
    hr = d3dVideoDevice->CreateVideoProcessorInputView(srcTextureNV12Fmt, d3dVideoProcEnum, &inputViewDesc, &videoProcInputView);
}

{
    D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC outputViewDesc = { D3D11_VPOV_DIMENSION_TEXTURE2D };
    outputViewDesc.Texture2D.MipSlice = 0;
    hr = d3dVideoDevice->CreateVideoProcessorOutputView(dstTextureRGBFmt, d3dVideoProcEnum, &outputViewDesc, &videoProcOutputView);
}

// Setup streams
D3D11_VIDEO_PROCESSOR_STREAM streams = { 0 };
streams.Enable = TRUE;
streams.pInputSurface = videoProcInputView.get();

RECT srcRect = { /* source rectangle in pixels*/ };
RECT dstRect = { /* destination rectangle in pixels*/ };

// Perform VideoProc Blit Operation (with color conversion)
hr = videoCtx_->VideoProcessorBlt(d3dVideoProc, videoProcOutputView.get(), 0, 1, &streams);

A: As a follow up, I am currently using MediaFoundation with windows 7,8 and 10, with directx(or just Windows SDK in the case of 8+)
It supports far fewer formats (or rather, resolutions/profile levels), and currently I'm not exactly sure if it's using hardware acceleration or not...
But this API is compatible, which was the original query

A:
How do I use Hardware accelerated video/H.264 decoding with directx 11 and windows 7?

You can't.
ID3D11VideoDevice is only avalaible for windows 8 ID3D11VideoDevice.
ID3D11VideoDecoder is only avalaible for windows 8 ID3D11VideoDecoder.
On windows 7, you just can use directx 9 for Hardware accelerated video/H.264. Thanks Microsoft. The good new, IDirect3D9Ex works... yeah...
The other good news, GPU decoding performance is very good using DirectX9 on Windows 7.
Here is a source code for windows 7 and DirectX 9 : mofo7777, under H264Dxva2Decoder project.


text:
Q: Which django apps are directly usable or easily adaptable for django-nonrel? Is there a list of django apps that can be used unaltered in django-nonrel or a list of django apps that can be easily adapted to be used in django-nonrel?

A: I used django-dbindexer from the same guys that made django-nonrel to use django-registration without modifications.

A: I haven't found such a list.
For the record, I've gotten tastypie working with tiny modifications
http://eatdev.tumblr.com/post/12076483835/tastypie-on-django-nonrel-on-app-engine
django-merchant seems to be working as well.
https://github.com/agiliq/merchant
Essentially simple apps that don't require JOINs in their DB queries will most likely work.  If they use ManyToManyRelations, they're probably not going to work.

A: I have used 'contenttypes, auth and sessions' from 'django.contrib' without any modification, the app code wont cause any problems. However any query using JOINs result in query errors, so you need to write your queries with this limitation in mind.
Did you have a particular app in mind?


text:
Q: Find how many (googlemap) polygons near x distance of a point I'm working on a MYSQL/PHP system where I have the following:
-- a set of latitude, longitude in the form of (lat,lng) stored as text format : (lat1,lng1)#(lat2,lng2)#(lat3,lng3) etc. which is basically a polygon drawn over a googlemap instance stored in the database.
-- a table which stores in a field - a point's coordinates P(plat,plng) which is basically a point where a device is stationed
I need to figure out how many polygons from the first table are within a distance of X kilometers from the point P essentially using MYSQL.
I have come across quite a few Google Map libraries regarding this already, but I intend to resolve this by the quickest method possible - which I assume is via a MYSQL query.
Can anyone please please shed some light regarding this?

I've so far consulted a few examples on geospatial querying - and come up with this :
    SELECT user_id, latitude, longitude,
      GeomFromText( "POINT(CONCAT_WS(' ',latitude,longitude))" ) AS point,
      Contains( GeomFromText( 'POLYGON(-26.167918065075458 28.10680389404297,
    - 26.187020810321858 28.091354370117188, -26.199805575765794 28.125,-26.181937320958628 28.150405883789062, -26.160676690299308 28.13220977783203, -26.167918065075458 28.10680389404297)' ) ,
      GEOMFromText( "POINT(CONCAT_WS(' ',latitude,longitude))" ) )
   FROM user_location

But the problem is it shows a record with lat: -26.136230, long: 28.338850 as well which is way off the polygon's boundaries. Can anyone please guide?

A: I'm not sure if you want to calculate the distance to the nearest corner of the polygon, boundary of the polygon or some notional central point of it. Either way I think the mathmetical solution to this is to use Pythagoras' theorem to work out the proximity of points.
If you have lat1,lng1 and lat2,lng2 expressed in metres I believe that the distance between them is:
SQRT(POW(ABS(lat1 - lat2),2) + POW(ABS(lng1 - lng2),2))

Using an algorithm similar to this you need to decide whether you want to compare your known lat/lng to a single central point of the polygon or to the points of its corners (three times the work!).
MySQL does have a geospatial extension which could be worth looking at. Unfortunately I don't have experience of it.

A: Okay, did this - and it works - might help someone:
SELECT user_id,latitude,longitude,
   Contains(
          PolyFromText( 'POLYGON((-26.167918065075458 28.10680389404297, -26.187020810321858 28.091354370117188, -26.199805575765794 28.125,-26.181937320958628  28.150405883789062, -26.160676690299308 28.13220977783203, -26.167918065075458 28.10680389404297))' ),
          PointFromText(concat("POINT(",latitude," ",longitude,")"))
   ) as contains
FROM user_location

=====
Although I agree on expert's views that PostGIS could be a better option.


text:
Q: Flickering sprites in Unity 2D when moving character I have some sprites placed in the game whose lines flicker. I have a video linked below as to what is happening. Notice the houses (mostly windows) that flicker when moving.
Note there are some buildings that aren't flickering. I am using a Virtual cam using Cinemachine with some lerp but that's all I can think of that could be causing this.
I can post more info if requested.
The video: https://youtu.be/7cad1Yk0-Cs
Thanks

A: Try changing the anti-aliasing, or turn it off.
Also try experimenting with the compression and settings of your atlases.


text:
Q: Spurious tokens don't raise typescript errors Why doesn't this raise a syntax error?
class foo {
    public x = 42;    comment
}

or even stranger
class foo2 {
    comment_wtf
    extra_weird
}

A: These are properties of type any. The semicolon is automatically inserted at the end of the line.

A: As mentioned by rightfold these are just member properties of the class you are declaring. If you use an undeclared member you will get an error as shown below:
class Foo {
    comment_wtf
    extra_weird
}

var foo:Foo;
foo.comment_wtf = 'allowed';
foo.notThere = 'error'; // ERROR


text:
Q: gcloud ingress https redirect define through a helm chart Now that http to https redirect is implemented in gcloud I am wondering how to define this programmatically in my helm chart template that defines my ingress. See
google issuetracker for the google issue.
Here is one of the tutorials on how to set this up in the console setting-up-traffic-management. This is straight forward but if it can't be scripted it is not cool. I use helm and I have set up a working ingress with google managed certificate like this:

templates/ingress-service.yaml

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: managed-ingress
  annotations:
    kubernetes.io/ingress.global-static-ip-name: {{ .Values.static_ip }}
    networking.gke.io/managed-certificates: {{ .Values.managed-certificates }}
spec:
  backend:
    serviceName: {{ .Values.name }}
    servicePort: {{ .Values.backend.port }}

That works nicely and I have both http and https access to my service. How do I configure a https redirect rule directly into this ingress definition?
If I simply set up another ingress with the tutorial setting-up-traffic-management, I get a 'external ip conflict' because I already have the aforementioned ingress service set up through the helm release.

A: Standard ingress controller in GKE does not support http to https redirection. You can install NGINX Ingress controller instead.
There is a similar thread


text:
Q: GPT2 simple returned string showing as none type Working on a reddit bot that uses GPT2 to generate responses based on a fine tuned model. Getting issues when trying to prepare the generated response into a reddit post. The generated text is returning as None Type and I'm unable to process or view the generated text
text = str(comments["text"])

x = gpt2.generate(sess,prefix=text,temperature=0.8,length=100)

print(type(x))

print(x)

returns:
<class 'NoneType'>
None

Why can't I treat 'x' as as string variable (substracting and adding substrings, due to being NoneType). Not using any functions, rest of the script previous is just scraping the top comment from the top post in a subreddit. Any feedback appreciated


text:
Q: Android sdk file explorer showing nothing I am using the Android AVD SDK File Explorer view, I have the emuator running as well, but the view isn't showing me any file listings.
This usually is not a problem, what would cause this?

A: In the devices view, ensure that the device/emulator you are using for testing is selected.


text:
Q: VBA to remove numbers from start of string/cell I hope you can help.
I have a piece of code that is currently removing all the text from the cells in Column G. What I need is for this code to instead of removing the text I would like it to remove the numbers, and I only want it to remove the numbers at the beginning of the string/cell the rest of the data I would like to remain the same.
I have attached a picture PIC.1 for betting understanding.
PIC1

The code I currently have and I hope can be amended is below and as always any and all help is greatly appreciated.
CODE
Sub RemoveNonDigits()
  Dim X As Long, Z As Long, LastRow As Long, CellVal As String
  Const StartRow As Long = 1
  Const DataColumn As String = "G"
  Application.ScreenUpdating = False
  LastRow = Cells(Rows.Count, DataColumn).End(xlUp).Row
  For X = StartRow To LastRow
    CellVal = Cells(X, DataColumn)
    For Z = 1 To Len(CellVal)
      If Mid(CellVal, Z, 1) Like "[!0-9]" Then Mid(CellVal, Z, 1) = " "
    Next
    With Cells(X, DataColumn)
      .NumberFormat = "@"
      .Value = Replace(CellVal, " ", "")
    End With
  Next
  Application.ScreenUpdating = True
End Sub

A: CellVal = LTrimDigits(Cells(X, DataColumn))

With this fairly efficient:
Public Function LTrimDigits(value As String) As String
    Dim i As Long
    For i = 1 To Len(value) '//loop each char
        Select Case Mid$(value, i, 1) '//examine current char
            Case "0" To "9" '//permitted chars
            Case Else: Exit For '// i is the cut off point
        End Select
    Next
    LTrimDigits = Mid$(value, i) '//strip lead
End Function

A: See the modified code below:
Sub RemoveNonDigits()
  Dim X As Long, Z As Long, LastRow As Long, CellVal As String
  Const StartRow As Long = 1
  Const DataColumn As String = "G"
  Application.ScreenUpdating = False
  LastRow = Cells(Rows.Count, DataColumn).End(xlUp).Row
  For X = StartRow To LastRow
    CellVal = Cells(X, DataColumn)
    While IsNumeric(Left(CellVal, 1))   ' Here
      CellVal = Mid(CellVal, 2)         ' all digits at the start
    Wend                                ' are removed
    Cells(X, DataColumn) = Trim(CellVal)
  Next
  Application.ScreenUpdating = True
End Sub

That is, while the starting char in CellVal is a digit, get the substring starting with the second char, and go on until no match.

A: This function will strip leading digits and spaces from a string
Function RemoveLeadingDigits(str As String) As String

    Dim i As Long
    Dim chr As String
    ' Loop through string
    For i = 1 To Len(str)
        ' Get character i
        chr = Mid(str, i, 1)
        ' Keep looping until character is not a number or space
        If Not IsNumeric(chr) And Not chr = " " Then
            ' If it is a number or space, strip checked characters
            ' from str (because they'll be numeric or space)
            str = Right(str, Len(str) - i + 1)
            ' Stop looping as non-numeric characters encountered
            Exit For
        End If
    Next i

    ' Return the value of str
    RemoveLeadingDigits = str

End Function

You can call it from your code by
Sub RemoveNonDigits()
    Dim X As Long, LastRow As Long, CellVal As String
    Const StartRow As Long = 1
    Const DataColumn As String = "G"
    Application.ScreenUpdating = False
    LastRow = Cells(Rows.Count, DataColumn).End(xlUp).Row
    For X = StartRow To LastRow
        CellVal = Cells(X, DataColumn).Value
        ' ----------------------------------------
        CellVal = RemoveLeadingDigits(CellVal)
        ' ----------------------------------------
    Next
    Application.ScreenUpdating = True
End Sub

A note on your code though:
You should really fully qualify your cells. For instance, wrap the whole looping section in With ThisWorkbook.Sheets("YourSheet") and then accessing cells using .Cells(row, col) rather than just Cells(row, col).

A: A bit hacky shorter alternative (assuming all values start with integer)
For Each cell in Range([G7], [G7].End(xlDown))

    cell.Value2 = Trim(Mid(cell, Len(Str(Val(cell)))))

Next

A: I think a simple change like this:
For X = StartRow To LastRow
    Cells(X, DataColumn).Formular1c1 = Application.Trim(Replace(Cells(X, DataColumn).Text, Val(Cells(X, DataColumn).Text), ""))
Next X

will solve your problem...


text:
Q: JSON not parsing using .getJSON having an issue with simple JSON parsing, wondering if someone could quickly spot any errors in this syntax?
function getFavs() {
    $.getJSON('http://www.example.com/scripts/test.json', function(data) {
        $('#main-content').html(data.foo);
    });
}

the JSON file is as follows:
{
 "foo": "The quick brown fox jumps over the lazy dog.",
 "bar": "ABCDEFG",
 "baz": [
     52,
     97
   ]
}

For some reason it doesn't like the 'data.foo' bit. I can use static data, but it's definitely not reading / parsing the JSON data. Not sure if it has to do with the URL I am using? (The file has been validated using JSONLint)
thanks for any clues.

A: this is solved, seemed to be running locally and calling to a live server would be cross-domain I figure. Running MAMP now and it works as should above.
thanks!

A: Things look ok, but check that the function is actually called. If you have Firebug, try to debug the code by running through it step by step. If you don't add a few alert("this code was run"); in different places (before the ajax, after the ajax and in the callback function).


text:
Q: Mass Edit Wordpress Permilinks in Mysql (Find & Replace) I am trying to edit permilinks in mysql. I ran a find and replace for the blog description which worked perfect but am coming up with an error #1064:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/%monthnum%/%day%/%postname%/','/%category%/%postname%/')' at line 1

Here is the query I'm running:
update wp_85_options set option_value = replace(option_value,'/%year%/%monthnum%/%day%/%postname%/','/%category%/%postname%/');


text:
Q: Access a field with . in name in scripted fields kibana I have a field that is getting pushed to Elastic and displayed on Kibana using Filebeat and ELK stack.
Field name is something like this: "field.name", i.e. it contains . in the name.
I created a Scripted field with the following code snippet:
if(doc['field.name.keyword'])
  return 1;
return 2;

But I always get an empty array in the result. After I create this scripted field by converting it to a number as it is of type string, I want to perform metric aggregation on it.
Does anybody have any idea how I can achieve this?


text:
Q: How do i get file_get_contents to work in wordpress Im using geoplugin.com to display content based on users location
the codex is set up like this:
$geoplugin  = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?      ip=' . $_SERVER['REMOTE_ADDR']) );

This works on my dev site but not on my live site. I tried to use wp_remote_get but couldnt get it to set up properly. Any ideas on why this would work on one site and not another?

A: It seems file_get_contents() isn't active in your server. Instead, use the wp_remote_get().
Note wp_remote_get() is among the family of WordPress HTTP API specifically used for sending GET requests.
The advantage of wp_remote_get() over file_get_contents() and other PHP stream/transport function is - The WordPress HTTP API was created to standardize a single API that handled everything with regards to HTTP as simply as possible. The HTTP API supports various PHP HTTP transports or implementations to cater for different hosting environments and configurations.
In a nutshell, if file_get_contents() isn't enabled, wp_remote_get() will use cURL if available, if not, it find and uses any available HTTP transport.

A: This is how I solved this issue   ::
   function get_client_ip_env() {
        $ipaddress = '';
        if (getenv('HTTP_CLIENT_IP'))
            $ipaddress = getenv('HTTP_CLIENT_IP');
        else if(getenv('HTTP_X_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
        else if(getenv('HTTP_X_FORWARDED'))
            $ipaddress = getenv('HTTP_X_FORWARDED');
        else if(getenv('HTTP_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_FORWARDED_FOR');
        else if(getenv('HTTP_FORWARDED'))
            $ipaddress = getenv('HTTP_FORWARDED');
        else if(getenv('REMOTE_ADDR'))
            $ipaddress = getenv('REMOTE_ADDR');
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;
    }

    $geoplugin  = maybe_unserialize( wp_remote_fopen('http://www.geoplugin.net/php.gp?ip=' . get_client_ip_env()) );