text:
Q: Notification Icons shrunk to 36x36 for xhdpi I have a drawable-xhdpi-v11 folder containing a 48x48 icon which is used in my Notification:
Notification notification = new Notification(R.drawable.ic_not_logo, null, now);

I noticed on my Galaxy Nexus running JB, the icon is shrunk to 36x36, making it blurry. Why does the documentation ask for a 48x48 if it wants a 36x36? Am I missing something? Is there a way to make my notification icons pixel perfect?
EDIT:
Here is a related post
Android status bar expects icons of size 25x25dp while guidelines recommend 32x32dp. Who is wrong?
The answers in this post do not explain why it still asks for a 48x48 sized icon and down scales it to 36x36.

A: You should provide different version of the very same resource.
Follow the guide: android design status bar

A: My final conclusion is that it is impossible to have pixel perfect Notification Icons. I experimented with providing different sized icons to the drawable-xhdpi-v11 folder and it down-scales all icons provided regardless of their size, leading to a loss in resolution and blurriness of pixel perfect icons. Pretty disappointing.

A: You should definitely stick to the 24dp value from the guidelines, but you must provide an xxhdpi res (72px) which can then be used by Android to scale to 36px without blur. Same with app icons, some tablets use the xxhdpi res for the homescreen, even though the device is xhdpi.


text:
Q: How to check if the page is loading inside facebook canvas and change the layout accordingly I'm working on creating flash games site and want to make the facebook application version of it. As the site width is bigger than canvas default width I'm trying to find the way to check if the site is loading inside facebook canvas and change the width accordingly. Please, help me to find the solution.

A: If a user accesses your site via your Facebook canvas iframe app, the request to your server will include a "signed_request" param. You can check for this param to determine if the user's inside the Facebook canvas or not.
Also note that you don't really need to do this anymore if you set the Canvas Width to Fluid:

You can set your Canvas Width to "Fixed (760px)", the default setting, which makes your app have a fixed width of 760 pixels. You can also set your width to "Fluid" which means that we set the iframe width to 100%. Your content will then be left-aligned and resize to fill the page as the user changes the width of their browser.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multivariate exponential smoothing and Kalman filter equivalence Suppose the time-series $X$ is hidden state Gaussian random walk and we observe $Y = X + e$,  where $e$ is gaussian white noise independent of $X$.
The Kalman estimator of $X$ in this case has a steady state closed form solution and corresponds to an exponential moving average smoother with constant smoothing parameter. The optimal smoothing parameter looks like $\lambda = \frac{p}{1-p}$  where $p$ is a quadratic formula of signal to noise ratio between $e$ and $\Delta{x}$. See formula for closed form (by searching 'kalman solution random walk noise').
If we have instead multiple independent observations $Y_1, Y_2,...$, i.e. independent $e_1, e_2,...$ is there a closed form solution for the optimal estimator of $X$?    What would it look like?
If the $e_1, e_2$ were independent and identically  distributed (same standard deviation), I can imagine the best estimator for $X$ is to simply average the estimators obtained treating the problem as univariate for each $Y$.
If the $e_1,e_2,...$ have different variance, then some $Y$ series should have low weightings in the overall estimator as their signal to noise ratio is poorer. Perhaps the closed form solution is linear with coefficients proportional to each $Y$ signal to noise ratio.
Is there a known closed form solution? Google seems not to be too helpful on this problem.

A: You haven't specified but if the observation noise is independent of the model noise then I think you should first combine the Y estimates with simple observation variance weighted mean as specified here:
http://en.wikipedia.org/wiki/Weighted_mean#Dealing_with_variance
after that apply kalman filter as if it is a univariate model. As a result you will have a lower observation noise hence a better estimate of x.


text:
Q: How to remove a div tag in html String in UIWebview I m extracting an html string using @"document.getElementsByClassName('entry-content')[0].innerHTML"; and i was successful in getting the html response where i m storing it in a string ,the problem is i need to remove a div named as "collections-form" on the html response from the string.could you guys help me out.below is the code.
    -(void)webViewDidFinishLoad:(UIWebView *)webView1 {
    NSLog(@"finish");
    [activity hide:YES];
    NSString *app;

    if (currentPage == 3)
    app=@"<style>table {font-size:10px;}</style>";
    else app=@"<style>table {font-size:10px;}</style>";

    NSString *temp1 = @"document.getElementsByClassName('entry-content')[0].innerHTML; " ;

    NSString *class =[webView1 stringByEvaluatingJavaScriptFromString:temp1];

    NSString *localString = [NSString stringWithFormat:@"%@%@",class,app];

    [webView1 loadHTMLString:localString baseURL:nil];

    webView.hidden = NO;
    webView.delegate =nil;
}

A: One solution is call js code which removes that element after content is loaded.
NSString *jsCommand = [NSString stringWithFormat:
         @"var element = document.getElementById('%@'); element.parentElement.removeChild(element);",
         @"id2",
];
[webView stringByEvaluatingJavaScriptFromString:jsCommand]

And This is another way if you wish to use JavaScript
How to remove tag from html with JavaScript in iphone UIWebView


text:
Q: Capturing stdout from subprocess after sending SIGINT I have a dtrace snippet run via python script and the dtrace snippet is such that it generates data when CTRL-C is issued to it. So I had a signal_handler defined in the python script to catch CTRL-C from user and relay this to the dtrace invocation done via subprocess.Popen but I am unable to get any output in my log file. Here is the script:
Proc = []
signal_posted = False

def signal_handler(sig, frame):
    print("Got CTRL-C!")
    global signal_posted
    signal_posted = True
    global Proc
    Proc.send_signal(signal.SIGINT) #Signal posting from handler

def execute_hotkernel():
    #
    # Generate the .out output file
    #
    fileout = "hotkernel.out"
    fileo = open(fileout, "w+")

    global Proc
    Proc = subprocess.Popen(['/usr/sbin/dtrace', '-n', dtrace_script], stdout = fileo)
    while Proc.poll() is None:
        time.sleep(0.5)

def main():
    signal.signal(signal.SIGINT, signal_handler)        # Change our signal handler
    execute_hotkernel()

if __name__ == '__main__':
    main()

Since I have a file hotkernel.out set in subprocess.Popen command for stdout I was expecting the output from dtrace to be redirected to hotkernel.out on doing a CTRL-C but it is empty. What is missing here?

A: I have a similar issue.
In my case, it's a shell script that runs until you hit Control-C, and then prints out summary information. When I run this using subprocess.Popen, whether using a PIPE or a file object for stdout, I either don't get the information (with a file object) or it hangs when I try to run stdout.readline().
I finally tried running the subprocess from the interpreter and discovered I could get the last line of output after the SIGINT with a PIPE if I call stdout.readline() (where it hangs) and hit Control-C (in the interpreter), and then call stdout.readline() again.
I do not know how to emulate this in script, for a file output or for a PIPE. I did not try the file output in the interpreter.
EDIT:
I finally got back to this and determined, it's actually pretty easy to emulate outside of python and really has nothing to do with python.
/some_cmd_that_ends_on_sigint
(enter control-c)
*data from stdout in event handler*

Works
/some_cmd_that_ends_on_sigint | tee some.log
(enter control-c)
*Nothing sent to stdout in event handler prints to the screen or the log*

Where's my log?
I ended up just adding a file stream in the event handler (in the some_cmd_that_ends_on_sigint source) that writes the data to a (possibly secondary) log. Works, if a bit awkward. You get the data on the screen if running without any piping, but I can also read it when piped or from python from the secondary log.


text:
Q: Adding animation in Syncfusion UWP I am using Syncfusion in UWP app to create a line chart. And I am trying to add animation such that the line extends when we add new data to the collection. Didn't find any help on documentation. The default animation draws between every two data points in it. no other animation was present. Any help is appreciated

A: Currently We don't have inbuilt support for animation when the new data point is added to the series dynamically. However, we can achieved your requirement by using CustomTemplate to the LineSeries and the storyboard has been defined in that template for animation. Please find the below code sample for reference,
MainWindow.xaml:
<chart:LineSeries ItemsSource="{Binding Collection}"
                            XBindingPath="XValue" YBindingPath="YValue"
                            >
           <chart:LineSeries.CustomTemplate>
                <DataTemplate>
                    <Canvas >
                        <Line X1="{Binding X1}" Y1="{Binding Y1}" X2="{Binding X2}"   Y2="{Binding Y2}" Loaded="Line_Loaded"  Stroke="{Binding Interior}" Name="line">
                            <Line.Resources>
                                <Storyboard x:Name="story" >
                                    <DoubleAnimation x:Name="Danimation1" EnableDependentAnimation="True" Storyboard.TargetName="line" Storyboard.TargetProperty="X2" From="{Binding X1}" To="{Binding X2 }" />
                                    <DoubleAnimation x:Name="Danimation2" EnableDependentAnimation="True" Storyboard.TargetName="line" Storyboard.TargetProperty="Y2" From="{Binding Y1}" To="{Binding Y2}" />
                                </Storyboard>
                            </Line.Resources>
                        </Line>
                    </Canvas>

                </DataTemplate>
            </chart:LineSeries.CustomTemplate>

        </chart:LineSeries>

MainWindow.cs:
private void Line_Loaded(object sender, RoutedEventArgs e)
{

        var line = sender as Line;

        Storyboard sb = line.Resources["story"] as Storyboard;
        sb.Begin();
}

We have prepared a demo sample based on your requirement and it can be downloaded from the below link,
Sample: Sample
Regards,
Durgadevi S


text:
Q: Does UIAppearance work outside of AppDelegate? I've played with UIAppearance a little bit, and it works fine. Currently I'm setting all the apperance-stuff in the AppDelegate, but now I need to do some customization after the App already started (Theming after a user logged in).
Is it possible to put the appearance-stuff outside of the AppDelegate? Of course I already tried, but it has no effect. Do I have to reload the wohle App-UI, and if so how can I do this?
Thank you!
Chris

A: If you are using xib to create your view you should do the appearance customization within the AppDelegate since customization should be performed before creating any UIControl objects. You can customize it for different view controllers/ containers  using appearanceWhenContainedIn

To customize the appearances for instances of a class contained within an instance of a container class, or instances in a hierarchy, use +appearanceWhenContainedIn: for the appropriate appearance proxy.

For example:
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTintColor:myNavBarColor];
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], [UIPopoverController class], nil] setTintColor:myPopoverNavBarColor];

Use ViewController class
 [[UIStepper appearanceWhenContainedIn:[MainViewController class], nil]setTintColor:[UIColor redColor]];
 [[UIStepper appearanceWhenContainedIn:[DetailViewController class], nil]setTintColor:[UIColor greenColor]];

If you are creating the controls programmatically, no matter customize just before creating the control
 [[UIStepper appearance]setTintColor:[UIColor redColor]];
 UIStepper *stepper = [[UIStepper alloc]init];
 [self.view addSubview: stepper];


text:
Q: Array.map() creates a new line for every element it creates I'm creating a demonstration of the concept of polyrhythms as a proof-of-concept project for my React learning. I have the following as a function right now:
  const [value, setValue] = useState("");
  const [value2, setValue2] = useState(""); // I will extrapolate out to n switches
  const beatArr = [];                       // when I have the rest of the functionality
  for (var i = 1; i <= value; i++) {        // implemented.
    beatArr.push(i);
  }
  const beats = beatArr.map((x) => <Beat key={x} identifier={x} />);

I have two components thus far; a <Switch /> (used to pull information from the DOM) and a <Beat /> (takes the switches' value and renders that many beats).
My issue as it stands right now is that using beatArr.map(...) creates a new line after every <Beat /> element, and I want it to not do that. For example with a value of 4 and three groupings of elements, right now it renders as:
1 1 1
2 2 2
3 3 3
4 4 4

While I want it to render as:
1 2 3 4
1 2 3 4
1 2 3 4

How can I refactor this into something that could make it work? Is this an issue with the .map() method? I have used CSS to add line breaks in between the groups, but the result as of now is:
1
2
3
4
1
...

Thanks in advance, you guys are great.
EDIT: Forked at current point for future-proofing this question; here is current source.

A: In your <Beat> component, if you use a  instead of
, it should work.
function Beat({ identifier }) {
return {identifier};
}

A: Simple solution is change you  element to  element in Beat component
import React from "react";

function Beat({ identifier }) {
  return {identifier};
}

export default Beat;

https://codesandbox.io/s/polyrhythm-demonstration-forked-bpgdp?file=/src/Beat.js


text:
Q: How can i make the width of a div respond to the width of a div a few parent levels above?

content

      Link 1
      Link 2
      Link 3
      Link 2
      Link 3

content

      Link 1
      Link 2
      Link 3
      Link 2
      Link 3

content

      Link 1
      Link 2
      Link 3
      Link 2
      Link 3

content

      Link 1
      Link 2
      Link 3
      Link 2
      Link 3

content

      Link 1
      Link 2
      Link 3
      Link 2
      Link 3

Hi, I'm not sure if this is possible or not, but am I able to say have a container div, with a few levels of divs nested and then somehow make the width of the most nested div react % wise to the main div?
For example with the above HTML, is there a way I could say make the "dropdown-content" class have, for example, 50% of the width of the main "navrow1" div?
How could one go about doing that?
More directly to the point its a nav bar with dropdown menus for each item, I would like to have the "dropdown-content" (the box that appears when nav item selected) to take up 50% of the entire navbar1. any width I set just goes to the parent class it currently has and needs.
also sorry if there's anything wrong with the way this is layed out I am new to this so please just tell me anything I do wrong so I can correct it.

A: idk why I didn't think of it earlier but I just set the width using the vw unit.


text:
Q: What is the preferred way to install new versions of software? I have installed Ubuntu Server 10.10 and now I want to install some software like PostgreSQL, Nginx and PHP. But what is the preferred way to get the latest stable version of the software?
E.g I tried with sudo apt-get install postgresql but that installed version 8.4 of PostgreSQL but 9.0.1 is the latest version.
I have had this issue before with NginX. The solution was then to download the sourcefiles and compile the latest version which took some time. Later a friend told me that wasn't a preferred way to install software.
Any recommendations?

A: Either you are patient and stick with what you have, or you find an official backport, or you find some unofficial backports, or you build your own package.  The details depend on the particular package.
For example, in the case of PostgreSQL, you can either wait a few more weeks until the package officially enters some Ubuntu version, at which point also official backports will appear, or in the meantime you can get unofficial packages (albeit from the same packager) at https://launchpad.net/~pitti/+archive/postgresql.
Building your own packages from scratch or installing from source is probably not recommendable for the type of rather complex software that you mention, unless you are mainly interested in learning the internals rather than using them in production.

A: The recommended way is to use the software versions your distribution provides, i.e. sudo apt-get install postgresql is correct. This might not always be the most recent version released upstream, but in most cases one doesn't really need the latest one.
If you (think you) need the very latest version of everything, you might want to use a distribution which is very fast with releasing new versions for its packages. E.g. while Ubuntu for many packages only releases new version upgrades with its half-yearly major update, Fedora more often adds new versions as updates to the current distribution incarnation. Other distributions like Gentoo give releases even faster. (However, all mentioned distribution gives security updates in a timely fashion of course.)
If you in general are happy by getting the latest versions, e.g. twice a year and only have one or two packages for which you need the latest and greatest, you can stay with Ubuntu or a similar distribution and either build the packages for which you need the latest  version from source and install e.g. to /opt or /usr/local or you can try to get pre-build packages from the development tree of your distribution.

A: If this is something that's very important to you, I'd consider switching to a more "bleeding edge" distribution; distros like Ubuntu follow a fixed release schedule, and also like to wait a bit before software has been through testing before shifting into their stable package repositories. (Of course it's much more up to date that some others, like Debian stable.)
Personally I use Arch Linux. Packages get updated to the newest release very quickly in most cases, and it's a "rolling release" distro so you can always be up to date. The counterbalance is that sometimes things break with updates and you have to keep on top of things to make the necessary adjustments yourself rather than waiting for a package management team to do it for you.
A good place to learn about which distributions are more or less up to date is OpenSourceWatershed.


text:
Q: How to imrove Stock Prediction using BilSTM/Prophet Output I have written and tried to implement a python code for stock market prediction.
The aim of the code is to run a couple of different ML methods and compare errors and outputs of each.
The data is stock closing price since 2005, split between training and testing(testing is last 3 months of data)
A loop run through the below ML definitions and outputs the error and prediction for each.
However even using high epochs upto 50 or 100 the methods are not performing very well, with prediction not being close to actual stock performance. I'm most suprised by the prophet result i think but i'm not sure what could be changed to improve this either as not based on epochs.
I would appreciate any help in tuning these models as i have tried a range of different "improvements" with little or no luck. I could go higher epoch but my colad times out whenever i try this and i'm not sure the actual benefit.
Any suggestions welcome please, or please reach out for any more info i've exlduded?
Data:

Date
Google
Microsoft
Apple
Amazon
Nivdia

01/03/2005
5.072823
18.913977
0.964983
2.226
1.804381

01/04/2005
4.867367
18.984707
0.974893
2.107
1.719442

Prophet Definition:

def prophet(train_dataset, test_dataset, verbose = 0):
    r2 = 0;
    mse = 0;
    rmse = 0;
    mae = 0;
    try:
        if (verbose == 1):
            print("starting prophet")
            print(train_dataset.head)
            print(test_dataset.head)
        prophet_basic = Prophet(daily_seasonality=True)
        #prophet_basic = Prophet(weekly_seasonality=False)
        #prophet_basic.add_seasonality(name='monthly', period=30.5, fourier_order=5)
        if (verbose == 1):
            print("fitting")
        prophet_basic.fit(train_dataset)
        future= prophet_basic.make_future_dataframe(periods=len(test_dataset), freq='D')
        if (verbose == 1):
            print("predicting")
        forecast=prophet_basic.predict(future)
        if (verbose == 1):
            print("predicted")
            print(forecast.yhat.head)
        '''
        metric_df = forecast.set_index('ds')[['yhat']].join(train_dataset.set_index('ds').y).reset_index()
        metric_df.dropna(inplace=True)
        if (verbose == 1):
            print("metric_df", metric_df.shape)
        r2 = r2_score(metric_df.y, metric_df.yhat)
        mse = mean_squared_error(metric_df.y, metric_df.yhat)
        mae = mean_absolute_error(metric_df.y, metric_df.yhat)
        rmse = math.sqrt(mse)
        '''
        l1 = len(forecast)
        l2 = len(train_dataset)
        l3 = len(test_dataset)
        result2 = pd.DataFrame()
        result2 ["forecasted"] = forecast.yhat[l2:]
        result2["real"] = [x for x in test_dataset["y"]]
        r2 = r2_score(result2.forecasted, result2.real)
        mse = mean_squared_error(result2.real, result2.forecasted)
        mae = mean_absolute_error(result2.real, result2.forecasted)
        rmse = math.sqrt(mse)
        if (verbose == 1):
            print("r2:", r2, "mse:", mse, "rmse:", rmse, "mae:", mae)
    except Exception as e:
        print(e)
        pass
    #return prophet_basic, forecast, r2, mae, mse, rmse
    return forecast, r2, mae, mse, rmse

Decomposed BiLSTM

def de_BiLSTM(train_dataset, test_dataset, n_input = 3, n_features = 1, u = 32, epochs = 100, batch = 1, verbose = 0):
    try:
        if (verbose == 1):
            print("starting BiLSTM")
        train=pd.DataFrame(data=train_dataset["y"],columns=["y"])
        if (verbose == 1):
            print("starting BiLSTM2")
        start = train_dataset.ds[0]
        if (verbose == 1):
            print("start value:", start)
        dti = pd.date_range(start, periods=len(train_dataset), freq='D')
        train["time"]=dti
        train_days=pd.DataFrame()
        train_days["time"]=dti
        train.set_index('time', inplace=True)
        if (verbose == 1):
            print("starting testdataset")
        test=pd.DataFrame(data=test_dataset["y"],columns=["y"])
        if (verbose == 1):
            print("starting testdataset2", test_dataset.head(1))
        #start2 = test_dataset.ds[0]
        start2 = test_dataset['ds'].iloc[0]
        if (verbose == 1):
            print("start value:", start2)
        dti2 = pd.date_range(start2, periods=len(test_dataset), freq='D')
        test["time"]=dti2
        if (verbose == 1):
            print("test_days")
        test_days=pd.DataFrame()
        test_days["time"]=dti2
        test.set_index('time', inplace=True)

        if (verbose == 1):
            print("starting decomposition")
        res = sm.tsa.seasonal_decompose(x=train["y"], extrapolate_trend='freq')
        lstm_train = pd.DataFrame()
        lstm_train["y"]=res.trend+res.resid

        res_test = sm.tsa.seasonal_decompose(x=test["y"], extrapolate_trend='freq')
        lstm_test = pd.DataFrame()
        lstm_test["y"]=res_test.trend+res_test.resid

        if (verbose == 1):
            print("starting scaler")
        scaler = MinMaxScaler()
        scaler.fit(lstm_train)
        scaled_train_data = scaler.transform(lstm_train)
        scaled_test_data = scaler.transform(lstm_test)

        if (verbose == 1):
            print("starting generator")
        generator = TimeseriesGenerator(scaled_train_data, scaled_train_data, length=n_input, batch_size=batch)
        lstm_model = models.Sequential()
        lstm_model.add(layers.Bidirectional(layers.LSTM(units=u, return_sequences = True, activation='relu', input_shape=(n_input, n_features))))
        lstm_model.add(layers.Dropout(0.005))
        lstm_model.add(layers.Bidirectional(layers.LSTM(units=u, return_sequences = True)))
        lstm_model.add(layers.Dropout(0.005))
        lstm_model.add(layers.Bidirectional(layers.LSTM(units=u, return_sequences = True)))
        lstm_model.add(layers.Dropout(0.005))
        lstm_model.add(layers.Bidirectional(layers.LSTM(units=u)))
        lstm_model.add(layers.Dropout(0.005))
        lstm_model.add(layers.Dense(1))
        lstm_model.compile(optimizer='adam', loss='mse')
        if (verbose == 1):
            print("starting fitting")
        lstm_model.fit(generator,epochs=epochs, verbose=verbose)
        batch = scaled_train_data[-n_input:]
        current_batch = batch.reshape((1, n_input, n_features))
        lstm_predictions_scaled = list()

        for i in range(len(lstm_test)):
            lstm_pred = lstm_model.predict(current_batch)[0]
            lstm_predictions_scaled.append(lstm_pred)
            current_batch = np.append(current_batch[:,1:,:],[[lstm_pred]],axis=1)

        lstm_predictions = scaler.inverse_transform(lstm_predictions_scaled)
        lstm_result = pd.DataFrame()
        lstm_result['y'] = test_dataset['y']
        lstm_result['LSTM_Predictions'] = lstm_predictions

        l_r2 = r2_score(lstm_result.y, lstm_result.LSTM_Predictions)
        l_mse = mean_squared_error(lstm_result.y, lstm_result.LSTM_Predictions)
        l_mae = mean_absolute_error(lstm_result.y, lstm_result.LSTM_Predictions)
        l_rmse = math.sqrt(l_mse)
        if (verbose==1):
            print("r2:", l_r2, "mse:", l_mse, "rmse:", l_rmse, "mae:", l_mae)

        seasonal_lstm = pd.DataFrame()
        seasonal_lstm["y"] = lstm_train["y"] + res.seasonal

        seasonal_lstm_test = pd.DataFrame()
        seasonal_lstm_test["y"] = lstm_test["y"] + res_test.seasonal

        seasonal_lstm_pred = pd.DataFrame()
        #seasonal_lstm_pred["y"] = lstm_result['LSTM_Predictions'] + res_test.seasonal
        seasonal_lstm_pred["s"] = res_test.seasonal
        seasonal_lstm_pred["p"] = [x for x in lstm_result['LSTM_Predictions']]
        seasonal_lstm_pred["y"] = seasonal_lstm_pred[['s', 'p']].sum(axis=1)
        seasonal_lstm_pred.drop('s', inplace=True, axis=1)
        seasonal_lstm_pred.drop('p', inplace=True, axis=1)

        #seasonal_lstm_pred["y"] = seasonal_lstm_pred["y"] + lstm_result['LSTM_Predictions']
        return lstm_result,seasonal_lstm, seasonal_lstm_test, seasonal_lstm_pred, l_r2, l_mae, l_mse, l_rmse
        #return lstm_model, lstm_train, lstm_test, lstm_result, train_days, test_days, current_batch, scaler
    except Exception as e:
        print("exception:", e)

'''
BiLSTM
def BiLSTM(train_dataset, test_dataset, n_input = 3, n_features = 1, u = 32, epochs = 100, batch = 1, verbose = 0):
    try:
        if (verbose == 1):
            print("starting BiLSTM")
        train=pd.DataFrame(data=train_dataset["y"],columns=["y"])
        if (verbose == 1):
            print("starting BiLSTM2")
        start = train_dataset.ds[0]
        if (verbose == 1):
            print("start value:", start)
        dti = pd.date_range(start, periods=len(train_dataset), freq='D')
        train["time"]=dti
        train_days=pd.DataFrame()
        train_days["time"]=dti
        train.set_index('time', inplace=True)
        if (verbose == 1):
            print("starting testdataset")
        test=pd.DataFrame(data=test_dataset["y"],columns=["y"])
        if (verbose == 1):
            print("starting testdataset2", test_dataset.head(1))
        #start2 = test_dataset.ds[0]
        start2 = test_dataset['ds'].iloc[0]
        if (verbose == 1):
            print("start value:", start2)
        dti2 = pd.date_range(start2, periods=len(test_dataset), freq='D')
        test["time"]=dti2
        if (verbose == 1):
            print("test_days")
        test_days=pd.DataFrame()
        test_days["time"]=dti2
        test.set_index('time', inplace=True)

        scaler = MinMaxScaler()
        scaler.fit(train)
        scaled_train_data = scaler.transform(train)
        scaled_test_data = scaler.transform(test)

        if (verbose == 1):
            print("starting generator")
        generator = TimeseriesGenerator(scaled_train_data, scaled_train_data, length=n_input, batch_size=batch)
        lstm_model = models.Sequential()
        lstm_model.add(layers.Bidirectional(layers.LSTM(units=u, return_sequences = True, activation='relu', input_shape=(n_input, n_features))))
        lstm_model.add(layers.Dropout(0.2))
        lstm_model.add(layers.Bidirectional(layers.LSTM(units=u, return_sequences = True)))
        lstm_model.add(layers.Dropout(0.2))
        lstm_model.add(layers.Bidirectional(layers.LSTM(units=u)))
        lstm_model.add(layers.Dropout(0.2))
        lstm_model.add(layers.Dense(1))
        lstm_model.compile(optimizer='adam', loss='mse')
        if (verbose == 1):
            print("starting fitting")
        lstm_model.fit(generator,epochs=epochs, verbose=verbose)
        batch = scaled_train_data[-n_input:]
        current_batch = batch.reshape((1, n_input, n_features))
        lstm_predictions_scaled = list()

        for i in range(len(test)):
            lstm_pred = lstm_model.predict(current_batch)[0]
            lstm_predictions_scaled.append(lstm_pred)
            current_batch = np.append(current_batch[:,1:,:],[[lstm_pred]],axis=1)

        lstm_predictions = scaler.inverse_transform(lstm_predictions_scaled)
        lstm_result = pd.DataFrame()
        lstm_result['y'] = test_dataset['y']
        lstm_result['LSTM_Predictions'] = lstm_predictions

        l_r2 = r2_score(lstm_result.y, lstm_result.LSTM_Predictions)
        l_mse = mean_squared_error(lstm_result.y, lstm_result.LSTM_Predictions)
        l_mae = mean_absolute_error(lstm_result.y, lstm_result.LSTM_Predictions)
        l_rmse = math.sqrt(l_mse)
        if (verbose==1):
            print("r2:", l_r2, "mse:", l_mse, "rmse:", l_rmse, "mae:", l_mae)

        return lstm_result, l_r2, l_mae, l_mse, l_rmse
        #return lstm_model, lstm_train, lstm_test, lstm_result, train_days, test_days, current_batch, scaler
    except Exception as e:
        print("exception:", e)

Loop
params = {'googl': {'name':'Google', 'n_features': 1, 'n_input': 24, 'u': 8, 'epochs' : 1, 'train':googl_train_dataset, 'test':googl_test_dataset},
          #'msft': {'name':'Microsoft', 'n_features': 1, 'n_input': 14, 'u': 4, 'epochs' : 2, 'train':msft_train_dataset, 'test':msft_test_dataset},
          #'aapl': {'name':'Apple', 'n_features': 1, 'n_input': 24, 'u': 4, 'epochs' : 2, 'train':aapl_train_dataset, 'test':aapl_test_dataset},
          #'amzn': {'name':'Amazon', 'n_features': 1, 'n_input': 20, 'u': 4, 'epochs' : 5, 'train':amzn_train_dataset, 'test':amzn_test_dataset},
          #'nvda': {'name':'Nivdia', 'n_features': 1, 'n_input': 14, 'u': 4, 'epochs' : 5, 'train':nvda_train_dataset, 'test':nvda_test_dataset},
         }
for p in params:
    print("-----------------------------------------")
    print("starting ",params[p]['name'])
    train_dataset = params[p]['train']
    test_dataset = params[p]['test']
    n_input = params[p]['n_input']
    n_features = params[p]['n_features']
    u = params[p]['u']
    epochs = params[p]['epochs']
    l = len(train_dataset)

    delstm_result,seasonal_lstm, seasonal_lstm_test, seasonal_lstm_pred , dl_r2, dl_mae, dl_mse, dl_rmse = de_BiLSTM(train_dataset, test_dataset, n_input, n_features, u , epochs,  1, 0)
    lstm_result, l_r2, l_mae, l_mse, l_rmse = BiLSTM(train_dataset, test_dataset, n_input, n_features, u , epochs,  1, 0)
    forecast,p_r2, p_mae, p_mse, p_rmse = prophet(train_dataset, test_dataset, 0)

    result = pd.DataFrame()
    result ["Prophet"] = forecast.yhat[l:]
    result["deBiLSTM"] = [x for x in seasonal_lstm_pred["y"]]
    result['avg'] = result.mean(axis=1)
    result["real"] = [x for x in seasonal_lstm_test["y"]]
    result["days"]  = [x for x in test_dataset["ds"]]
    result["BiLSTM"] = [x for x in lstm_result["LSTM_Predictions"]]
    result["hdeBiLSTM"] = [x for x in hseasonal_lstm_pred["y"]]

    r2 = r2_score(result.real, result.avg)
    mse = mean_squared_error(result.real, result.avg)
    mae = mean_absolute_error(result.real, result.avg)
    rmse = math.sqrt(mse)
    print("hybrid:", "r2:", r2, "mse:", mse, "rmse:", rmse, "mae:", mae)
    print("prophet:", "r2:", p_r2, "mse:", p_mse, "rmse:", p_rmse, "mae:", p_mae)
    print("deBiLSTM:", "r2:", dl_r2, "mse:", dl_mse, "rmse:", dl_rmse, "mae:", dl_mae)
    print("BiLSTM:", "r2:", l_r2, "mse:", l_mse, "rmse:", l_rmse, "mae:", l_mae)
    plot_graph(result, params[p]['name'], show = 0)

Sample Prediction


text:
Q: Where does GMSMapView get its location data when isMyLocationEnabled is set to true? I'm using the Google Maps iOS SDK to display a blue dot for my current location.  I instantiate the map and set the flag to true via:
self.mapView.isMyLocationEnabled = true

Doing this shows the blue dot for my current location, but I cannot find any information about how often this data is updated.  I'm concerned about battery usage while receiving location updates with this option.

*

*Does the Google Maps SDK use its own CLLocationManager?

*If so, what parameters does it use?  Does it update the location continually?

*What location accuracy does it use?

*How does it handle the view going off screen?

A: What a coincidence, I have had the same questions recently and nothing could found in the Google documentation or somewhere.
So here is my thoughts and observations on the matter, you might find something useful

*

*There is no way to get user's GPS location except using  iOS CoreLocation, so I believe  they use it as we do

*Based on how accurate it shows user's location on the map, I suspect Google map uses accuracy about 10 meters if not the best.  Actual accuracy you can try to get from myLocation property that is CLLocation instance. I didn't try it. And probably It updates user location continually, however it doesn't keep your application in background, even if you have 'always' authorization.

*It uses user's location even when is off the screen, I looked at the energy bar, while my location manager was off and it fills corresponding cells for background, of course
SDK might decrease accuracy, but I am not sure if subclass of UIView can even detect if it is shown or hidden. The only way I found, was to change flag to false

self.mapView.isMyLocationEnabled = false
Hope it helps, in case you'll find something to share regarding the question, please get back.


text:
Q: Array of pointer to structs printing I have an array of pointers to structs:
item** items = NULL;

These are the functions I wrote for allocating and printing the array:
void allocateItems(item** items, int numItems) {
    items =malloc(numItems*sizeof(item*));
    for (int i = 0; i < numItems; i++) {
        items[i]=malloc(sizeof(item*));
        items[i]->data = i + 1;
        items[i]->data2 = (i + 1) % 2;
    }
}

void printItems(item** items, int numItems) {
    for (int i = 0; i < numItems; i++) {
        printf("%d : %d\n", items[i]->data, items[i]->data2);
    }
}

But when I try to print that array of structs, I get a segmentation fault. Can someone tell me where the mistake is?

A: This is only allocating enough memory for an item*:
items[i]=malloc(sizeof(item*));

it must allocate memoryfor an item:
items[i]=malloc(sizeof(item));

In order for the changes made with allocateItems() to be visible to the caller then address of items must be passed in:
allocateItems(&items, 4);

which the changes the argument type and means items must be dereferenced within the function:
void allocateItems(item*** items, int numItems)
{
    *items = malloc(numItem * sizeof(item*));
    for (int i = 0; i < numItems; i++)
    {
        (*items)[i] = malloc(sizeof(item));
        (*items)[i]->data = i + 1;
        (*items)[i]->data2 = (i + 1) % 2;
    }
}

This could be simplified by allocating an array of item instead of an array of item*. It would also mean that the list of items are in a contiguous block of memory instead of being fragmented with the multiple malloc() for allocating each element in the array:
void allocateItems(item** items, const int numItems)
{
    *items = malloc(numItems * sizeof(item));
    if (*items)
    {
        for (int i = 0; i < numItems; i++)
        {
            (*items)[i].data  = i + 1;
            (*items)[i].data2 = (i + 1) % 2;
        }
    }
}

item* items;
allocateItems(&items, 4);

if (items)
{
    for (int i = 0; i < 4; i++)
        printf("[%d]: (%d, %d)\n",
               i,
               items[i].data,
               items[i].data2);

    free(items);
}


text:
Q: Shell script run with mac address validate Can we run shell script with check system mac address validation then process.
#!/bin/bash

### here i need to check system mac address
### if mac is not match then script will not run
killall gnome-terminal
echo "End Of Day Session Complete"

plz suggest

A: Why not. First get the mac address of your system and store it in a variable in your shell script or in a config file. Every time when you run the script first get the mac address of the system and compare with the mac id already stored in your script's variable if same continue and if not just exit. Use ifconfig -a command to get the mac address of your system and store it in a config file or in your script.

A: A hardware adress can be obtained like this:
LC_ALL=C ifconfig | egrep "HWaddr" | awk '{print $5}'

but note:

*

*there might be more than one interface with a mac

*on many systems, the mac can be spoofed

To suspend work, just exit. Don't killall, and if you do, don't expect later echo messages to be seen by someone.

A: As you want to run your code on multiple systems, you could use an associative array to store the MAC addresses of the systems where the script is to be run
declare -A valid_mac
valid_mac["00:00:00:00:00:00"]=1
valid_mac["00:00:00:00:00:01"]=1
valid_mac["00:00:00:00:00:02"]=1

Your script function is to terminate all gnome-terminal sessions on each machine where it is run if the mac address is valid.
Let's define a function
function kill_all_terms(){
    killall gnome-terminal
    echo "End Of Day Session Complete"
}

Now on each machine you want to get a list of MAC addresses of this machine. There are many ways to do it. The function below lists MAC addresses of all IPv4 interfaces using shell string parsing capabilities
function macs(){
   local macs line l1
   while read line ; do
     l1="${line#*link/ether }"  ;
     macs="${l1% brd*} ${macs}" ;
   done < <( ip -4 -o link ) ;
   echo "${macs}"
}

Now we can define the main loop
function main() {
   for mac in $(macs) ; do
      if [ -n "${valid_mac[$mac]}" ] ; then
         kill_all_terms
         break
      fi
   done
}

Finally just run main() as
 main "$@"


text:
Q: how to allow a certain group of useres to only login via LDAP while others can use LDAP or local login? I managed to set up my system to use either LDAP or the local password (by adding "password sufficient pam_ldap.so" to PAM and calling "pam_unix2.so" afterwards). However I would like to restrict a certain group of users to be able to only use LDAP and not have the fallback of pam_unix2.so. Is there way of doing this?

A: I don't think there is any point in having local accounts for users that are in LDAP, since all the needed information can be loaded from LDAP anyways. If you remove the local accounts for the users who should only log in through LDAP, then won't that fix this problem?

A: in case this is intersting for others, I found the answer here:
https://serverfault.com/questions/196255/how-to-allow-a-certain-group-of-useres-to-only-login-via-ldap-while-others-can-us


text:
Q: Powershell number notation matches and rename-item logic In the below solution for renaming files taken from an answer to my question Rename-Item error, what do the following bits of code do?

*

*^\d{4}

*e={$Matches[1]}

*Rename-item -Newname {"{0:D4} - sp - C - {1}" -f ++$Count.Value,$_.Name}
For 1. I think this is saying a four digit number but I would like to understand the notation used.
For 2. $Matches hasn't been set anywhere, is this a variable specific to Select-Object?
For 3. what is {0:D4} doing and the {1} at the end of the same string. Also, is this line concatenating two strings with the comma delimiter?
$Count = [Ref][math]::Max(1000,
    [int](Get-ChildItem -Path $Folder -Filter *.sql -File|
            Where-Object Name -match '^(\d{4}) - sp - C -' |
            Select-Object @{n='Count';e={$Matches[1]}} -Last 1).Count)

Get-ChildItem -Path $Folder -Filter *.sql -File |
  Where-Object Name -NotMatch '^\d{4} - sp - C - ' |
    Rename-item -Newname {"{0:D4} - sp - C - {1}" -f ++$Count.Value,$_.Name}

A: *

*^\d{4} is a Regular Expression
^ anchors at line begin
\d represents a digit
{4} is a quantifier, specifying exactly 4 of the previous, here digits
() parentheses mark a capture group

*cite from Get-Help about_Comparison_Operators

The -Match and -NotMatch operators populate the $Matches automatic variable.

Where $Matches[1] represents the 1st capture group of the RegEx.
The Select-Object builds a calculated property from the match (4 digit number) and only uses the last/highest

*Obtaining the previously used highest number was a bonus I should have explained better 1st place.
As the obtained number now contains 4 digits (no more a fixed 1 and three zeroes) the -format operator (shorted to just -f) is used to build the new file name by inserting variable contents in place of the {x} where x is a zero based number.


text:
Q: How to implement a dynamic generic type return method without casting at runtime in C#? Say I want to convert the below implementation in Java to C#, so that I don't have to cast the returned value at runtime, where the casting should already be handled in the get method.

why not create setters and getters, if you ask? simply because I plan to have 50-100+ attributes and I don't want to create setters and getters for every attributes.

[c#] - what i want to end up doing in c#
string name = playerA.getAttribute(Attribute.NAME);
int age = playerA.getAttribute(Attribute.AGE);

Currently I can't unless I cast the returned value to the correct type. But can I do that casting in side the get method before returning?
[Java] - anyhow, this is the current java implementation that works without casting
//setting attributes
playerA.setAttribute(Attribute.NAME, "Tom");
entityB.setAttribute(Attribute.AGE, 4);
...
//getting the attribute without casting
string name = playerA.getAttribute(PlayerAttribute.NAME);
int age = playerB.getAttribute(PlayerAttribute.AGE);

The method inside a Player/Entity is setup like this to get attributes
[Java]
public <E> E getAttribute(Attribute attr){
    //atrributeRepository is EnumMap<Attribute, Object>
    //how I will get my attribute value type at runtime
    Object result = attributeRepositoryMap.get(attr);

    //the enumMap will only ever hold these three type for this example
    if(result instanceof Boolean){ return (E) (Boolean) result; }
    if(result instanceof String){ return (E) (String) result; }
    if(result instanceof Integer){ return (E) (Integer) result; }

    return null;
    //say all checks are in place and null will never be reach
}

The closest I was able to get in c# is this.
[c#] - though I can deal with it, i would like to prevent casting
string name = (string) getAttribute<string>(Attribute.NAME);
int age = (int) getAttribute<int>(Attribute.AGE);

the method
public T getAttribute<T>(Attribute attribute){
{
     Object result = attributeRepositoryDictionary[attribute];
     return (T)result;
}

is this as closest as I can get with c#, where casting is needed for getting attributes?

A: I'm not sure I really like it as an idea - but you could do this by making Attribute generic:
public static class Attributes
{
    public static Attribute<int> Age = new Attribute<int>("age");
    public static Attribute<string> Name = new Attribute<string>("name");
}

public class Attribute<T>
{
    public string Key { get; }

    public Attribute(string key)
    {
        Key = key;
    }

    ...
}

Then you can implement your method as:
public T GetAttribute<T>(Attribute<T> attribute)
{
    // attributeDictionary would be a Dictionary<string, object>
    return (T) attributeDictionary[attribute.Key];
}

At that point, type inference will be your friend, so you can just write:
int a = player1.GetAttribute(Attributes.Age);

and it'll be equivalent to:
int a = player1.GetAttribute<int>(Attributes.Age);

A: I was able to find an alternative solution along with @Jon Skeet, which this was more of what I was looking for (not sure if it is an ideal design though). Anyhow, little did I know there was a keyword called "dynamic" in cSharp.
It allowed my method getAttribute() to return any type at runtime, The only requirement is that you must know the return type.
So I do not recommend using this approach if you plan to work with many return types that are in the 5+. That's why I would recommend using something like an enum to give clues on what type will be returned.
In my case, I will only deal with the basic common return types (int, string, float, bool), so its rather easy to know what type will be returned base on the attribute that is called.
class Entity
{
     Dictionary<Attribute, Object> attributeRepositoryEnumMap;
     ...
     public dynamic getAttribute(Attribute attribute){
         Object result = attributeRepositoryEnumMap[attribute];
         return result;
     }
}

now I can get return attributes like in the example below without casting
class MyApp
{
    Entity e = new Entity();
    e.setAttribute(Attribute.NAME, "Bob");
    e.setAttribute(Attribute.AGE, 55);
    e.setAttribute(Attrbute.HEIGHT, 5.5f);

    string name = e.getAttribute(Attribute.NAME);
    int age = e.getAttribute(Attribute.AGE);
    float height = e.setAttribute(Attribute.HEIGHT);
}

Not sure how this will all work out for me, but a part of this attempt was to also find an easier work around saving and hydrating my json objects without creating tons of setters and getters.


text:
Q: Total number of instances of single-digit numbers w/in two-digit numbers w/in same cell. Our legacy payroll system reports each day of the month, i.e., 1 through 31, across a single row of cells, e.g., A1:AE1. Below each day, an empty cell or a two-digit number is reported. An empty cell means the employee was not at work at all that day. Since we operate on two back-to-back shifts, the system reports two-digit numbers. The two-digit number, not separated by a space, has no meaning as a whole; each digit must be interpreted separately. Each digit is limited to numbers 0 through 5; and can look like 22, 33, 50, 32, or 40. The 0 through 5 range is used to codify hourly pay rates. A 2 means $14/hour, whereas a 3 means $16/hour. It is the sum of all instances of each pay rate, 0 through 5, that I am trying to tally but have not been able to. The point of doing this is to find out how many shifts, not days, an employee worked at a certain hourly rate. These tallies would be reported to the right of column AE.
COUNTIF(A1:AE1,"2") tallies 2 for {..., 50, 23, 32, ...} -- Desired tally
COUNTIF(A1:AE1,"2") tallies 3 for {..., 22, 23, 32, ...} -- Hoping to get a 4
I have tried tinkering with SUMPRODUCT but haven't been very successful.
In the image below (not allowed to post because I'm a newbie), there are 2 instances of hourly rate 2 and 8 instances of hourly rate 3 between the 14th and 18th of November 2013, i.e., {23, 33, 33, 33, 23}. Although the COUNTIF formula used also reports 2 instances of hourly rate 2, it only reports 5 instances of hourly rate 3.

A: Try using SUBSTITUTE to count within individual cells and then sum them up with SUMPRODUCT:
=SUMPRODUCT((LEN(A1:AE1)-LEN(SUBSTITUTE(A1:AE1,"2",""))))

The above is to count the 2. You can change the 2 to 3 to count the 3s:
=SUMPRODUCT((LEN(A1:AE1)-LEN(SUBSTITUTE(A1:AE1,"3",""))))
                                                ^

LEN(A1:AE1)-LEN(SUBSTITUTE(A1:AE1,"3","")) gives the number of each 3 in each particular cell.
The logic is subtracting the length of the cell without 3 from the length of the cell.

A: Create a UDF  (User Defined Function), and use that to do the counting.
Instead of putting =COUNTIF(A1:AE1,"2")  in a cell, rather put =TALLYPAYRATES(A1:AE1,"2")
Press  View / Macros / ViewMacros
In Macro Name, type  TALLYPAYRATES,  and press Create.
Replace both lines with the following--
Function TALLYPAYRATES(rng As Range, sRate As String) As Long

    Dim nOccurs As Long
    Dim aCell As Range
    Dim sCellRate As String

    nOccurs = 0
    For Each aCell In rng
        sCellRate = Format(aCell, "00")

        If Left(sCellRate, 1) = sRate Then
            nOccurs = nOccurs + 1
        End If

        If Right(sCellRate, 1) = sRate Then
            nOccurs = nOccurs + 1
        End If

    Next aCell

    TALLYPAYRATES = nOccurs

End Function

Then add something like the following in some cells
=TALLYPAYRATES(A1:F1,"2")
=TALLYPAYRATES(A1:F1,"3")
The following data ------- gives these results
22  33  50  32  40  counts      3   3
50  23  32  00      00      counts      2   2
22  23  32  00  00  counts      4   2
23  33  33  33  23  counts      2   8

A: Another way is the following:
=COUNT(IF(VALUE(MID($A$1:$AE$1,SEQUENCE(2),1)) = COLUMN()-COLUMN($AF$1:$AF$1), VALUE(MID($A$1:$AE$1,SEQUENCE(2),1)), "a") )

It breaks each cell into two array elements and makes a full array of all of them. Then makes them values, not text. The IF() then checks each array element for a value and places a text character in the place of any that are not equal to it. COUNT() then counts the numerical values left, ignoring those text character elements.
What value is the COLUMN()-COLUMN($AF$1:$AF$1) calculation. It starts at 0 and rises to 5 as you copy and paste into the five cells so that it is in the range AF:AK.
(For whatever reason, I am not presently able to make it a Spill formula, so the copying and pasting is needed.)
The key element is the distinction COUNT() makes between values and text.
It looks long and messy, but one could dress that objection up via LET() or, if preferred or not available, Named Ranges.
(Of course, in 2014 it would have needed CSE entry and SEQUENCE() would need replaced, probably with an array constant ({0,1,2,3,4,5}). This answer is not only meant to present a different way, but also one that uses more of post-2021's capabilities.
In some time period over the next year and a half, as the new text/array formulas are finally allowed to most of us, this will become trivial to do. But until then... and for legacy installations...)


text:
Q: Where can I get xfwm4-themes on Xubuntu 19.10 When using Xubuntu I always installed the package xfwm4-themes as I really liked the good old nostalgic themes like Redmond, Platinum, etc. I am unable to find this package in 19.10 in the main repos these days though, so I was wondering where one can find this package.

A: According to packages.ubuntu.com, the xfwm4-themes package is no longer available in the standard 19.04 and 19.10 repositories. And that makes sense because it's been dropped from Debian in December 2018 for being unmaintained.
Alternative 1
I would suggest looking at the themes available in the 19.10 repositories. Many of them provide their own xfwm4 theme and it's likely that these themes will be appropriate for your system.
Alternative 2
You can visit xfce-look.org and click on XFCE/XFWM4 Themes to get a listing of themes. I suggest you choose from recently updated themes to ensure compatibility.

I downloaded the Neon_Knights_Blue .tar.xz archive, extracted it, and placed it in ~/.themes.
Then, I opened Settings > Window Manager and could choose it from there.

Alternative 3
You can still find the xfwm4-themes in archived form online. For example, there's git.xfce.org/archive/xfwm4-themes/ from which you can download xfwm4-themes-4.10.0.tar.gz from eight years ago.

*

*extract the contents

*open the redmond folder

*create a folder called xfwm4 in the redmond folder

*move all the .xpm files and the themerc file into the xfwm4 folder

*move the redmond folder into ~/.themes, which you'll need to create if it doesn't exist.

*open Settings > Window Manager and choose redmond

*applications that use GNOME's client-side decorations will obviously not use any  xfwm4 theme.

Using the redmond xfwm4 theme

A: The package in question was last part of Xfce 4.10.  The currently shipping version of Xfce 4.14 does not include it and the current development tree does not have it either.  If you want something like that to return you need to raise the point at a Xubuntu meeting like the most recent one where development issues were discussed both for Xubuntu and upstream Xfce.


text:
Q: unexpected token parsing XML I've been looking at this for over an hour trying to figure out the problem without any luck. I am not quite sure what is wrong, I am working on my custom hotkey system. Any help would be appreciated.

'<' is an unexpected token. The expected token is ';'. Line 3, position 19

<Root>
<keyCodes>https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx</keyCodes>
<hotkeyToggle>&HA3</hotkeyToggle>
<reattachGame>&H74</reattachGame>
<toggleMenu>&H2D</toggleMenu>
[...]

A: You either mean &HA3 (the content being a literal string "&HA3", where you have to XML-escape & as & otherwise XML will consider it a broken XML-entity) or the XML-entity £ (a byte with hex value 0xA3).


text:
Q: Merging nested lists based on the first element of a nested list I have a large list of lists that contains some data.
[['', 'A', 'B'],['C', '', 'D'],['E', 'F', ''],['', 'H', 'I'],['J', 'K', ''],['L', 'M', 'N']]

The data represented in those lists are connected. When the first element of a nested list is '', I know for certainty that every list after that, should be apart of the list that began with an element of ''. Every list that is, until the next list that has a first element of ''. Then the cycle repeats. Any of the lists can contain '' at any element. It is only when the first element is '' that the cycle repeats.
I'm hoping to find a quick way of creating a new list of lists from the above list of lists that produces the expected outcome below.
[['', 'A', 'B', 'C', '', 'D', 'E', 'F', ''],['', 'H', 'I', 'J', 'K', '', 'L', 'M', 'N']]

A: This works:
a = [['', 'A', 'B'],['C', '', 'D'],['E', 'F', ''],['', 'H', 'I'],['J', 'K', ''],['L', 'M', 'N']]

final = []

for i in a:
    if i[0] == "":
        final.append([])
    final[-1].extend(i)

print(final)

Output
[['', 'A', 'B', 'C', '', 'D', 'E', 'F', ''], ['', 'H', 'I', 'J', 'K', '', 'L', 'M', 'N']]
[Finished in 0.7s]

A: Here's one answer:
lst = [['', 'A', 'B'],['C', '', 'D'],['E', 'F', ''],['', 'H', 'I'],['J', 'K', ''],['L', 'M', 'N']]
result = []
temp = []
for l in lst:
    if len(l[0]) == 0 and len(temp) == 0:
        temp.extend(l)
    elif len(temp) != 0:
        temp.extend(l)
        if len(l[-1]) == 0:
            result.append(temp)
            temp = []
result

Output:
[['', 'A', 'B', 'C', '', 'D', 'E', 'F', ''], ['', 'H', 'I', 'J', 'K', '']]

A: You could try something like
data=[['', 'A', 'B'],['C', '', 'D'],['E', 'F', ''],['', 'H', 'I'],['J', 'K', ''],['L', 'M', 'N']]

new_list = []
for l in data:
    if l and l[0]=='':
        new_list.append([])
        new_list[-1].extend(l)
    else:
        new_list[-1].extend(l)
print(new_list)

An empty list is appended to the list to be output (in this case new_list) whenever a sublist with first element '' is found in data.
New elements are added to the last sublist in the current value of new_list.
Output is:
[['', 'A', 'B', 'C', '', 'D', 'E', 'F', ''], ['', 'H', 'I', 'J', 'K', '', 'L', 'M', 'N']]

A: You could do this in two stages, first find the indices of the ones that start with '', then iterate over those indices and create the sub-list:
from itertools import chain, zip_longest

lst = [['', 'A', 'B'], ['C', '', 'D'], ['E', 'F', ''], ['', 'H', 'I'], ['J', 'K', ''], ['L', 'M', 'N']]

# find the indices
starts = [i for i, e in enumerate(lst) if e[0] == '']

# iterate over the indices in pairs (current, next)
result = [list(chain.from_iterable(lst[start:end])) for start, end in zip_longest(starts, starts[1:], fillvalue=len(lst))]

print(result)

Output
[['', 'A', 'B', 'C', '', 'D', 'E', 'F', ''], ['', 'H', 'I', 'J', 'K', '', 'L', 'M', 'N']]


text:
Q: Running nagios on nginx I'm trying to set up Nagios on Nginx and I'm having trouble. I used  this as a guide, but I still can't access Nagios from the web.
Just to confirm, I have nagios, fcgiwrap and php-cgi running. When i go to example.com/nagios, it brings up the nagios pages. But when i click on anything substantial, i get a message saying "Error: Could not read host and service status information!". I am sure it has something to do with permissions, but I can't figure out what the problem is.
Anyone know what i can do?
thanks in advance!

A: Found out my problem. It had to do with file permissions for the nagios files. Nginx ran under a different user, so it didn't have the right permissions to access the nagios files.


text:
Q: Alert is not get called in the onSubmit method Here is my html code, and i expect when i submit, an alart message appears.
<input id="reportForm" type="submit" value="Submit Report" class="btn btn-primary" />

and here is the js code:
$(document).ready(function () {
    $('#reportForm').submit(function () {
        alert("Thanks for your report.");
    });
});

Unfortunately, it does not call the alert!

A: The submit() event handler can only be bound to an form element (not to a input element, as you have done).
You have two options:
(1) Bind the action(s) to the form submission, by changing your HTML to something along these lines --
<form id="reportForm">
    <input type="submit" value="Submit Report" class="btn btn-primary" />
</form>

Or; (2) Bind the action(s) to the button click, by changing your javascript, like so --
$('#reportForm').click(function(){
   alert("Thanks for your report.");
});

A: Submit events are triggered when you try to submit a form. If you wrap the field inside a <form> tag and target that element it should work.
<form id="reportForm">
    <input id="submitButton" type="submit" value="Submit Report" class="btn btn-primary" />
</form>


text:
Q: ASP.NET MVC3 database deployment I have created application in mvc3 and I used the default account controller for my users.
I followed instructions from http://www.asp.net/mvc/tutorials/authenticating-users-with-forms-authentication-cs to put all tables (from aspnetdb) in one database.
My trouble is how to set webconfig and connection string corectly?
I set the conn string to my databse but if I try to register Visual studio create aspnetdb and put my user info there.
I am trying to find solution to stop vs creating aspnetdb.
My hosting provider is http://www.inside.hr it is hosting company from Croatia

A: If your shared hosting environment only allows you to use one database, you can add the ASP.NET Membership database tables to your existing database. Joe Stagner has a walkthrough on how to do that here.
Can you update your question to tell us where you're hosting? That will help.

A: I'm not sure if I follow you correctly, but did you try something like this:
<connectionStrings>
  <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
   providerName="System.Data.SqlClient" />
  <add name="MyDevArmyDB" connectionString="Data Source=DATASOURCE;Initial Catalog=devarmydb;Persist Security Info=True;User ID=USERID;Password=PASSWORDSTRING"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

DATASOURCE- replace with the address of your database
USERID- replace with the actual user id
PASSWORDSTRING- replace with the actual password
Accessing the DB is done like this:
public class SqlUserRepository : IUserRepository
{
    private DataContext dataContext;
    private Table<User> usersTable;

    public IQueryable<User> Users { get { return usersTable; } }

    public SqlUsersRepository(string databaseName)
    {
        HttpRequestWrapper request = new HttpRequestWrapper(System.Web.HttpContext.Current.Request);
        Configuration config = WebConfigurationManager.OpenWebConfiguration(request.ApplicationPath);
        dataContext = new DataContext(config.GetConnetionString(databaseName));
    }
}

Note that GetConnectionString is an extension function which supports encryption/decryption of the connection string (if you decide to protect the connection string):
public static class ConfigExtension
{
    public static string GetConnetionString(this Configuration config, string databaseName, string provider = "RSAProtectedConfigurationProvider")
    {
        string sectionName = "connectionStrings";
        ConfigurationSection section = config.GetSection(sectionName);
        if (section != null && !section.SectionInformation.IsProtected)
        {
            section.SectionInformation.ProtectSection(provider);
            config.Save();
        }

        return WebConfigurationManager.ConnectionStrings[databaseName].ConnectionString;
    }
}


text:
Q: Как получить доступ к корневому элементу из листа в листе JSON Есть JSON файл такой структуры:
{
"person" {
    "someElement" : "test",
    "operationsList": [
        {
          "date": 1505980686916,
          "sendersLastName": "last",
          "sendersFirstName": "first",
          "sendersSecondName": "second",
          "operationDetailsList" : [
            {
                "innerKey" : "key1",
                "innerValue" : "value1"
            },
            {
                "innerKey" : "key2",
                "innerValue" : "value2"
            }
          ],
          "operationCurrencyAmount": 456,
          "operationCurrencyCode": "TEST"
        },
        {
          "date": 1505980686916,
          "sendersLastName": "last",
          "sendersFirstName": "first",
          "sendersSecondName": "second",
          "operationDetailsList" : [
            {
                "innerKey" : "key1",
                "innerValue" : "value1"
            },
            {
                "innerKey" : "key2",
                "innerValue" : "value2"
            }
          ],
          "operationCurrencyAmount": 456,
          "operationCurrencyCode": "TEST"
        },

    ],
    "otherField" : "testValue"
},
"booleanFlag" : true
}

Создан jr:list с элементами "operationsList":
subDataSource("person.operationsList").
Внутри этого (operationsList) листа есть еще один jr:list (operationDetailsList):
subDataSource("operationDetailsList")
Вопрос:
Нужно внутри дочернего (operationDetailsList) листа использовать корневой элемент "booleanFlag" в качестве printWhenExpression для одного из полей (например, "innerKey").
Однако в списке доступных полей есть только поля из subDataset="operationDetailsList", т.е. доступны только "innerKey" и "innerValue". Можно ли получить доступ к элементу "booleanFlag" из листа в листе?

A: Есть решение, можно передать это поле в виде параметра в лист и использовать в листе именно параметр, а не сам филд.


text:
Q: How to filter a list of generic objects I have find the code to implement a SortableBindingList that extends of BindingList and it theoretically let sort and filter a list of generic objects.
It works perfectly sorting the list but I can not get filtering.
The filter code is as follows
       Protected Sub UpdateFilter()
        _isSorted = False 'remove sort.
        Try
            'We filter on the entire collection
            Dim filtered = _originalData.AsQueryable()

            If Not String.IsNullOrEmpty(_filter) Then filtered = filtered.Where(_filter)

            Dim filteredResult = filtered.ToList()
            Items.Clear()

            If filteredResult IsNot Nothing AndAlso filteredResult.Count > 0 Then
                For Each tItem As T In filtered
                    Items.Add(tItem)
                Next
            End If
        Catch
            'Reset the list
            Items.Clear()
            For Each tItem As T In _originalData
                Items.Add(tItem)
            Next

            'Rethrow the error
            Throw
        Finally
            OnListChanged(New ListChangedEventArgs(ListChangedType.Reset, -1))
        End Try
    End Sub

The problem is that the following example receive like a filter a string in the clause where but the compile trhow an error since it wait a function
I don't know how to resolve this
Sorry if you do not understand well. I do not speak English well

A: You need to pass a predicate. I hope this example will guide you.
Private Function AddFilter(list As List(Of String), filter As Func(Of String, Integer, Boolean)) As List(Of String)
    Dim l As IEnumerable(Of String) = Nothing
    If Not IsNothing(filter) Then
        l = list.Where(filter)
    End If
    Return l.ToList
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim A As New List(Of String) From {"Mathew", "Mark", "Luke", "John"}
    Dim predicate As Func(Of String, Integer, Boolean) = Function(str, index) str.StartsWith("M")
    Dim FilteredList = AddFilter(A, predicate)
    For Each s As String In FilteredList
        Debug.Print(s)
    Next
End Sub

A: There is an answer in some post that recommend this.
You can use Dynamic Linq:
Dim filter As String = "property1>10 and property2 like 'anystring' or property3<=25".
Dim results = Elements.Where(filter).
But I don't know how to use dinamic linq


text:
Q: How do you run a set of test classes from 1 class Currently all my tests extend another class that has a @BeforeAll tag but I want this BeforeAll code to be run just once in total for the entirety of the tests instead of once per class
@BeforeAll
static void createWriter() throws IOException {
    // create file to be writen to
}

@AfterAll
static void finishFile() throws IOException {
    // end file and create high level metrics
}

@Override
public void testSuccess(ExtensionContext extensionContext, Throwable throwable) {
    // override normal test execution finishes
}

A: You have to run test cases as a test suite. You can use testing framework "TestNG" to achieve this functionality.
Use annotations @BeforeSuite and @AfterSuite, which will execute once for multiple test classes.
Please check with this link for detailed information.

A: I am not aware of any built-in way of doing that. So the simple technical answer would be to use a static boolean flag that tells that method whether the method ran already (or not). Upon the first method execution, that flag gets toggled, and prevents further executions.
But the real answer is: you are probably going down the wrong rabbit hole. Having test classes extend a base class is more of an anti pattern, and to have a BeforeAll method that is either too expensive to be called repeatedly, or worse: not idempotent makes things worse. Unit tests should be simple and self explanatory (thus self contained). Inheritance and "run only once" directly violate that requirement.


text:
Q: JS to jQuery! - Combobox solution? i have this code working in js :
let selecter = document.getElementById("select");
for (let i = 0; i < selecter.children.length; i++) {
    selecter.children[i].addEventListener("click", function() {
    console.log(i);
}

so i tried to convert this into jQuery. My result is kinda mixed up and i tried a few variations but none worked.
maybe you guys can show me the right way to handle this.
not working code:
let cbx = $("#cbx option:selected");
for (let i = 0; i < cbx.length; i++) {
    cbx.click(function() {
        console.log(cbx.index());
    });
}

the goal is to get the index of the choosen field in the combobox after you clicked it.
here is the HTML code for the Combobox:
    <div id="cbx-container" class="container">
        <select name="combobox" id ="cbx" class="combobox">
            <option id="oTrue" selected="">True</option>
            <option id="oFalse">False</option>
            <option id="oId1">Identitaet 1</option>
            <option id="oId2">Identitaet 2</option>
            <option id="oNotA">Not A</option>
            <option id="oNotB">Not B</option>
            <option id="oAnd">AND</option>
            <option id="oNand">NAND</option>
            <option id="oOr">OR</option>
            <option id="oNor">NOR</option>
            <option id="oXor">XOR</option>
            <option id="oAequ">Aequivalenz</option>
            <option id="oInhib1">Inhibition 1</option>
            <option id="oInhib2">Inhibition 2</option>
            <option id="oImp1">Implikation 1</option>
            <option id="oImp2">Implikation 2</option>
        </select>
    </div>

couldnt find the right solution here, maybe was using the wrong search words.

A: Instead of re-inventing the wheel, you can use index() function combined with find() using "option:selected".
$("#cbx").change(function(){
  console.log($(this).find('option:selected').index());
});

Example fiddle;
https://jsfiddle.net/hbm4qrfm/1/

A: For what reason do you use id's, instead of value?
Having a list of id's seems kinda weird.
value="someVal"

https://jsfiddle.net/vhhc45dc/

A: You can get the selected options index like this
$("select").on('change', function(){
   console.log(this.selectedIndex)
})

here is the fiddle : https://fiddle.jshell.net/marwat/vL4sh11x/

A: You can use the index method like below
$("#cbx").change(function(){
   console.log($("#cbx :selected").index());
})

A: i found out that this way workes well:
$("#cbx").change(function(){

  let selecter = $(this).prop('selectedIndex');
  console.log(selecter + " THIS WORKS");

  if (selecter == 0) {
      console.log("0 selected");
  } else {
      console.log("1 selected");
  }
});

will try your answeres too & wich method is the newest?
thank you all for your help (sadly cant upvote so far)


text:
Q: Have the default partitions required by Windows 10 been cloned correctly (by Acronis True Image)? Backstory:
I had a 1TB HDD (Disk 0 in image) and wanted to got an SSD (500GB). I cloned the HDD to the SSD (it respectively cloned and downgraded the partitions too). I had previously was dual booting with Ubuntu and didn't know that there was a specific process to removing Ubuntu. Anyway after a multitude of issues, the last issue I got was Your PC/Device needs to be repaired. A required Device isn't connected or can't be accessed. Error code 0x0000225 (there was an issue with Winload.efi) running BCDBoot c:\Windows seemed to fix it  and I was able to boot. I then became somewhat curious about the partitions e.g if EFI has been cloned (via Acronis True Image) correctly (since I couldn't see it in diskpart until running the command just mentioned).
How can I verify if I have all the partitions required by the Windows 10 have been cloned (they are Windows 10 associated partitions e.g windows recovery etc) and if the partitions highlighted in red contain anything -- since they seem empty to me.

(The unallocated partition used to be the C: drive which I have now deleted).

A: If you can boot, then EFI has been cloned successfully.
As you have used the well-know Acronis tool for cloning, it seemed to have
done correctly the cloning into a smaller disk.
However, Acronis being a Windows product, it probably did a bad job on the Linux
partitions, which are perhaps the ones you have encircled in red.
If you would like to verify their contents, you can always enter Disk Management,
assign them drive-letters and try to have a look at the contents.
If the contents cannot be displayed, then the partition most likely is from Linux.
However, since you still have the original disk, you don't run a big risk if you
delete them one-by-one, rebooting after each delete.
At worst, you will need to repeat the cloning process that you already did,
this time leaving alone the problematic partition.


text:
Q: less scientific or clinical sounding yet reassuring term for a gas that's okay to breathe than "breathable gas"? In the first sentence of the SE question In simple terms, how does the way space suits manage breathable gas differ from how scuba gear does it? I explain:

I say "breathable gas" because what's in the tank can be a variety of mixtures and I don't know a single word for gas mixture you can safely breathe.

In the interest of biological and medical research and in deep sea diving and space exploration people have been give all kinds of gas mixtures with witch breathe to stay alive and conscious1. Sometimes pure oxygen, sometimes an oxygen-helium mix, etc.
The unifying feature would be to allow a proper amount of oxygen to the person's blood through the lungs, and otherwise "do no harm".
For water we have potable water. For air, we obviously have breathable gas.
But someone giving you a canister and saying "Here, inhale some of this. Trust me, it's breathable gas" doesn't sound reassuring.
Question: Is there a less scientific or clinical sounding yet reassuring term for a gas that's okay to breathe?
The phrase "fit to breathe air" (perhaps with some hyphenation) is not scientific or clinical and apparently means the same as breathable. But is there a less awkward construction for that or something different and yet obvious?

1here I'm excluding anesthetic mixutres or things that have other adverse or impairing effects (e.g. tear gas and worse).

A: While not a common term, the best description that encompasses both "normal" air as well as other gas mixtures that can safely sustain a person is breathing gas.
Wikipedia gives the following explanation:

A breathing gas is a mixture of gaseous chemical elements and
compounds used for respiration. Air is the most common, and only
natural, breathing gas. But other mixtures of gases, or pure oxygen,
are also used in breathing equipment and enclosed habitats such as
scuba equipment, surface supplied diving equipment, recompression
chambers, high-altitude mountaineering, high-flying aircraft,
submarines, space suits, spacecraft, medical life support and first
aid equipment, and anaesthetic machines.


text:
Q: jQuery trigger click on first child I'm trying to invoke a click on first .loader child when document is ready, but no success:
html:

Danny Boy

jQuery:
//Does not work
$('a.loader:first-child').bind('click');
$('a.loader:first-child').trigger('click');
$('a.loader:first-child').click();
//Works
$('a.loader:first-child').css("background", "red");

Any ideas why?
Update
Handler:
$('.loader').click(function(){
    var name=$(this).data("target");
    callVideo(name);
});

Update2
So the problem was that I had declared the :first-child action before the handler. I changed their places and everything ok

A: Did you define the handler before you initiated the triggered 'click'?
Here's the EXACT same code from your fiddle except I put the handler BEFORE the trigger
$(document).ready(function(){
    $('.loader').click(function(){
       alert($(this).data("target"));
    });
    $('.loader:first-child').click();
    $('.loader:first-child').css("background", "red");
});

This will pop the alert you're looking for

A: You need to have a handler to the click event...
$('a.loader:first-child').click(function(){
    alert('clicked');
});

$('a.loader:first-child').click();

Update:
You're handler was probably attached before the element was ready.
$(function(){
    $('.loader').click(function(){
        var name=$(this).data("target");
            callVideo(name);
    });
});


text:
Q: Excel inbuilt function I am in the process of converting a excel work book into a web based application.
The workbook performs many calculations based in input by the user. I am currently reverse engineering the formulae for these calculations.
The workbook contains many calls to the PV() function, however rather than pass implicit values, it passes either calculations or cells which are the result of other calculations to the function.
Is there any way in excel that I can see what the underlying values being passed to an inbuild function actually are?
Many Thanks

A: This is a link for how to debug formula errors
Hope it helps!

A: Mick
If I understand you correctly then if you click the cell with the formula in and then click the function icon in the formula bar (f x) then you will see what implicit values are being used.
Alternatively, if you select Tools > Formula Auditing > Evaluate Formula and then click the Evaluate button you can cycle through each input and it will resolve the underlying value.
Happy trails.


text:
Q: Color Comparison of two images using matlab Is it possible to compare the color of two images using Matlab if the two images are of different sizes?The problem that am facing is that, i want to detect the presence of a colored patch in an image?

A: You could just compare normalized histograms (i.e., like a color probability distribution). If the large and small images are semantically identical, then their normalized histograms are similar.
If they are semantically different, then their histograms will likely differ.

A: Do you have the image processing toolbox? If so, you might approach the problem by taking the images, splitting them into their component color channels, resizing the individual channels, and re-assembling them into resized color images. I wrote a program to do that a while ago, and I recall the code looking something like this:
function imout = ResizeRGB(imin,height,width)
imout = zeros(height,width,3);

iminR = imin(:,:,1);
iminG = imin(:,:,2);
iminB = imin(:,:,3);

imoutR = imresize(iminR, [height width]);
imoutG = imresize(iminG, [height width]);
imoutB = imresize(iminB, [height width]);

imout(:,:,1) = imoutR;
imout(:,:,2) = imoutG;
imout(:,:,3) = imoutB;

(Since I don't have the IPT handy at the moment, that program should be considered pseudocode even though it's more or less in correct matlab syntax. I can't run it without the IPT, so I can't tell if it's buggy or not.)
Once you resize the images so that they have common dimensions, the problem becomes identical to the problem of comparing colors for two images of equal dimensions.
On the other hand, if you have a picture of the patch and a picture that may contain the patch, you might consider using a binary mask to threshold the results of a cross-correlation (xcorr2 in the IPT). For more information on that approach, there's a tutorial on the MathWorks website: http://www.mathworks.com/products/demos/image/cross_correlation/imreg.html

A: This would be a bit crude, but you could crop your images to the minimum common size if this will be sufficient for your application:
A = imread("image1.jpg");
B = imread("image2.jpg");

rows = min(size(A,1), size(B,1));
cols = min(size(A,2), size(B,2));

croppedA = A(1:rows, 1:cols, :);
croppedB = B(1:rows, 1:cols, :);


text:
Q: Is it possible to annotate class constructor in Kotlin Clarification
This questions was asked before kotlin hit version 1.0. Language syntax in example is obsolete now, please follow official docs.

I'm playing with kotlin and spring DI.
I want to use constructor-based dependency injection, so I need to annotate the constructor.
I tried following approach:
Configuration
Import(javaClass<DataSourceConfig>())
public open class AppConfig(dataSource: DataSource) {
    private val dataSource: DataSource

    Autowired {
        this.dataSource = dataSource
    }
}

Configuration
public open class DataSourceConfig {

    Bean
    public open fun dataSource(): DataSource {
        // source omitted
    }

}
But it doesn't work. Is it even possible to annotate constructor in kotlin?
P.S. I'm using Kotlin M10.1 and Spring 4.1.4
UPDATE:
Annotating constructor is possible in kotlin. The problem was that it's not allowed to use constructor-based DI for @Configuration

A: Hrm, I think the syntax has changed radically since this question was posted. The current way (according to the docs) is to add the keyword constructor between your class name and arguments and annotate that, i.e.
public class AppConfig @Configuration constructor(dataSource: DataSource) {
    //...
}

A: Try to write:
Configuration
public open class AppConfig [Import(javaClass<DataSourceConfig>())] (dataSource: DataSource) {
//...
}

A: This syntax works for me:
Configuration
Import(javaClass<DataSourceConfig>())
public open class AppConfig {
  private val dataSource: DataSource

  Autowired constructor(dataSource: DataSource){
    this.dataSource = dataSource
  }
}


text:
Q: Do the messages with the same key but from different Kafka producers go to different partitions? I have two Kafka producers send messages to the same topic that has multiple partitions.
The messages with the same key K1 from the same producer PR1 always go to the same partition PA1, as expected.
The problem is the messages with the same key K1 from the other producer PR2 go to another partition PA2 while I expect they also go to PA1.
Doesn't Kafka keep the partition assignment across producers?
Is it related to the two producers use different Kafka client libraries?
Will it help if I set the two producers to use the same id?

A: How messages are assigned to partitions can be configured per-producer based on the configuration set with partitioner.class passed to the Producer API. There is an interface if you want to write your own.
This defaults to org.apache.kafka.clients.producer.internals.DefaultPartitioner, which uses a hash of the key to ensure that all messages for the same key end up in the same partition.

A: Thank you all for your comments and answers.
The cause is one of the Kafka libraries node-rdkafka uses a different default partitioner from the Java producer, https://github.com/Blizzard/node-rdkafka/issues/616.
Changing the partioner configuration to murmur2_random works.


text:
Q: How to transform multiple files with in sub-directories using XSLT? For example, there are chapter1 and chapter2 sub-folders inside parent folder, named:"S9ml". In both sub-directories:Chapter1 and Chapter2 has many .htmls. I want to transform all these .html' to remove white-spacing or Strip-white spacing. How do I do it? Please do help on how to run using Oxygen Editor?
<?xml version="1.0" encoding="UTF-8" ?>

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="html" indent="no" />

<xsl:template match="*">
   <xsl:copy>
      <xsl:copy-of select="@*" />
      <xsl:apply-templates />
   </xsl:copy>
</xsl:template>

<xsl:template match="comment()|processing-instruction()">
   <xsl:copy />
</xsl:template>

</xsl:stylesheet>

I tried this but in config transform, when I select the ${cfdu} getting, your access is denied.


text:
Q: google maps not showing all destination markers on map, only first and last I have a google map that displays my route correctly with all markers.
https://jsfiddle.net/az5tk8ns/17/
The destinations are hard coded in:
destinations = ["", "durban,KZN", " ixpop,kzn"]
I then have another function that produces an array of my addresses:
var addresses = [];
addresses.push('Durban, KZN');
addresses.push('izopo, KZN');`

I then set:
destinations = addresses

https://jsfiddle.net/az5tk8ns/19/
when doing this the map only shows the start and end destination markers, not my stop in the middle?
How can I use this method so I can pass my dynamically generated array of addresses to google maps and have it show each point in the journey?
complete google maps syntax:
$(document).ready(function() {

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var distancearray=[];
var addresses = [];
addresses.push('Durban, KZN');
addresses.push('izopo, KZN');

warehouse='ladysmith, kwa zulu natal';

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(-28.5710903, 26.0826083);
  var mapOptions = {
    zoom: 7,
    center: chicago
  };
  map = new google.maps.Map(document.getElementById('route_map_canvas'), mapOptions);
  directionsDisplay.setMap(map);
  calcRoute();
}
var origin = "johannesburg",
  destinations = addresses

service = new google.maps.DistanceMatrixService();

function calcRoute() {
  var waypts = [];
  for (var i = 1; i < destinations.length - 1; i++) {
    waypts.push({
      location: destinations[i],
      stopover: true
    });
  }
  var request = {
    origin: origin,
    destination: destinations[destinations.length - 1],
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var orig = document.getElementById("orig"),
        dest = document.getElementById("dest"),
        dist = document.getElementById("dist");

      orig.value = response.routes[0].legs[0].start_address;
      dest.value = response.routes[0].legs[0].end_address;
      var total_distance = 0.0;
      for (var i = 0; i < response.routes[0].legs.length; i++) {
        total_distance += response.routes[0].legs[i].distance.value;
        distancearray.push([response.routes[0].legs[i].distance.value]);
        //alert(distancearray);
      }
      dist.value = total_distance + " meters";
    }
  });

}
  initialize();

})

Thanks as always,

A: You have done everything correct except that there are only two destinations in the destinations variable which are used as start and end. There are zero waypoints in the directionsRequest object in the calcRoute() function.
This is the reason you are not getting any intermediate waypoints and hence no markers.
See this updated Fiddle where I have pushed one more location to the addresses variable(line number 11) and it is shown on the map correctly.
You can always do console.log(request); to see what request object you are passing to google.


text:
Q: Unity3d simulate GetAxis I'm trying to simulate the acceleration of Input.GetAxis("Horizontal") and Input.GetAxis("Vertical") based on where I'm touching the screen. So lets say I have an object in the middle of my screen called "middle_Object". What I'd like to do is if I touch to the right of the object, to simulate the gradual increase from 0 to 1 that Input.GetAxis("Horizontal") does and then if I put my finger to the left, it quickly goes back to 0 and then gradually decreases to -1. Basically transform the input.getaxis into a touch friendly version. Any ideas how I could do this?
Thanks!

A: It sounds like you need the magic of Lerp :) (linear interpolation)
Essentially, you want to work out if you're to the left or right (or up or down) of a reference point. In this case, let's say the centre of the screen. If you are, move toward either 1 or -1 accordingly.
On a touch screen, this means unless you add a 'deadzone', you will never be at zero, which is a pain, so you should also check if the distance from the centre is too small to care.
Then, you use the Lerp function to go from where you are now, to where you want to be, at the speed of your choice.
Here's some code with comments to show you how I'd do that.
// for this example, using the actual screen centre as our central point
// change this if you like :)
Vector2 myCentre = new Vector2( Screen.width/2, Screen.height/2 );
Vector2 touchPos = new Vector2( Screen.width/2, Screen.height/2 );

// change this to affect how quickly the number moves toward its destination
float lerpSpeed = 0.3f;

// set this as big or small as you want. I'm using a factor of the screen's size
float deadZone = 0.1f * Mathf.Min( Screen.width, Screen.height );

public void Update()
{
    Vector2 delta = (Vector2)Input.mousePosition - myCentre;

    // if the mouse is down / a touch is active...
    if( Input.GetMouseButton( 0 ) == true )
    {
        // for the X axis...
        if( delta.x > deadZone )
        {
            // if we're to the right of centre and out of the deadzone, move toward 1
            touchPos.x = Mathf.Lerp( touchPos.x, 1, lerpSpeed );
        }
        else if( delta.x < -deadZone )
        {
            // if we're to the left of centre and out of the deadzone, move toward -1
            touchPos.x = Mathf.Lerp( touchPos.x, -1, lerpSpeed );
        }
        else
        {
            // otherwise, we're in the deadzone, move toward 0
            touchPos.x = Mathf.Lerp( touchPos.x, 0, lerpSpeed );
        }

        // repeat for the Y axis...
        if( delta.y > deadZone )
        {
            touchPos.y = Mathf.Lerp( touchPos.y, 1, lerpSpeed );
        }
        else if( delta.y < -deadZone )
        {
            touchPos.y = Mathf.Lerp( touchPos.y, -1, lerpSpeed );
        }
        else
        {
            touchPos.y = Mathf.Lerp( touchPos.y, 0, lerpSpeed );
        }
    }
    else
    {
        // the mouse is up / no touch recorded, so move both axes toward 0
        touchPos.x = Mathf.Lerp( touchPos.x, 0, lerpSpeed );
        touchPos.y = Mathf.Lerp( touchPos.y, 0, lerpSpeed );
    }

    Debug.Log("TouchPos: " + touchPos );

}


text:
Q: 10 Gb JVM Heap Memory full but only 1Gb Field data cache We have a ES 1.6 cluster with 4 nodes used to store mostly logging data (~500 documents a second).
ES is configured with 10G of Heap but after numerous OutOfMemoryExceptions and stop-the-world GCs we limited the Field data cache to 10%.
My question is, why are all nodes' JVM constantly using ~9Gb Heap when field data (which i understand to be one of the primary users of Heap) is limited to 1Gb.
Some graphs:

It's worth pointing out our filter cache size is much smaller (~200Mb) and yes the aggressively limited Field data cache size does cause a lot of Field data cache evictions.
What else is using so much heap?
Thanks