text:
Q: Pandas: Finding the average of every next 10 data points in CSV I have a large datasets:
Time,   Value
01.01.2018 00:00:00.000,  5.1398
01.01.2018 00:01:00.000,  5.1298
01.01.2018 00:02:00.000,  5.1438
01.01.2018 00:03:00.000,  5.1228
01.01.2018 00:04:00.000,  5.1168
.... , ,,,,
31.12.2018 23:59:59.000,  6.3498

The data is a minute data from the first day of the year to the last day of the year
I want to use Pandas to find the average of every 5 days. For example:
Average from 01.01.2018 00:00:00.000 to 05.01.2018 23:59:59.000 for 05.01.2018
The next average will be from 02.01.2018 00:00:00.000 to 6.01.2018 23:59:59.000 for 06.01.2018
The next average will be from 03.01.2018 00:00:00.000 to 7.01.2018 23:59:59.000 for 07.01.2018
and so on...

For a given day, there are 24hours * 60minutes =  1440 data points. So I need to get the average of 1440 data points * 5 days = 7200 data points.

The final DataFrame will look like this:
Time,   Value
05.01.2018,  5.1398
06.01.2018,  5.1298
07.01.2018,  5.1438
.... , ,,,,
31.12.2018,  6.3498

The bottom line is to calculate the average of data from today to the past 5 days and the average value is shown as above.
I tried to iterate through Python loop but I wanted something better than we can do from Pandas.

A: IIUC
You want to do rolling mean then resample it daily.
Setup
df = pd.DataFrame(dict(
    Time=pd.date_range('2018-01-01', '2018-01-7 23:59', freq='12H')
)).assign(Value=lambda d: np.arange(len(d)))

df['Time'] = pd.to_datetime(df['Time'])
df = df.set_index('Time')

df

                 Value
Time
2018-01-01 00:00:00      0
2018-01-01 12:00:00      1
2018-01-02 00:00:00      2
2018-01-02 12:00:00      3
2018-01-03 00:00:00      4
2018-01-03 12:00:00      5
2018-01-04 00:00:00      6
2018-01-04 12:00:00      7
2018-01-05 00:00:00      8
2018-01-05 12:00:00      9
2018-01-06 00:00:00     10
2018-01-06 12:00:00     11
2018-01-07 00:00:00     12
2018-01-07 12:00:00     13

Solution
Interesting thing when you roll by time window is that Pandas doesn't know about when you've begun a full rolling period.  Consequentially, df.rolling('5D').mean() will start taking the mean immediately.  You can solve this by trimming the first 5 days (or 4 days) which we take take of after resampling daily.
df.rolling('5D').mean().resample('D').last().iloc[4:]

            Value
Time
2018-01-05    4.5
2018-01-06    6.5
2018-01-07    8.5

A: As you stated that you have data for every minute, i.e. there's always the same number of values per day (1440), then you can simply take the daily means and then the means of a 5-day rolling window on these daily means.
Example (value is running minute number in year, starting with 0):
s = pd.Series(pd.date_range('2018-01-01', '2018-12-31 23:59', freq='1T'))
df = pd.DataFrame(s.index.values, index=s, columns=['Value'])
df.groupby(df.index.floor('d'))['Value'].mean().rolling(5).mean().dropna()

Result:
2018-01-05      3599.5
2018-01-06      5039.5
2018-01-07      6479.5
2018-01-08      7919.5
                ...
2018-12-28    517679.5
2018-12-29    519119.5
2018-12-30    520559.5
2018-12-31    521999.5


text:
Q: Mockito ArgumentCaptor: How to capture Class and Object I've been trying to capture some types and I can't find a clean solution. I got this:
@Captor
private ArgumentCaptor<T extends DTO> targetMapperCaptor;

I'm using this Captor against a mapper using 2 types of params; a instance or a clazz.
As it's declared is only capturing those object that extends DTO, for capturing the classes:
@Captor
private ArgumentCaptor<Class> targetMapperCaptor;

Giving an example, having this code in the implementation:
mock.map(MyObject.class);
mock.map(new MyObject());

And having this in the test:
when(mock, times(2)).map(targetMapperCaptor.capture());

Will always throw an TooLittleActualInvocations (wanted 2 but got 1). If we remove the times(2), inside the targetMapperCaptor.getAllValues() there is only the value that matchs the type.
There is any way of declaring the ArgumentCaptor for capturing any param?
I've also unsuccessfully tried:
private ArgumentCaptor<?> targetMapperCaptor;
private ArgumentCaptor targetMapperCaptor;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sending Fileupload from HTTPClient to dotnet core Application i have a Server Application using dotnet core Controllers. There I have this Controller:
        [HttpPost]
        [RequestSizeLimit(100_000)]
        public async Task<IActionResult> xxx([FromForm] string name, [FromForm] string description, [FromForm] bool isprivate, [FromForm] IFormFile icon)
{
   ...
}

When i send the request from my Frontend in the Browser, it works fine, generating this request:
Frame 103: 2148 bytes on wire (17184 bits), 2148 bytes captured (17184 bits) on interface \Device\NPF_Loopback, id 2
Null/Loopback
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
Transmission Control Protocol, Src Port: 51141, Dst Port: 8001, Seq: 4701, Ack: 1792, Len: 2064
Hypertext Transfer Protocol
    POST /api/xxx/xxxHTTP/1.1\r\n
    Host: localhost:8001\r\n
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0\r\n
    Accept: application/json, text/plain, */*\r\n
    Accept-Language: de,en-US;q=0.7,en;q=0.3\r\n
    Accept-Encoding: gzip, deflate\r\n
    Content-Type: multipart/form-data; boundary=---------------------------20261806215495369501698203786\r\n
    Content-Length: 1127\r\n
    Origin: http://localhost:8001\r\n
    DNT: 1\r\n
    Connection: keep-alive\r\n
    Referer: http://localhost:8001/xxx\r\n
     [truncated]Cookie: .AspNetCore.Cookies=CfDJ8M_ELI8knopFkQ6zEqeCkgwDf43UGRqyyzwLWbKrkSuSRcmzqAPIcsi94bVzQFVWJB0NOGVRZVgzm4n7sf-0ox3SPK1ChgaqQuPRTogxdWzbJZPo1DCCi1TMI04RH4tmMj8rgv8EwDko5s1S2BNw0Owj8qL_-loCOz2VYU7wG3lVl5TIVavb46_nV6_Zr6MVdz
    \r\n
    [Full request URI: http://localhost:8001/api/xxx/xxx]
    [HTTP request 6/6]
    [Prev request in frame: 97]
    [Response in frame: 107]
    File Data: 1127 bytes
MIME Multipart Media Encapsulation, Type: multipart/form-data, Boundary: "---------------------------20261806215495369501698203786"
    [Type: multipart/form-data]
    First boundary: -----------------------------20261806215495369501698203786\r\n
    Encapsulated multipart part:
    Boundary: \r\n-----------------------------20261806215495369501698203786\r\n
    Encapsulated multipart part:
    Boundary: \r\n-----------------------------20261806215495369501698203786\r\n
    Encapsulated multipart part:
    Boundary: \r\n-----------------------------20261806215495369501698203786\r\n
    Encapsulated multipart part:  (image/png)
    Last boundary: \r\n-----------------------------20261806215495369501698203786--\r\n

Now i also have a Client written in C# using the HTTPClient, and i can't get the fileupload working.
This is my code there right now:
        public async Task<string?> Addxxx(string name, string description, bool isPrivate, byte[] ImageData, CancellationToken token)
        {
            var url = $"{Scheme}://{Address}:{Port}/api/xxx/xxx";
            var Content = new MultipartFormDataContent();
            var ImageContent = new ByteArrayContent(ImageData);
            ImageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
            Content.Add(ImageContent);
            var request = new HttpRequestMessage(HttpMethod.Post, url)
            {
                Content = new MultipartFormDataContent()
                {
                    {
                        new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
                        {
                            new KeyValuePair<string, string>("name" , name),
                            new KeyValuePair<string, string>("description" , description),
                            new KeyValuePair<string, string>("isprivate" , isPrivate.ToString()),
                        })
                    },
                    {Content }
                }
            };
            request.Headers.Add("Accept", "multipart/form-data");
            request.Headers.Add("User-Agent", UserAgent);
            request.Headers.Add("Cookie", Cookies);
            var response = await HttpClient.SendAsync(request, token);

            if (!response.IsSuccessStatusCode)
                return null;
            ...
        }

However, this always gets a bad request.
This is the request generated:
Frame 16: 1523 bytes on wire (12184 bits), 1523 bytes captured (12184 bits) on interface \Device\NPF_Loopback, id 2
Null/Loopback
Internet Protocol Version 4, Src: 192.168.2.101, Dst: 192.168.2.101
Transmission Control Protocol, Src Port: 51121, Dst Port: 8001, Seq: 1394, Ack: 1020, Len: 1439
Hypertext Transfer Protocol
    POST /api/xxx/xxxHTTP/1.1\r\n
    Host: 192.168.2.101:8001\r\n
    Accept: multipart/form-data\r\n
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36\r\n
     [truncated]Cookie: .AspNetCore.Cookies=CfDJ8M_ELI8knopFkQ6zEqeCkgx2TK33iweuVbSNkdR_HNs5nC6EEy6zFxnuwpIovyH9WenSzaVCDgW3VWk0BJJ7cDnfdnQ5W_o98sJvaVtiVmPk3JB8e5bySGdcoRN6NwIl27mqLMl89Kt5hnsrq5Jps9Q3kJ1XSk5kpMciycb9AijtG9N_tqqqhRbV9EvbQc0CUU
    Request-Id: |10c9eb89-46f0038fdc2e3b2d.\r\n
    Content-Type: multipart/form-data; boundary="4265ae7c-56da-4811-b646-fc1123794472"\r\n
    Content-Length: 576\r\n
    \r\n
    [Full request URI: http://192.168.2.101:8001/api/xxx/xxx]
    [HTTP request 3/3]
    [Prev request in frame: 10]
    [Response in frame: 20]
    File Data: 576 bytes
MIME Multipart Media Encapsulation, Type: multipart/form-data, Boundary: "4265ae7c-56da-4811-b646-fc1123794472"
    [Type: multipart/form-data]
    First boundary: --4265ae7c-56da-4811-b646-fc1123794472\r\n
    Encapsulated multipart part:  (application/x-www-form-urlencoded)
    Boundary: \r\n--4265ae7c-56da-4811-b646-fc1123794472\r\n
    Encapsulated multipart part:  (multipart/form-data)
    Last boundary: \r\n--4265ae7c-56da-4811-b646-fc1123794472--\r\n

I tried a lot and am a bit lost in how to Send the request from the Client...
Can someone point me in the right direction on how to send the image together with the other POST data?


text:
Q: How to extract predictors from parsnip fit object I have the following prediction model:
library(tidymodels)

data(ames)

set.seed(4595)
data_split <- initial_split(ames, strata = "Sale_Price", prop = 0.75)

ames_train <- training(data_split)
ames_test  <- testing(data_split)

rec <- recipe(Sale_Price ~ ., data = ames_train)
norm_trans <- rec %>%
  step_zv(all_predictors()) %>%
  step_nzv(all_predictors())  %>%
  step_corr(all_numeric_predictors(), threshold = 0.1)

# Preprocessing
norm_obj <- prep(norm_trans, training = ames_train)
rf_ames_train <- bake(norm_obj, ames_train) %>%
  dplyr::select(Sale_Price, everything()) %>%
  as.data.frame()
dim(rf_ames_train )

rf_xy_fit <- rand_forest(mode = "regression") %>%
  set_engine("ranger") %>%
  fit_xy(
    x = rf_ames_train,
    y = log10(rf_ames_train$Sale_Price)
  )

Note that after preprocessing step the number of features are reduced from 74 to 33.
dim(rf_ames_train )
# 33

Currently, I have to explicitly pass the predictors in the function:
preds <- colnames(rf_ames_train)
my_pred_function <- function (fit = NULL, test_data = NULL, predictors = NULL) {

  test_results <- test_data %>%
    select(Sale_Price) %>%
    mutate(Sale_Price = log10(Sale_Price)) %>%
    bind_cols(
      predict(fit, new_data = ames_test[, predictors])
    )
  test_results

}

my_pred_function(fit = rf_xy_fit, test_data = ames_test, predictors = preds)

Shown as predictors = preds in the function call above.
In practice, I have to save the rf_xy_fit and preds as two RDS files, then read them again. This is prone to error and troublesome.
I would like to by-pass this explicit passing. Is there a way I can extract that from rf_xy_fit directly?

A: This is a case where you would benefit from using the workflows package. This allows you to combine the preprocessing code with the model fitting code
library(tidymodels)

data(ames)

set.seed(4595)
# Notice how I did log transformation before doing the splitting to assure that it is not on both testing and training data sets.

ames <- ames %>%
  mutate(Sale_Price = log10(Sale_Price))

data_split <- initial_split(ames, strata = "Sale_Price", prop = 0.75)

ames_train <- training(data_split)
ames_test  <- testing(data_split)

rec <- recipe(Sale_Price ~ ., data = ames_train)
norm_trans <- rec %>%
  step_zv(all_predictors()) %>%
  step_nzv(all_predictors())  %>%
  step_corr(all_numeric_predictors(), threshold = 0.1)

rf_spec <- rand_forest(mode = "regression") %>%
  set_engine("ranger")

rf_wf <- workflow() %>%
  add_recipe(norm_trans) %>%
  add_model(rf_spec)

rf_fit <- fit(rf_wf, ames_train)

predict(rf_fit, new_data = ames_train)
#> # A tibble: 2,197 × 1
#>    .pred
#>    <dbl>
#>  1  5.09
#>  2  5.12
#>  3  5.01
#>  4  4.99
#>  5  5.12
#>  6  5.07
#>  7  4.90
#>  8  5.09
#>  9  5.13
#> 10  5.08
#> # … with 2,187 more rows

Created on 2022-11-21 with reprex v2.0.2

A: Supplementing Emils answer based on your comment...
Keep in mind that most R modeling functions will expect the original feature set, even if some of them are not at all used. This is a by-product of R's formula/model.matrix() machinery.
For recipes, it depends on which steps that you use.
You could refit the final model without them but you might not get exactly the same model. In many cases, the process to getting to the subset of features depends on how many were originally passed.
I'm working on a tidymodels api for this but caret has one to get the list of predictors that were actually used by the model. See the example:
library(caret)
#> Loading required package: ggplot2
#> Loading required package: lattice
library(tidymodels)

tidymodels_prefer()
options(pillar.advice = FALSE, pillar.min_title_chars = Inf)

data(ames)

set.seed(4595)

ames <- ames %>%
  mutate(Sale_Price = log10(Sale_Price))

data_split <- initial_split(ames, strata = "Sale_Price", prop = 0.75)

ames_train <- training(data_split)
ames_test  <- testing(data_split)

rec <- recipe(Sale_Price ~ ., data = ames_train)
norm_trans <- rec %>%
  step_zv(all_predictors()) %>%
  step_nzv(all_predictors())  %>%
  step_corr(all_numeric_predictors(), threshold = 0.1)

rf_spec <- rand_forest(mode = "regression") %>%
  set_engine("ranger")

rf_wf <- workflow() %>%
  add_recipe(norm_trans) %>%
  add_model(rf_spec)

rf_fit <- fit(rf_wf, ames_train)

# get predictor set:
rf_features <-
  rf_fit %>%
  extract_fit_engine() %>%
  predictors()  #<- the caret funciton

head(rf_features)
#> [1] "MS_SubClass"  "MS_Zoning"    "Lot_Frontage" "Lot_Shape"    "Lot_Config"
#> [6] "Neighborhood"

# You get an error here:
ames_test %>%
  select(all_of(rf_features)) %>%
  predict(rf_fit, new_data = .)
#> Error in `validate_column_names()`:
#> ! The following required columns are missing: 'Lot_Area',
#> 'Street', 'Alley', 'Land_Contour', 'Utilities', 'Land_Slope',
#> 'Condition_2', 'Year_Built', 'Year_Remod_Add', 'Roof_Matl',
#> 'Mas_Vnr_Area', 'Bsmt_Cond', 'BsmtFin_SF_1', 'BsmtFin_Type_2',
#> 'BsmtFin_SF_2', 'Bsmt_Unf_SF', 'Total_Bsmt_SF', 'Heating',
#> 'First_Flr_SF', 'Second_Flr_SF', 'Gr_Liv_Area', 'Bsmt_Full_Bath',
#> 'Full_Bath', 'Half_Bath', 'Bedroom_AbvGr', 'Kitchen_AbvGr',
#> 'TotRms_AbvGrd', 'Functional', 'Fireplaces', 'Garage_Cars',
#> 'Garage_Area', 'Wood_Deck_SF', 'Open_Porch_SF', 'Enclosed_Porch',
#> 'Three_season_porch', 'Screen_Porch', 'Pool_Area', 'Pool_QC',
#> 'Misc_Feature', 'Misc_Val', 'Mo_Sold', 'Latitude'.

Created on 2022-11-21 by the reprex package (v2.0.1)
This error comes from the workflows package but the underlying modeling package would also error.


text:
Q: will the webserver [IIS] possibly know whether a request is an AJAX request or a Normal one will any webserver [IIS possibly] know whether a request is an AJAX request or a Normal one.

A: If you are using native XmlHttpRequests then there is no difference between this request and once generated by visiting a page or submitting a form. If you use jQuery to create the AJAX request then is adds a request header X-Requested-With: XMLHttpRequest. This header could be used to distinguish AJAX and non-AJAX requests.

A: Some (most?) frameworks can send a custom header, but, really, an ajax request is just the same as a "normal" request from the point of view of the server.
If you use curl, wget, telnet, or a program you write yourself, then the web server handles the request the same way - at the end of the day, it's all HTTP.

A: Firebug can show you what is being sent to the server from both types of requests, try it out.

A: Possibly, it is not the webserver that can distinguish, but the server side code might be able to distinguish. If you are talking about ASP.NET and AJAX, then ScriptManager.IsInAsyncPostBack can be used to find whether a postback is from AJAX or not.

A: The easiest way for the receiving page to 'know' would be to send a query string parameter.  This isn't 100% safe though.


text:
Q: MVVM. Can i implement logic code in behavior or should i put it whole to binded command in VM? I have behavior for entry completed command, that validates data inside of entry, logic for that i keep in ViewModel. But also, when i complete entry i need to change the focus to the next entry (next entry does not have a x:Name, because it is inside of the DataTemplate). To change focus i need object of the next entry, and i finding that object via his parent right in the Behavior file, not in VM. It is correctly way to do this in MVVM, or i should pass entry object via parameter to VM and find his parent and then next entry in VM?
Behavior:
using System.Windows.Input;
using Xamarin.Forms;

namespace RollPositioningMobile.ViewModels.Behaviors
{
    public class EntryCompletedBehavior : Behavior<Entry>
    {
        protected override void OnAttachedTo(Entry bindable)
        {
            base.OnAttachedTo(bindable);

            AssociatedObject = bindable;

            bindable.BindingContextChanged += Bindable_BindingContextChanged;
            bindable.Completed += Bindable_Completed;
        }
        protected override void OnDetachingFrom(Entry bindable)
        {
            base.OnDetachingFrom(bindable);

            bindable.BindingContextChanged -= Bindable_BindingContextChanged;
            bindable.Completed -= Bindable_Completed;

            AssociatedObject = null;
        }

        private void Bindable_BindingContextChanged(object sender, System.EventArgs e)
        {
            OnBindingContextChanged();
        }
        private void Bindable_Completed(object sender, System.EventArgs e)
        {
            if (Command == null) return;

            Entry entry = (Entry)sender;
            Grid circularEntriesGrid;

            //If this handler was invoked from the RequiredValueEntry,
            //focus on the next Entry mechanic is different
            if (entry.TabIndex == 0)
            {
                //First we need to define the main Grid,
                //and then find subgrid inside of the main
                Grid mainGrid = (Grid)entry.Parent.Parent;
                circularEntriesGrid = mainGrid.FindByName<Grid>("CircularEntriesGrid");
            }
            else
            {
                //Get the Frame parent and then the Grid parent of the Entry
                circularEntriesGrid = (Grid)entry.Parent.Parent;

                //Check for last entry
                if (circularEntriesGrid.Children.Count == entry.TabIndex)
                    return;
            }

            //Execution of the input data validation commands
            if (Command.CanExecute(entry.TabIndex))
                Command.Execute(entry.TabIndex);

            //Set focus on the next Entry
            if ((bool)CommandParameter)
            {
                var nextEntryFrame = (Frame)circularEntriesGrid.Children[entry.TabIndex];
                var nextEntry = (Entry)nextEntryFrame.Content;
                nextEntry.Focus();
            }
            else
            {
                entry.Focus();
            }
        }

        protected override void OnBindingContextChanged()
        {
            base.OnBindingContextChanged();
            BindingContext = AssociatedObject.BindingContext;
        }

        public Entry AssociatedObject { get; private set; }

        public static readonly BindableProperty CommandProperty =
                BindableProperty.Create("Command", typeof(ICommand), typeof(EntryCompletedBehavior), null);
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        public static readonly BindableProperty CommandParameterProperty =
            BindableProperty.Create("CommandParameter", typeof(object), typeof(EntryCompletedBehavior), null);
        public object CommandParameter
        {
            get { return GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }
    }
}

VM part:
public ICommand EntryCompletedCommand { get; protected set; }
    void EntryCompleted(object param)
    {
        var entryId = (int)param;

        //Validating required value
        if (entryId == 0)
        {
            RequiredValueIsValid = true;
            if (RequiredValue <= 0)
            {
                Application.Current.MainPage.DisplayAlert("Error", $"Required value cannot be equals to {RequiredValue}", "OK");
                RequiredValueIsValid = false;
            }
            return;
        }

        //Validating actual values
        var entry = ActualValues[entryId - 1];
        var value = entry.Value;
        if (value < 0 || Math.Abs(value - RequiredValue) > Measurment.MaxOffset)
        {
            entry.Value = entry.OldValue;
            Application.Current.MainPage.DisplayAlert("Error", $"The actual and the required value should not differ more than {Measurment.MaxOffset}", "OK");
            entry.IsValid = false;
            return;
        }
        entry.IsValid = true;
        RequiredValueIsValid = true;
        entry.OldValue = entry.Value;
    }

A:
Can i implement logic code in behavior or should i put it whole to binded command in VM?

Since you had used MVVM , it would better to handle the logic in ViewModel . We always do some customization  of the element itself .
In your case , it is necessary to pass the entry as params to ViewModel . You could binding the value of IsFocused to the property of Model and handle it directly in VM .
Here is a similar thread and I had provided a whole solution .Hope it will be helpful to you  .


text:
Q: How to silence 'Expected a type' Xcode compiler warnings? Is there any way to silence Xcode compiler warnings because of unknown types like with @class?
I defined a type in a single .h file that can be reused throughout the app:
#ifndef Apsiape_InterfaceDefinitions_h
#define Apsiape_InterfaceDefinitions_h

#define COLOR_ALERT_RED [UIColor colorWithRed:1 green:0.3 blue:0.3 alpha:1]
...

typedef enum  {
    BYEdgeTypeNone = 0,
    BYEdgeTypeTop,
    BYEdgeTypeLeft,
    BYEdgeTypeBottom,
    BYEdgeTypeRight
} BYEdgeType;

#endif

And one of my classes uses the BYEdgeType type for a custom protocol in the .h file:
#import <UIKit/UIKit.h>

@protocol BYPullScrollViewDelegate <NSObject>

- (void)pullScrollView:(UIScrollView*)pullScrollView didScrollToPage:(NSInteger)page;
- (void)pullScrollView:(UIScrollView*)pullScrollView didDetectPullingAtEdge:(BYEdgeType)edge;

@end

I want my InterfaceDefinitions.h file to be in the .m file of my class, but if I don't import it in the .m of the class Xcode (of course) complains that it "Expected a type" (BYEdgeType). How can I silence this warning @class-style?
Thanks in advance

A: Is the protocol defined in a header (.h) file? If so, to use enums and #defines in the .h file, you'll have to import the header with those definitions in that .h file.


text:
Q: Syslog server not displaying sonic wall firewall logs We have configured syslog in sonic wall firewal... in firewall packets are forwarding to syslog server that is centos
but in the syslog server we are unable to  findout where the logs have been stored.

A: Sounds like you want to know where CentOs stores the syslog messages?  If so, check:
/var/log
/var/log/messages


text:
Q: Spring Boot - @Value annotation doesn't work I try to create mail service using SmtpAuthenticator. The component is started correctly but null values are in username and password fields. Why is it?
@Component
public class SmtpAuthenticator extends Authenticator {

    private static final Logger LOG =
    LogManager.getLogger(SmtpAuthenticator.class.getSimpleName());

    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    public SmtpAuthenticator() {
        LOG.info(SmtpAuthenticator.class.getSimpleName() + " started...");
        LOG.debug("username=" + username);
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            LOG.debug("Username and password are correct...");
            return new PasswordAuthentication(username, password);
        }
    LOG.error("Not correct mail login data!");
    return null;
    }
}

A: You guessed it right, the values will get injected only after the objects gets instantiated; because the spring container cannot set a property of something which doesn't exist yet. So while in constructer, those fields will still be null. One solution is, either

*

*Switch to constructer Injection instead of setter Injection (YMMV, havnt tested your usecase)

Or

*Replace the constructor with a method annotated with @PostConstruct. This method will be executed after the injection process.

for example
@Component
public class SmtpAuthenticator extends Authenticator {
    private static final Logger LOG =
    LogManager.getLogger(SmtpAuthenticator.class.getSimpleName());

    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    @PostConstruct
    public void init() {
        LOG.info(SmtpAuthenticator.class.getSimpleName() + " started...");
        LOG.debug("username=" + username);
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            LOG.debug("Username and password are correct...");
            return new PasswordAuthentication(username, password);
        }
    LOG.error("Not correct mail login data!");
    return null;
    }
}

A: Moved no argument constructor code to PostConstruct has done the trick for me. As it'll keep default bean loading workflow intact.

Try this solution. https://stackoverflow.com/a/72547797/2002804


text:
Q: These quotient spaces are homeomorphic? If $h:A\to B$ is a homeomorphism, where the subset $A_1$ of $A$ is homeomorphic to a subset $B_1$ of $B$. How can I prove that the quotient spaces $A/A_1$ and $B/B_1$ are homeomorphic?
Thanks

A: We are given maps $h: A \rightarrow B$, $g: B \rightarrow A$ such that $gh = id_A, hg = id_B$ (namely take $g = h^{-1}$), $h(A_1) = B_1$.
To give a map out of $A/A_1$ is to give a map out of $A$ which sends $A_1$ to a point: consider $A \xrightarrow{h} B \rightarrow B/B_1$, this induces $h': A/A_1 \rightarrow B/B_1$, similarly we get $g': B/B_1 \rightarrow A/A_1$, one observes that $h', g'$ are by construction inverse, as desired.
I think the claim is false if they're independently homeomorphic. Consider $A = B = [0,1]$, $A_1 = \{0,1\}, B_1 = \{1/3, 2/3\}$. Then $A/A_1$ is just $S^1$, but $B/B_1$ looks like:

Now if I pluck out $1/3 = 2/3$ from $B/B_1$ I get something with 3 connected components, but if you take out any point from $S^1$, you get just 1 connected component.


text:
Q: Very low Rsquared of Lasso on Test sample. But very low MSE too? I am not sure what is going wrong here. I did the following :
#Running Lasso:
from sklearn import linear_model
lasso=linear_model.LassoCV(max_iter=2000,cv=10,normalize=False)
lasso.fit(tourism_train_X,tourism_train_Y)
lasso.alpha_
scores=np.zeros((100,1))
scores[:,0]=np.mean(lasso.mse_path_,axis=1)
scores=np.sort(scores)
lasso.coef_

Before this, this is how I split the dataset and the pre-processing involved.
import numpy as np
from sklearn.cross_validation import train_test_split
tourism_train_X,tourism_test_X,tourism_train_Y,tourism_test_Y=train_test_split(tourism_train, tourism_Y, test_size=0.20, random_state=42)

Encoding the categorical variable (only one):
# Encoding categorical variables
from sklearn import preprocessing
tourism_train_X=preprocessing.Imputer(missing_values='NaN', strategy='mean', axis=0).fit_transform(tourism_train_X)
tourism_test_X=preprocessing.Imputer(missing_values='NaN', strategy='mean', axis=0).fit_transform(tourism_test_X)

tourism_train_X=preprocessing.OneHotEncoder(categorical_features=[1],sparse=False).fit_transform(tourism_train_X)
tourism_test_X=preprocessing.OneHotEncoder(categorical_features=[1],sparse=False).fit_transform(tourism_test_X)

Standardising the variables both in train and test set:
# Standardising the variables
tourism_train_X=preprocessing.scale(tourism_train_X)
tourism_test_X=preprocessing.scale(tourism_test_X)

If you see I am doing a 10 fold cross validation to choose best lasso coeff.
Now when I check it on my test set. I get this.
# Test error of Lasso:
from sklearn.metrics import mean_squared_error
mse_test_tourism=mean_squared_error(tourism_test_Y,lasso.predict(tourism_test_X))
# R^2 of Test sample
rsquared_test_tourism=lasso.score(tourism_test_X,tourism_test_Y)
print("The MSE on Test data is :", mse_test_tourism)
print("The R^2 on Test data is:", rsquared_test_tourism)

It gives this:
The mse is very low, but Rsquared is way less.
('The MSE on Test data is :', 0.0046515559443549301)
('The R^2 on Test data is:', 0.03861779182108882

What does this mean? According to this the model doesn't explain anything if we look at Rsquared. But MSE of the model on test dataset is very low.
Any answers? as a note, my target variable (Y) is a log transformed variable.

A: Essentially, you're comparing the wrong things.
The Mean Squared Error tells you the average error of each prediction. It's sensitive to the units you're predicting, so since you're predicting a log transformed variable, it's not surprising that the mean squared error would be small. To compare to R squared, you need to look at the Mean Squared Error as a proportion of the variance in Y (which is essentially the formula for R squared, turned around a bit).
R squared is the proportion of variance explained - so it takes into account the variance of your dependent variable, as well as the average error, to get the percentage of variance that isn't error (essentially).
What is probably happening in your data is that you have very low variance, such that your mean squared error is still pretty large in comparison to this variance, and that your model doesn't explain a lot (as shown by the low R squared).
This post may be helpful to give a more mathematically complete answer:
What is the difference between "coefficient of determination" and "mean squared error"?


text:
Q: Symfony2 triple entity forms i'm trying to realize a form that show a list of exercices and under each one of them, the input texte for the logged in user to answer ,i don't need embeded forms because i will not change the exercice text i will just save the responses for each exercice of the given exam and user.
in my database i have three tables :exam that has many exercices and table exercice and table response that has the following fields (user, exercice, response, date)
please am stuck help me !

A: You can insert a form when displaying your exercices unter each of them and create a route & controller for this form but the router/controller will receive as paramater the Id or Code of your exercice so that when it save the response it set directly it's exercice.
So you must get a ManyToOne relation between Exercice & Reponse.
Just tell me if i've not understood (my english is very poor )

A: I thik you must add dynamicly your form into the template not send via controller but the action of each form will be a controller route that will yse your POST data to edit exercice
route_name:
     pattern: /patten/{id} #hier id is the id of the exercice
     defaults: { _controller:.....:Response }

ResponseAction(Exercice $e}
    {
           In this controller you get the POst datas and you can add your response on the
           article
}
Twig:
 {{ exercice.content }} {# an example #}
 {# a form that you will normaly generate will jQuery or another of your choice #}
 <form action="{{ path('route_name',{'id':exercice.id}) }}" method="POST">
      //
      your fields  ...
  </form>


text:
Q: Checking the stdin buffer if it's empty I am trying to read a number character with character, but I don't know if the stdin buffer is empty or not.
My first solution whas to look for \n character in stdin buffer, but this is no good if I what to enter multiple numbers separated by " ".
How can I know if in stdin buffer I have characters or not?
I need to do it in C and to be portable.

A: For anyone who comes here from google – easy select solution to check stdin emptyness:
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(STDIN_FILENO, &readfds);
fd_set savefds = readfds;

struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;

int chr;

int sel_rv = select(1, &readfds, NULL, NULL, &timeout);
if (sel_rv > 0) {
  puts("Input:");
  while ((chr = getchar()) != EOF) putchar(chr);
} else if (sel_rv == -1) {
  perror("select failed");
}

readfds = savefds;

Needs unistd.h, stdlib.h and stdio.h.
Explanation can be found here.
UPD:
Thanks DrBeco for noticing that select returns -1 on error -- error handling was added.
Actually, select returns:

*

*the number of ready descriptors that are contained in the descriptor sets

*0 if the time limit expires

*-1 if an error occurred (errno would be set)

A: There are several soutions:
poll or select with timeout of 0 - these would return immediately and result is either -1 with errno EAGAIN if no data available or number of descriptors with data (one, since you're checking only stdin).
ioctl is a swiss army knife of using descriptors. The request you need is I_NREAD:
if (ioctl(0, I_NREAD, &n) == 0 && n > 0)
    // we have exactly n bytes to read

However the correct solution is to read everything you got (using scanf) as a line, then process the result - and this works good enough with sscanf:
char buf[80]; // large enough
scanf("%79s", buf); // read everything we have in stdin
if (sscanf(buf, "%d", &number) == 1)
    // we have a number

... as long as you properly handle re-reading, strings that are longer than your buffer, and other real-life complications.

A: I inspired from this as referenced by @stek29's post on this page and prepared a simple example as follows:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    fd_set readfds;
    FD_ZERO(&readfds);

    struct timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = 0;

    char message[50];

    while(1)
    {
        FD_SET(STDIN_FILENO, &readfds);

        if (select(1, &readfds, NULL, NULL, &timeout))
        {
            scanf("%s", message);
            printf("Message: %s\n", message);
        }

        printf("...\n");
        sleep(1);
    }

    return(0);
}

A: int number=-1;   //-1 is default std for error;
int success=0;   //will serve as boolean (0==FALSE;1==TRUE)
char buf[BUFFER_SIZE];   // Define this as convinient (e.g. #define BUFFER_SIZE 100)
char *p=buf;   //we'll use a pointer in order to preserve input, in case you want to use it later

    fgets(buf,BUFFER_SIZE,stdin);  //use fgets() for security AND to grab EVERYTHING from stdin, including whitespaces

    while(*p!='\0'){   //parse the buf
        if(sscanf(p,"%d",&number)==1){   //at each char position try to grab a valid number format,
            success=1;                   //if you succeed, then flag it.
            break;
        }

        p++;   //if you don't succeed, advance the pointer to the next char position
     }   //repeat the cycle until the end of buf (string end char =='\0')

    if (success)
        printf(">> Number=%d at position nº %d.",number,(int)(p-buf));   //you get the position by calculating the diff
                                                                    //between the current position of the p and the
                                                                    //beginning position of the buf
    else {
    // do whatever you want in case of failure at grabbing a number
    }

A: There are many ways to check if stdin has input available. The most portable ones are, in that order: select, fcntl and poll.
Here some snippets on how to do it, case by case.
#include <stdio.h> /* same old */
#include <stdlib.h> /* same old */
#include <time.h> /* struct timeval for select() */
#include <unistd.h> /* select() */
#include <poll.h> /* poll() */
#include <sys/ioctl.h> /* FIONREAD ioctl() */
#include <termios.h> /* tcgetattr() and tcsetattr() */
#include <fcntl.h> /* fnctl() */

#define BUFF 256

int chkin_select(void);
int chkin_poll(void);
int chkin_ioctl(void);
int chkin_fcntl(void);
int chkin_termios(void);

/*
  Simple loops to test varios options of non-blocking test for stdin
*/

int main(void)
{
    char sin[BUFF]="r";

    printf("\nType 'q' to advance\nTesting select()\n");
    while(sin[0]++ != 'q')
    {
        while(!chkin_select())
        {
            printf("nothing to read on select()\n");
            sleep(2);
        }
        fgets(sin, BUFF, stdin);
        printf("\nInput select(): %s\n", sin);
    }

    printf("\nType 'q' to advance\nTesting poll()\n");
    while(sin[0]++ != 'q')
    {
        while(!chkin_poll())
        {
            printf("nothing to read poll()\n");
            sleep(2);
        }
        fgets(sin, BUFF, stdin);
        printf("\nInput poll(): %s\n", sin);
    }

    printf("\nType 'q' to advance\nTesting ioctl()\n");
    while(sin[0]++ != 'q')
    {
        while(!chkin_ioctl())
        {
            printf("nothing to read ioctl()\n");
            sleep(2);
        }
        fgets(sin, BUFF, stdin);
        printf("\nInput ioctl(): %s\n", sin);
    }

    printf("\nType 'q' to advance\nTesting fcntl()\n");
    while(sin[0]++ != 'q')
    {
        while(!chkin_fcntl())
        {
            printf("nothing to read fcntl()\n");
            sleep(2);
        }
        fgets(sin, BUFF, stdin);
        printf("\nInput fcntl: %s\n", sin);
    }

    printf("\nType 'q' to advance\nTesting termios()\n");
    while(sin[0]++ != 'q')
    {
        while(!chkin_termios())
        {
            printf("nothing to read termios()\n");
            sleep(2);
        }
        fgets(sin, BUFF, stdin);
        printf("\nInput termios: %s\n", sin);
    }

    return EXIT_SUCCESS;
}

/*
   select() and pselect() allow a program to monitor multiple file
   descriptors, waiting until one or more of the file descriptors become
   "ready" for some class of I/O operation (e.g., input possible).  A
   file descriptor is considered ready if it is possible to perform a
   corresponding I/O operation (e.g., read(2) without blocking, or a
   sufficiently small write(2)).
 */
int chkin_select(void)
{
    fd_set rd;
    struct timeval tv={0};
    int ret;

    FD_ZERO(&rd);
    FD_SET(STDIN_FILENO, &rd);
    ret=select(1, &rd, NULL, NULL, &tv);

    return (ret>0);
}

/*  poll() performs a similar task to select(2): it waits for one of a
       set of file descriptors to become ready to perform I/O.

       The set of file descriptors to be monitored is specified in the fds
       argument, which is an array of structures of the following form:

           struct pollfd {
               int   fd;         // file descriptor //
               short events;     // requested events //
               short revents;    // returned events //
           };

       The caller should specify the number of items in the fds array in
       nfds.
*/
int chkin_poll(void)
{
    int ret;
    struct pollfd pfd[1] = {0};

    pfd[0].fd = STDIN_FILENO;
    pfd[0].events = POLLIN;
    ret = poll(pfd, 1, 0);

    return (ret>0);
}

/*
    The ioctl(2) call for terminals and serial ports accepts many
       possible command arguments.  Most require a third argument, of
       varying type, here called argp or arg.

       Use of ioctl makes for nonportable programs.  Use the POSIX interface
       described in termios(3) whenever possible.
*/
int chkin_ioctl(void)
{
    int n;
    ioctl(STDIN_FILENO, FIONREAD, &n);
    return (n>0);
}

/*
       fcntl() performs one of the operations described below on the open
       file descriptor fd.  The operation is determined by cmd.

       fcntl() can take an optional third argument.  Whether or not this
       argument is required is determined by cmd.  The required argument
       type is indicated in parentheses after each cmd name (in most cases,
       the required type is int, and we identify the argument using the name
       arg), or void is specified if the argument is not required.

       Certain of the operations below are supported only since a particular
       Linux kernel version.  The preferred method of checking whether the
       host kernel supports a particular operation is to invoke fcntl() with
       the desired cmd value and then test whether the call failed with
       EINVAL, indicating that the kernel does not recognize this value.
*/
int chkin_fcntl(void)
{
    int flag, ch;

    flag = fcntl(STDIN_FILENO, F_GETFL, 0); /* save old flags */
    fcntl(STDIN_FILENO, F_SETFL, flag|O_NONBLOCK); /* set non-block */
    ch = ungetc(getc(stdin), stdin);
    fcntl(STDIN_FILENO, F_SETFL, flag); /* return old state */

    return (ch!=EOF);
}

/*
 The termios functions describe a general terminal interface that is provided to control asynchronous communications ports.
 This function doesn't wait for '\n' to return!
 */
int chkin_termios(void)
{
    struct termios old, new;
    int ch;

    tcgetattr(STDIN_FILENO, &old); /* save settings */

    new = old;
    new.c_lflag &= ~ICANON; /* non-canonical mode: inputs by char, not lines */
    new.c_cc[VMIN] = 0; /* wait for no bytes at all */
    new.c_cc[VTIME] = 0; /* timeout */
    tcsetattr(STDIN_FILENO, TCSANOW, &new); /* new settings */

    ch = ungetc(getc(stdin), stdin); /* check by reading and puking it back */

    tcsetattr(STDIN_FILENO, TCSANOW, &old); /* restore old settings */
    return (ch!=EOF);
}

Try to avoid ioctl and termios, they are too specific, or too low-level. Also, you can't really use feof in a meaningful way with stdin or any FIFO for that matter. You can guarantee the pointer position, and if you try ftell or fseek you will get an error (ask perror).

References:

*

*http://man7.org/linux/man-pages/man2/select.2.html

*http://man7.org/linux/man-pages/man2/poll.2.html

*http://man7.org/linux/man-pages/man2/ioctl.2.html

*http://man7.org/linux/man-pages/man2/fcntl.2.html

*http://man7.org/linux/man-pages/man3/termios.3.html


text:
Q: Performance issue for vector::size() in a loop in C++ In the following code:
std::vector<int> var;
for (int i = 0; i < var.size(); i++);

Is the size() member function called for each loop iteration, or only once?

A: It's 'called' each time, but I put called into quotes because it really probably is just an inline method call, so you don't have to worry about its performance.
Why not use vector<int>::iterator instead?

A: In theory, it is called each time, since a for loop:
for(initialization; condition; increment)
    body;

is expanded to something like
{
    initialization;
    while(condition)
    {
        body;
        increment;
    }
}

(notice the curly braces, because initialization is already in an inner scope)
In practice, if the compiler understands that a piece of your condition is invariant through all the duration of the loop and it does not have side-effects, it can be smart enough to move it out. This is routinely done with strlen and things like that (that the compiler knows well) in loops where its argument isn't written.
However it must be noted that this last condition isn't always trivial to prove; in general, it's easy if the container is local to the function and is never passed to external functions; if the container is not local (e.g. it's passed by reference - even if it's const) and the loop body contains calls to other functions, the compiler often has to assume that such functions may alter it, thus blocking the hoisting of the length calculation.
Doing that optimization by hand is worthy if you know that a part of your condition is "expensive" to evaluate (and such condition usually isn't, since it usually boils down to a pointer subtraction, which is almost surely inlined).

Edit: as others said, in general with containers it's better to use iterators, but for vectors it's not so important, because random access to elements via operator[] is guaranteed to be O(1); actually with vectors it usually is a pointer sum (vector base+index) and dereference vs the pointer increment (preceding element+1) and dereference of iterators. Since the target address is still the same, I don't think that you can gain something from iterators in terms of cache locality (and even if so, if you're not walking big arrays in tight loops you shouldn't even notice such kind of improvements).
For lists and other containers, instead, using iterators instead of random access can be really important, since using random access may mean walk every time the list, while incrementing an iterator is just a pointer dereference.

A: The problem with your question is that it does not make any sense. A C++ compiler translates some source code into a binary program. The requirement is that the resulting program must preserve observable effects of the code according to the rules of the C++ Standard. This code:
for (int i = 0; i < var.size(); i++);

simply does not have any observable effect. Moreover, it does not interact with the surrounding code any way, and the compiler may optimize it completely away; that is to generate no corresponding assembly.
To make your question meaningful, you need to specify what happens inside the loop. The problem with
for (int i = 0; i < var.size(); i++) { ... }

is that the answer very much depends on what ... actually is. I believe @MatteoItalia provided a very nice answer, just would add a description of some experiments I made. Consider the following code:
int g(std::vector<int>&, size_t);

int f(std::vector<int>& v) {
   int res = 0;
   for (size_t i = 0; i < v.size(); i++)
      res += g(v, i);
   return res;
}

First, even if calling var.size() will almost 100% sure be inlined with enabled optimizations, and this inlining typically translates into a subtraction of two pointers, this still brings into the loop some overhead. If a compiler is not able to prove that the vector size is preserved (which, generally, is very difficult or even infeasible, such as in our case), then you will end up with unnecessary load and sub (and, possibly, shift) instructions. The generated assembly of the loop with GCC 9.2, -O3, and x64 was:
.L3:
    mov     rsi, rbx
    mov     rdi, rbp
    add     rbx, 1
    call    g(std::vector<int, std::allocator<int> >&, unsigned long)
    add     r12d, eax
    mov     rax, QWORD PTR [rbp+8] // loads a pointer
    sub     rax, QWORD PTR [rbp+0] // subtracts another poniter
    sar     rax, 2                 // result * sizeof(int) => size()
    cmp     rbx, rax
    jb      .L3

If we rewrite the code as follows:
int g(std::vector<int>&, size_t);

int f(std::vector<int>& v) {
   int res = 0;
   for (size_t i = 0, e = v.size(); i < e; i++)
      res += g(v, i);
   return res;
}

then, the generated assembly is simpler (and, therefore, faster):
.L3:
    mov     rsi, rbx
    mov     rdi, r13
    add     rbx, 1
    call    g(std::vector<int, std::allocator<int> >&, unsigned long)
    add     r12d, eax
    cmp     rbx, rbp
    jne     .L3

The value of the vector's size is simply kept in a register (rbp).
I even tried a different version where the vector is marked as being const:
int g(const std::vector<int>&, size_t);

int f(const std::vector<int>& v) {
   int res = 0;
   for (size_t i = 0; i < v.size(); i++)
      res += g(v, i);
   return res;
}

Surprisingly, even when v.size() cannot change here, the generated assembly was the same as in the first case (with additional mov, sub, and sar instructions).
Live demo is here.
Additionally, when I changed the loop into:
for (size_t i = 0; i < v.size(); i++)
   res += v[i];

then, there was no evaluation of v.size() (subtraction of pointers) within the loop on an assembly level. GCC was able to "see" here, that the body of the loop does not alter the size any way.

A: It must be called everytime because size() might return a different value everytime.
Therefore there's no big choice it simply must be.

A: But it could be done in this way (providing that this loop intends to only read/write without actually changing the size of a vector):
for(vector<int>::size_type i=0, size = var.size(); i < size; ++i)
{
//do something
}

In the loop above you have just one call to size independently from size being inlined or not.

A: The size() member function is called each time, but it would be a really bad implementation that wouldn't inline it, and a strange one where it wouldn't be a simple access of a fixed datum or a subtraction of two pointers.
Anyway, you shouldn't worry yourself with such trivialities until you have profiled your application and found out that this is a bottleneck.
However, what you should pay attention to is:

*

*The correct type for a vector's index is std::vector<T>::size_type.

*There are types (some iterators, for example) where i++ might be slower than ++i.

Therefore, the loop should be:
for(vector<int>::size_type i=0; i<var.size(); ++i)
  ...

A: As other have said

*

*the semantics must be as if it were called each time

*it is probably inlined, and is probably a simple function

on top of which

*

*a smart enough optimizer may be able to deduce that it is a loop invariant with no side effects and elide it entirely (this is easier if the code is inlined, but may be possible even if it is not if the compiler does global optimization)

A: I think that if the compiler can conclusively deduce that the variable var is not modified inside the "loop body"
for(int i=0; i< var.size();i++) {
    // loop body
}

then the above may be transposed to something equivalent of
const size_t var_size = var.size();
for( int i = 0; i < var_size; i++ ) {
    // loop body
}

However, I am not absolutely sure, so comments are welcome :)
Also,

*

*In most situations, the size() member function is inlined, so the issue does not warrant worrying

*The concern is perhaps equally applicable to the end() which is always used for iterator based looping, i.e. it != container.end()

*Please consider using size_t or vector<int>::size_type for the type of i [See Steve Jessop's comment below.]

A: as others said, The compiler shall decide what to do with the actual code written. The key figure is that it is called each time. But if you want to get a performance boost, it is best to write your code with some considerations. Your case is one of them, there are others as well, like the difference between these two pieces of code:
for (int i = 0 ; i < n ; ++i)
{
   for ( int j = 0 ; j < n ; ++j)
       printf("%d ", arr[i][j]);
   printf("\n");
}
for (int j = 0 ; j < n ; ++j)
{
   for ( int i = 0 ; i < n ; ++i)
       printf("%d ", arr[i][j]);
   printf("\n");
}

The difference is that the first one will not change the ram page too much per references, but the other will exhaust your cache and TLB and other stuff.
Also inline won't help that much! because the order of the calling function will remain as n(size of the vector) times. It helps in some places though, but the best thing is to rewrite your code.
But! if you want to let a compiler do it's optimizations over your code NEVER put volatile, like so:
for(volatile int i = 0 ; i < 100; ++i)

It prevents the compiler from optimizing.
If you need another hint for performance use register instead of volatile.
for(register int i = 0 ; i < 100; ++i)

The compiler will try not to move i from the CPU-registers to RAM. It is not ensured that it can do it, but it will do it's best ;)

A: Tested it for 900k iterations
Its taking time 43 seconds for pre-calculated size and 42 seconds for using the size() call.
If you guaranteed vector size doesn't  change in the loop, better to use pre-calculated size otherwise there is no choice and must use size().
#include <iostream>
#include <vector>

using namespace std;

int main() {
vector<int> v;

for (int i = 0; i < 30000; i++)
        v.push_back(i);

const size_t v_size = v.size();
for(int i = 0; i < v_size; i++)
        for(int j = 0; j < v_size; j++)
                cout << "";

//for(int i = 0; i < v.size(); i++)
//      for(int j = 0; j < v.size(); j++)
//              cout << "";
}


text:
Q: How to import tables from sql server through sqoop to hdfs I have hadoop, hive, sqoop installed. I imported the table from my database to hdfs but couldnt import it to hive. Do I need to configure any file in hive? Also when I browsed the web the configuration is shown for MySQL but I am using the driver jdbc:sqlserver.
Anyone please help me as I am stuck with this since many days.

A: jdbc:mysql is for mysql and it won't work for sqlserver, i have tried using it and it was giving out errors.  I have tried the below command and it worked wonderfully.
Command – import
Copy data from Database Table to HDFS File System
In the example below, our database & hdfs configuration is:

*

*server name :- labDB

*database name :- demo

*SQL user name :- sqoop

*SQL password :- simp1e

*Driver Class Name :- com.microsoft.sqlserver.jdbc.SQLServerDriver

*Table :- dbo.customers

*Target Directory : /tmp/dbo-customer (HDFS Folder name)

Syntax:
  sqoop import --connect jdbc:sqlserver://sqlserver-name \
      --username <username> \
      --password <password> \
      --driver   <driver-manager-class> \
      --table    <table-name> \
      --target-dir  <target-folder-name>

Sample:
  sqoop import --connect "jdbc:sqlserver://labDB;database=demo" \
       --username sqoop  \
       --password simp1e \
       --driver   com.microsoft.sqlserver.jdbc.SQLServerDriver \
       --table    "dbo.customer" \
       --target-dir  "/tmp/dbo-customer"

https://danieladeniji.wordpress.com/2013/05/06/hadoop-sqoop-importing-data-from-microsoft-sql-server/

A: You should be able to import a table and see it in Hive using the --hive-import flag
Check if you have defined all the global variables, HADOOP_HOME, SQOOP_HOME and HIVE_HOME
If it doesn't work for you, in the meantime you can always use CREATE EXTERNAL TABLE syntax to make use of your imported data in Hive.

A: Have you used the specific --hive-import switch in the sqoop command line?
Sqoop import --connect 'jdbc:sqlserver://sqlservername.mycompany.com;username=hadoop;password=hadoop;database=hadoop' --table dataforhive --hive-import

A: just create an external hive table on the path in hdfs. or use --hive-import
Any of the two should work for you.

A: I also had the same problem, I could store my MYSQL table in the HDFS but couldn't store it in hive. I simple imported the table in hive using the following command without again storing it in the HDFS and it worked for me.
sqoop import --connect jdbc:mysql://ipAddress:portNo/mysqldatabase --table mysqltablename --username mysqlusername --password mysqlpassword --hive-import --hive-table hivedatabase.hivetablename


text:
Q: How to hide/show progress bar from method onLoadingStateChanged in the FirestorePagingAdapter? In my app there is a recyclerview with FirestorePagingAdapter. In the adapter there is method onLoadingStateChanged who is responsible for the loading state. I want to show progress bar while the next page is loading and hide it when it loaded, that's means when case LOADING_INITIAL - show progress bar.
The code below will more explain:
public class AdAdapter extends FirestorePagingAdapter<Ad, AdAdapter.AdHolder> {
    private Context mContext;
    private ArrayList<String> imageUrls;
    private ProgressBar homeRecyclerViewProgressBar;

    public AdAdapter(Context context, @NonNull FirestorePagingOptions<Ad> options) {
        super(options);
        this.mContext = context;
    }

    @NonNull
    @Override
    public AdAdapter.AdHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.ad_item, viewGroup, false);
        AdHolder vh = new AdHolder(v);
        mContext = viewGroup.getContext();
        return vh;
    }

    @Override
    protected void onBindViewHolder(@NonNull AdHolder holder, int position, @NonNull Ad model) {

        holder.textViewTitle.setText(model.getTitle());
        holder.textViewPrice.setText(String.valueOf(model.getPrice()));

        imageUrls = model.getImagesUrls();
        Glide.with(mContext)
                .load(imageUrls.get(0))
                .into(holder.imageView);
    }

    @Override
    protected void onLoadingStateChanged(@NonNull LoadingState state) {
        super.onLoadingStateChanged(state);

            switch (state) {
            case LOADING_INITIAL:

                homeRecyclerViewProgressBar.setVisibility(View.VISIBLE);

                // The initial load has begun
                // ...
                Log.d("someLog", "The initial load has begun");
                return;
            case LOADING_MORE:
                // The adapter has started to load an additional page
                // ...
                Log.d("someLog", "The additional load has begun");
                return;
            case LOADED:
                homeRecyclerViewProgressBar.setVisibility(View.GONE);
                // The previous load (either initial or additional) completed
                // ...
                Log.d("someLog", "Has loaded");
                return;
            case ERROR:
                // The previous load (either initial or additional) failed. Call
                // the retry() method in order to retry the load operation.
                // ...
                Log.d("someLog", "Failed to load");
        }
    }

    class AdHolder extends RecyclerView.ViewHolder {
        TextView textViewTitle;
        TextView textViewPrice;
        ImageView imageView;

        public AdHolder(View itemView) {
            super(itemView);

            textViewTitle = itemView.findViewById(R.id.adTitleMain);
            textViewPrice = itemView.findViewById(R.id.adPriceMain);
            imageView = itemView.findViewById(R.id.imageView);
            homeRecyclerViewProgressBar = itemView.findViewById(R.id.home_recycler_view_progressbar);

        }
    }
}

The problem is here:
...
switch (state) {
            case LOADING_INITIAL:

                homeRecyclerViewProgressBar.setVisibility(View.VISIBLE);

                // The initial load has begun
                ........

A: To show/hide your homeRecyclerViewProgressBar, please use the following lines of code in your onLoadingStateChanged() method:
@Override
protected void onLoadingStateChanged(@NonNull LoadingState state) {
    switch (state) {
        case LOADING_INITIAL:
            homeRecyclerViewProgressBar.setVisibility(View.VISIBLE);
            break;
        case LOADING_MORE:
        case LOADED:
            homeRecyclerViewProgressBar.setVisibility(View.GONE);
            break;
        case FINISHED:
            homeRecyclerViewProgressBar.setVisibility(View.GONE);
            break;
        case ERROR:
            retry();
            break;
    }
}


text:
Q: Linear approximation (surface area question)
The surface area of a sphere of radius $r$ is given by $A=4{\pi}r^2$. Use the linear approximation or differentials to compute the approximate percent change in the surface area if the radius of the sphere decreases by $3$%
I attached my solution.

A: $A = 4\pi r^2$
r decrease by 3%, Hence the new r = 0.97r
The new area $A_1 = 4\pi )(.97r)^2 = 4\pi (0.9409) r^2$
Change in area $ = (0.9409-1) (4\pi r^2)$
Percentage change$ = \frac{-0.0591 (4\pi r^2)}{4\pi r^2} = -5.91$%
This is the right answer.
You can also use what you have mentioned which is $\frac{dA}{A} = \frac{8\pi rdr}{4\pi r^2} = \frac{2dr}{r}$
But you know $\frac{dr}{r} = -0.03$  Hence percentage change $= 2\times (-0.03)=-0.06 = -6$% $ \approx -0.0591 = -5.91$%
Thanks
Satish


text:
Q: Handling StackOverflow in Java for Trampoline I would like to implement a trampoline in java by returning a thunk whenever I hit a StackOverflowError. Are there any guarantees about the StackOverflowError, like, if the only thing I do after the StackOverflowError is creating objects on the heap and returning from functions, I will be fine?
If the above sounds vague, I have added some code for computing even/odd in a tail-recursive manner in continuation passing style, returning a delayed thunk whenever the stack flows over. The code works on my machine, but does Java guarantee that it will always work?
public class CPS {
public static class Thunk {
    final Object r;
    final Continuation c;
    final boolean isDelayed;
    public Object force() {
        Thunk t = this;
        while (t.isDelayed)
            t = t.compute();
        return t.r;
    }
    public Thunk compute() {
        return this;
    }
    public Thunk(Object answer) {
        isDelayed = false;
        r = answer;
        c = null;
    }
    public Thunk(Object intermediate, Continuation cont) {
        r = intermediate;
        c = cont;
        isDelayed = true;
    }
}

public static class Continuation {
    public Thunk apply(Object result) {
        return new Thunk(result);
    }
}

public static Thunk even(final int n, final Continuation c) {
    try {
        if (n == 0) return c.apply(true);
        else return odd(n-1, c);
    } catch (StackOverflowError x) {
        return new Thunk(n, c) {
            public Thunk compute() {
                return even(((Integer)n).intValue(), c);
            }
        };
    }
}

public static Thunk odd(final int n, final Continuation c) {
    try {
        if (n == 0) return c.apply(false);
        else return even(n-1, c);
    } catch (StackOverflowError x) {
        return new Thunk(n, c) {
            public Thunk compute() {
                return odd(((Integer)n).intValue(), c);
            }
        };
    }
}

public static void main(String args[]) {
    System.out.println(even(100001, new Continuation()).force());
}

}

A: That's an interesting way to jump up the stack. It seems to work, but is probably slower than the usual way to implement this technique, which is to throw an exception that is caught $BIGNUM layers up the call stack.

A: I tried the following implementation possibilities:
A) With thunks (see code CPS below)
B) Without thunks as suggested by chris (see code CPS2 below)
C) With thunks with the stack overflow replaced by a depth check (see code CPS3 below)
In each case I checked if 100,000,000 is an even number. This check lasted
A) about 2 seconds
B) about 17 seconds
C) about 0.2 seconds
So returning from a long chain of functions is match faster than throwing an exception that unwinds that chain. Also, instead of waiting for a stack overflow, it is much faster to just record the recursion depth and unwind at depth 1000.
Code for CPS:
public class CPS {

public static class Thunk {
    final Object r;
    final boolean isDelayed;
    public Object force() {
        Thunk t = this;
        while (t.isDelayed)
            t = t.compute();
        return t.r;
    }
    public Thunk compute() {
        return this;
    }
    public Thunk(Object answer) {
        isDelayed = false;
        r = answer;
    }
    public Thunk() {
        isDelayed = true;
        r = null;
    }
}

public static class Continuation {
    public Thunk apply(Object result) {
        return new Thunk(result);
    }
}

public static Thunk even(final int n, final Continuation c) {
    try {
        if (n == 0) return c.apply(true);
        else return odd(n-1, c);
    } catch (StackOverflowError x) {
        return new Thunk() {
            public Thunk compute() {
                return even(n, c);
            }
        };
    }
}

public static Thunk odd(final int n, final Continuation c) {
    try {
        if (n == 0) return c.apply(false);
        else return even(n-1, c);
    } catch (StackOverflowError x) {
        return new Thunk() {
            public Thunk compute() {
                return odd(n, c);
            }
        };
    }
}

public static void main(String args[]) {
    long time1 = System.currentTimeMillis();
    Object b =  even(100000000, new Continuation()).force();
    long time2 = System.currentTimeMillis();
    System.out.println("time = "+(time2-time1)+", result = "+b);
}

}

Code for CPS2:
public class CPS2 {

public abstract static class Unwind extends RuntimeException {
    public abstract Object compute();
    public Object force() {
        Unwind w = this;
        do {
            try {
                return w.compute();
            } catch (Unwind unwind) {
                w = unwind;
            }
        } while (true);
    }
}

public static class Continuation {
    public Object apply(Object result) {
        return result;
    }
}

public static Object even(final int n, final Continuation c) {
    try {
        if (n == 0) return c.apply(true);
        else return odd(n-1, c);
    } catch (StackOverflowError x) {
        throw new Unwind()  {
            public Object compute() {
                return even(n, c);
            }
        };
    }
}

public static Object odd(final int n, final Continuation c) {
    try {
        if (n == 0) return c.apply(false);
        else return even(n-1, c);
    } catch (StackOverflowError x) {
        return new Unwind() {
            public Object compute() {
                return odd(n, c);
            }
        };
    }
}

public static void main(String args[]) {
    long time1 = System.currentTimeMillis();
    Unwind w = new Unwind() {
        public Object compute() {
            return even(100000000, new Continuation());
        }
    };
    Object b = w.force();
    long time2 = System.currentTimeMillis();
    System.out.println("time = "+(time2-time1)+", result = "+b);
}

}

Code for CPS3:
public class CPS3 {

public static class Thunk {
    final Object r;
    final boolean isDelayed;
    public Object force() {
        Thunk t = this;
        while (t.isDelayed)
            t = t.compute();
        return t.r;
    }
    public Thunk compute() {
        return this;
    }
    public Thunk(Object answer) {
        isDelayed = false;
        r = answer;
    }
    public Thunk() {
        isDelayed = true;
        r = null;
    }
}

public static class Continuation {
    public Thunk apply(Object result) {
        return new Thunk(result);
    }
}

public static Thunk even(final int n, final Continuation c, final int depth) {
    if (depth >= 1000) {
        return new Thunk() {
            public Thunk compute() {
                return even(n, c, 0);
            }
        };
    }
    if (n == 0) return c.apply(true);
    else return odd(n-1, c, depth+1);
}

public static Thunk odd(final int n, final Continuation c, final int depth) {
    if (depth >= 1000) {
        return new Thunk() {
            public Thunk compute() {
                return odd(n, c, 0);
            }
        };
    }
    if (n == 0) return c.apply(false);
    else return even(n-1, c, depth+1);
}

public static void main(String args[]) {
    long time1 = System.currentTimeMillis();
    Object b =  even(100000000, new Continuation(), 0).force();
    long time2 = System.currentTimeMillis();
    System.out.println("time = "+(time2-time1)+", result = "+b);
}

}


text:
Q: convert List[Tuple2[A,B]] to Tuple2[Seq[A],Seq[B]] Stuck here, trying to convert a List of case class tuples to a tuple of sequences and multi-assign the result.
val items = repo.foo.list // gives me a List[(A,B)]

I can pull off multi-assignment like so:
val(a,b) = (items.map(_._1).toSeq, items.map(_._2).toSeq)

but it would be nicer to do in 1 step, along the lines of:
val(a,b) = repo.foo.list.map{case(a,b) => (a,b)}

A: I am not sure if I understood the question correctly. Maybe unzip works for what you want?
Here is a link with some examples: http://daily-scala.blogspot.de/2010/03/unzip.html

A: For a more general case you can look at product-collections.  A CollSeqN is both a Seq[TupleN[A1..An]] and a TupleN[Seq[A1..An]]
In your example you could extract the Seqs like so:
items._1
items._2
...


text:
Q: How do I split a shape with conected pixels in to two parts in a binary image My goal is to draw a rectangle border around the face by removing the neck area connected to the whole face area. All positive values here represent skin color pixels.  Here I have so far filtered out the binary image using OpenCV and python. Code so far skinid.py
Below is the test image.

Noise removals have also been applied to this binary image

Up to this point, I followed this paper Face segmentation using skin-color map in videophone applications. And for the most of it, I used custom functions rather than using built-in OpenCV functions because I kind of wanted to do it from scratch. (although some erosion, opening, closing were used to tune it up)
I want to know a way to split the neck from the whole face area and remove it like this,

as I am quite new to the whole image processing area.

A: Perform a distance transform (built into opencv or you could write by hand its a pretty fun and easy one to write using the erode function iteratively, and adding the result into another matrix each round, lol slow but conceptually easy).  On the binary image you presented above, the highest value in a distance transform (and tbh I think pretty generalized across any mug shots) will be the center of the face.  So that pixel is the center of your box, but also that value (value of that pixel after the distance transform) will give you a pretty solid approx face size (since it is going to be the pixel distance from the center of the face to the horizontal edges of the face).  Depending on what you are after, you may just be able to multiply that distance by say 1.5 or so (figure out standard face width to height ratio and such to choose your best multiplier), set that as your circle radius (or half side width for a box) and call it a day.  Comment if you need anything clarified as I am pretty confident in this answer and would be happy to write up some quick code (in c++ opencv) if you need/ it would help.
(alt idea). You could tweak your color filter a bit to reject darker areas (this will at least in the image presented) create a nice separation between your face and neck due to the shadowing of the chin. (you may have to dial back your dilate/ closing op tho)


text:
Q: XMLHttpRequest не работает в асинхронном режиме. Status == 0 Вот мой код, может я не правильно обрабатываю запрос но req.status == 0 постоянно
var req = new XMLHttpRequest;
    req.overrideMimeType("application/json");
    var date = "test";
    var url = "qservice.php";
    if (q) {
        var dur = new Date(q.mint);

        var _userOffset = dur.getTimezoneOffset()*60000;
        date = new Date(dur.valueOf()-60000-_userOffset);
        url+="?date="+date.toISOString();
    } else {
        url += "?date=test";
    }
    req.open('GET', url, true);

    req.onload = function () {

        if (req.readyState==4 && req.status==200) {
            q = (JSON.parse(req.responseText));
            f(q);
            document.getElementById("loader").style.display = "none";
        }

    }

    req.send(null);

A: попробуй этот код. я там добавил пару комментов http://jsfiddle.net/yrsWy/
этот код 100% рабочий. у меня все работает


text:
Q: Beacon Payload Analysis I am analyzing the traffic beacons generate using tshark and iptraf. I know they are mainly used to determine the proximity of a device and like any other network device the traffic generated by them must be having a header and payload information in it.
What is best way to find out the payload information though header info can be identified as to where packet is being sent etc , but how we can classify the payload and what information it contains in a beacon signal , is it the same like any other web traffic sent and receive on a network or is it different since they make use of Bluetooth ?
Any pointers regarding would be useful .

A: Bluetooth LE beacon transmissions are much simpler than the HTTP protocol.  They are transmit only and have no real headers, although there are short segments within the transmissions called PDUs that have a similar purpose.
To see an example of a beacon transmission, see my answer here:
What is the iBeacon Bluetooth Profile


text:
Q: Encoding CSV lists in python I need some help with the encoding of a list. I'm new in python, sorry.
First, I'm using Python 2.7.3
I have two lists (entidad & valores), and I need to get them encoded or something of that.
My code:
import urllib
from bs4 import BeautifulSoup
import csv

sock = urllib.urlopen("http://www.fatm.com.es/Datos_Equipo.asp?Cod=01HU0010")
htmlSource = sock.read()
sock.close()
soup = BeautifulSoup(htmlSource)

form = soup.find("form", {'id': "FORM1"})
table = form.find("table")

entidad = [item.text.strip() for item in table.find_all('td')]

valores = [item.get('value') for item in form.find_all('input')]
valores.remove('Imprimir')
valores.remove('Cerrar')
header = entidad
values = valores

print values

out = open('tomate.csv', 'w')

w = csv.writer(out)
w.writerow(header)
w.writerow(values)
out.close()

the log: UnicodeEncodeError: 'ascii' codec can't encode character
any ideas? Thanks in advance!!

A: You should encode your data to utf-8 manually, csv.writer didnt do it for you:
w.writerow([s.encode("utf-8") for s in header])
w.writerow([s.encode("utf-8") for s in values])
#w.writerow(header)
#w.writerow(values)

A: This appears to be the same type of problem as had been found here UnicodeEncodeError in csv writer in Python

UnicodeEncodeError in csv writer in Python
  Today I was writing a
  program that generates a csv file after some processing. But I got the
  following error while trying on some test data:
writer.writerow(csv_li) UnicodeEncodeError: 'ascii' codec can't encode
  character u'\xbf' in position 5: ordinal not in range(128)
I looked into the documentation of csv module in Python and found a
  class named UnicodeWriter. So I changed my code to
writer = UnicodeWriter(open("filename.csv", "wb"))
Then I tried to run it again. It got rid of the previous
  UnicodeEncodeError but got into another error.
self.writer.writerow([s.encode("utf-8") for s in row]) AttributeError:
  'int' object has no attribute 'encode'
So, before writing the list, I had to change every value to string.
row = [str(item) for item in row]
I think this line can be added in the writerow function of
  UnicodeWriter class.


text:
Q: Null Value for datagridview cell vb.net How to get for null value in datagridview i did this in the cell validation event but it dosent seem to work. I want the user to add a new row and someone force him to give an ID or delete the row. What am i doing wrong. This is not a how to do question. This is a what is wrong Question. So right now it detects null but once i corrected the cell it still dosent allow me to get out of the row.
          If DataGrid.CurrentCell.ColumnIndex = 0 Then
        If IsDBNull(DataGrid.CurrentCell.Value) Then
            Msgbox("Cannot be Null")
              e.cancel = true
        ElseIf Not IsDBNull(DataGrid.CurrentCell.Value) Then
              e.cancel = False

        End If
    End If

A: So i tried this and it works for me . it simply uses e.formatedvalue. Current Cell Value is the cell value before and after edit while formatedvalue is what is being typed it . i guess i understand now so here is the coding
              If grdDataGrid.CurrentCell.ColumnIndex = 2 Then
        If e.FormattedValue = "" Or IsDBNull(e.FormattedValue) Then
            MsgBox("Cannot be Null")
            e.Cancel = True
            Exit Sub

        End If
    End If

They are also different ways like adjusting your column properties to not allowed null but since the column properties inherit from the database i decided to use this.

A: I think this should be works ...
If DataGrid.CurrentCell.ColumnIndex = 0 Then
    If IsDBNull(DataGrid.CurrentCell.Value) Then
          Msgbox("Cannot be Null")
          e.cancel = true
          exit sub
    End If
End If

A: Another way around this would be to explicitly set the default null value for the new datagrid cell to the value you are checking for. For instance,set the null= to an empty string if you are pulling string values.  You can use the properties palette to set this.


text:
Q: How to define a template specialization for a templated function for a templated class I have a class, something like BizClass below. I'd like to define a templated function and a specialization for a particular concrete type. I'm not sure of the appropriate syntax.
template <class Foo>
class BizClass {
 public:
  template <typename Bar>
  void Action(Container<Bar> m);
  // Foo is used somewhere else...
};

// This seems to work.
template <class Foo>
template <typename Bar>
inline void BizClass<Foo>::Action(Container<Bar> m) {}

// This specialization doesn't compile, where Foobar is a concrete class.
template <class Foo>
inline void BizClass<Foo>::Action(Container<FooBar> m) {}

How do I handle the template specialization for this case?

A:
How do I handle the template specialization for this case?

As far I know, the C++ forbids specialization of a method, inside a template struct/class, without specializing the struct/class itself.
But you can use overloading: make Action (Container<FooBar> m) a not-template method
#include <iostream>

template <typename>
struct Container
 { };

struct FooBar
 { };

template <typename Foo>
struct BizClass
 {
   template <typename Bar>
   void Action (Container<Bar> m);

   void Action (Container<FooBar> m);
 };

template <typename Foo>
template <typename Bar>
inline void BizClass<Foo>::Action (Container<Bar> m)
 { std::cout << "Action() generic version" << std::endl; }

template <typename Foo>
inline void BizClass<Foo>::Action (Container<FooBar> m)
 { std::cout << "Action() FooBar version" << std::endl; }

int main ()
 {
   BizClass<int>  bci;

   bci.Action(Container<int>{});     // print Action() generic version
   bci.Action(Container<FooBar>{});  // print Action() FooBar version
 }

A: In your first code sample titled This seems to work., that is just defining the body for the template function, it is not a specialization.
In the second sample you attempt to specialize a template which is a member of another unspecialized template. This is not allowed.
You need to also specialize BizClass if you want to specialize Action, e.g. here is an example with Foo=int and Bar=char:
template<> template<>
inline void BizClass<int>::Action(Container<char> m)
{

}


text:
Q: Javascript: image object -> HTML image element The code preloads an image into an image object and then (supposed to) set it to the image element src on HTML:
<!DOCTYPE html>

Why it doesn't work?

A: Try
<!DOCTYPE html>

You can't set a src to an image, you have to set it to the image's src. (PS: Added semicolon at the end and changed .src = oImage to .src = oImage.src)
DEMO


text:
Q: Create dynamically expandable Goupbox in MFC and place the controls with in it I want to create 2 Groupboxes placed one below another in dialog and place some control items with in both Groupboxes. The number of controls with in the Group boxes decided on run time.
The Groupbox size should be fit to the number of controls with in it and second Groupbox should be next to first Groupbox.

A: Create the groupbox dynamically - at run time . This http://www.tech-archive.net/Archive/VC/microsoft.public.vc.mfc/2004-07/2144.html might be helpful and add the controls during runtime, making the group box the parent window .


text:
Q: drupal7 - loading node using ajax(jquery) I wanted to load simple content dynamically on a node when a link in a view is clicked. Is there a way to do that without involving forms?

A: For anyone reading this in the future - from the Drupal forums:
(function($) {
    $(document).ready(function() {
        var selector = '#main-menu li a'; // Or whatever selector you need
        $(selector).click(function(e) {
            e.preventDefault();
            $.ajax({
                url: $(this).attr('href') + '?ajaxrequest',
                success: function(data) {
                    // I'm assuming here that the wrapper around your content region
                    // will be given an ID of 'region-content', you'll need to check that
                    $('#region-content').replaceWith(data);
                }
            });
        });
    });
 })(jQuery);

And in the module:
<?php
function mymodule_page_alter(&$page) {
    if (isset($_GET['ajaxrequest'])) {
        echo render($page['content']);
        drupal_exit();
    }
}
?>

Worked for me with a few tweaks.


text:
Q: How many ways are there to pack $9$ identical DVDs into $3$ indistinguishable boxes?
How many ways are there to pack $9$ identical DVDs into $3$ indistinguishable boxes so that each box contains at least two DVDs?

Is this having one to one correspondence with the partitions of a number?

A: Yes, it's the number of partitions of $3$ with at most $3$ parts, but since $3\leq3$ the extra condition doesn't add anything in this case.
(The first $3$ is the number of DVDs you have left after putting the minimum number into each box, and the second is the number of boxes.)
So there are $3$ ways, which correspond to the partitions $3$, $2+1$, $1+1+1$, and have boxes with $5,2,2$ or $4,3,2$ or $3,3,3$ DVDs respectively.


text:
Q: How to display path on map with openlayers? I have a path like this:
[53.994791502000055,32.87857732600003,141,53.99267829900003,32.95958344100006,126,53.98845189300005,32.99902989800006,124,53.998313507000034,33.01593552200006,120,54.04269077100008,33.07158320100007,109,54.05184798400006,33.06242598800003,109,54.07086681100003,33.00818711100004,109,54.04480397400005,32.98564627800005,113]

This path includes long, lat and z for each point. Also I have a map that created with OpenLayers. I want show this path on map. I tried different methods and instructions,but it is not shown. This is how I show my map:
var map = new ol.Map({
        controls: ol.control.defaults({
          attributionOptions: {
            collapsible: false
          }
        }).extend([mousePositionControl]),
        layers: layers,
        // Improve user experience by loading tiles while dragging/zooming. Will make
        // zooming choppy on mobile or slow devices.
        loadTilesWhileInteracting: true,
        target: 'map',
        view: new ol.View({
          center: ol.proj.fromLonLat([54.081, 32.908]),
          zoom: 13
        })
      });

I tested the display of part of the route this way but it didn't work:
routlayer = new ol.layer.Vector({
     source: new ol.source.Vector({
         features: [
             new ol.Feature({
                 geometry: new ol.geom.LineString([
      [53.9888, 32.8876],
      [54.1576, 32.9360]
])
             })
         ]

     })

 });

    map.addLayer(routlayer);

And I tried similar methods in different references, but it didn't work.

A: I think that you are missing the transformation from geographic coordinates to Web Mercator on the geometry of routlayer. If you fix that it should work.
Here you have a working example I made for you with the data of the post,

<!doctype html>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/css/ol.css" type="text/css">

    <title>OL - LineString From Coords</title>

LineString From Coords


text:
Q: Pause an "until" loop and wait for a keypress to continue (Ruby) I have a method with an until loop that keeps calling another method until a third method returns true. This is basically checking to see if a puzzle is solved.
def call_loop
  until solved?  #returns true if puzzle is solved
    flip         #changes one piece on the board
  end
end

Is there a way to have this loop pause before each call to the flip method and wait for the user to press the spacebar?

A: The easy solution would be to add a gets before flip. Then it would wait for you to hit enter.
If you really want to wait for spacebar, you can use curses. It can do robust input handling in the terminal, but it can get pretty complicated. If you're using Ruby 2.1.0 or earlier curses is part of the stdlib. Otherwise you'll need one of the gems.


text:
Q: In php how to create database dynamically on godaddy server I am using this code to create database on runtime. But it is not working. Getting error:

No user created.

<?php

mysql_connect('localhost','root','root');
mysql_query("CREATE USER 'xyz'@'localhost' IDENTIFIED BY '1234';");
mysql_query("GRANT ALL ON db1.* TO 'xyz'@'localhost'");
mysql_query("CREATE DATABASE locus_ag_1234");
mysql_close();

?>


text:
Q: Is there a way to create phantom tables in a postgres database? I have a table called groups in my postgres production server, they have a column called manager_id. What I'm trying to do is to create simulated look up tables base off the ids of the manager. For example, if I have the following rows for table groups:
|   id   |manager_id| ... |
|   1    |     1    | .
|   2    |     3    | .
|   4    |     1    |
|   5    |     2    |
|   7    |     2    |

I would like to access make believe tables like group-1
|   id   |manager_id| ... |
|   1    |     1    | .
|   4    |     1    | .

Or group-2
|   id   |manager_id| ... |
|   5    |     2    | .
|   7    |     2    | .

I am not sure if this is possible, and yes I'm aware I could query for it, but for the purpose of the question (and my very specific needs, which I am having trouble finding a workaround), can I do something like that? If yes, can I do it without duplicating data, just picking up references from the original one?

A: Generally: just a use a where clause to filter on the manager you want the result from:
select *
from groups
where manager_id = 1

You could take one step forward and create views:
create view v_groups_1 as
select *
from groups
where manager_id = 1

create view v_groups_2 as
select *
from groups
where manager_id = 2

You can then run queries against the views just like you would do with a regular table.


text:
Q: harmonic function invariant under a rotation I am trying to solve the following problem:
Suppose that $u$ is a harmonic function on the unit disk such that $u(e^{2\pi i/9}z)=u(z)$ for all $z$. Prove that $u$ has a harmonic conjugate $v$ such that $v(e^{2\pi i/9}z)=v(z)$ for all $z$.
I have no idea what to do. Any hints will be appreciated.

A: One approach:
Define $f(z) = u(z) + iv(z)$, where $v$ is some harmonic conjugate of $u$.  Let $\alpha = e^{2 \pi i /9}$
Since $g(z) = \alpha z$ is an analytic function, the composition $f(g(z)) = f(\alpha z)$ must be analytic. From there, we note that
$$
f(\alpha z) - f(z) = [u(\alpha z) - u(z)] + i[v(\alpha z) - v(z)] = i [v(\alpha z) - v(z)]
$$
Since $f(\alpha z) - f(z)$ is the difference of analytic functions, it is analytic.
So, $v(\alpha z) - v(z)$ is a harmonic conjugate to $0$, which means that $v(\alpha z) - v(z)$ must be constant (verify this).  Since $v(\alpha z) - v(z)$ is defined over the entire unit disk (which includes the point $z = 0$), we may state that for all $z$, we have
$$
v(\alpha z) - v(z) = v(\alpha \cdot 0) - v(0) = v(0) - v(0) = 0
$$
We conclude that any harmonic conjugate $v$ of $u$ satisfies $v(\alpha z) = (z)$ for all $z$ in the disk.


text:
Q: Idiomatic scala solution to combining sequences Imagine a function combineSequences: (seqs: Set[Seq[Int]])Set[Seq[Int]] that combines sequences when the last item of first sequence matches the first item of the second sequence.  For example, if you have the following sequences:
(1, 2)
(2, 3)
(5, 6, 7, 8)
(8, 9, 10)
(3, 4, 10)

The result of combineSequences would be:
(5, 6, 7, 8, 8, 9, 10)
(1, 2, 2, 3, 3, 4, 10)

Because sequences 1, 2, and 5 combine together.  If multiple sequences could combine to create a different result, the decisions is arbitrary.  For example, if we have the sequences:
(1, 2)
(2, 3)
(2, 4)

There are two correct answers.  Either:
(1, 2, 2, 3)
(2, 4)

Or:
(1, 2, 2, 4)
(2, 3)

I can only think of a very imperative and fairly opaque implementation.  I'm wondering if anyone has a solution that would be more idiomatic scala.  I've run into related problems a few times now.

A: Certainly not the most optimized solution but I've gone for readability.
def combineSequences[T]( seqs: Set[Seq[T]] ): Set[Seq[T]] = {
  if ( seqs.isEmpty ) seqs
  else {
    val (seq1, otherSeqs) = (seqs.head, seqs.tail)
    otherSeqs.find(_.headOption == seq1.lastOption) match {
      case Some( seq2 ) => combineSequences( otherSeqs - seq2 + (seq1 ++ seq2) )
      case None =>
        otherSeqs.find(_.lastOption == seq1.headOption) match {
          case Some( seq2 ) => combineSequences( otherSeqs - seq2 + (seq2 ++ seq1) )
          case None => combineSequences( otherSeqs ) + seq1
        }
    }
  }
}

REPL test:
scala> val seqs = Set(Seq(1, 2), Seq(2, 3), Seq(5, 6, 7, 8), Seq(8, 9, 10), Seq(3, 4, 10))
seqs: scala.collection.immutable.Set[Seq[Int]] = Set(List(1, 2), List(2, 3), List(8, 9, 10), List(5, 6, 7, 8), List(3, 4, 10))
scala> combineSequences( seqs )
res10: Set[Seq[Int]] = Set(List(1, 2, 2, 3, 3, 4, 10), List(5, 6, 7, 8, 8, 9, 10))
scala> val seqs = Set(Seq(1, 2), Seq(2, 3, 100), Seq(5, 6, 7, 8), Seq(8, 9, 10), Seq(100, 4, 10))
seqs: scala.collection.immutable.Set[Seq[Int]] = Set(List(100, 4, 10), List(1, 2), List(8, 9, 10), List(2, 3, 100), List(5, 6, 7, 8))
scala> combineSequences( seqs )
res11: Set[Seq[Int]] = Set(List(5, 6, 7, 8, 8, 9, 10), List(1, 2, 2, 3, 100, 100, 4, 10))


text:
Q: Learning about Java MVC and Swing framework I have been looking around for tutorials on Java MVC concept and Swing framework. But, unfortunately, the ones I found aren't understandable . I want something to follow. Please help.
Thanks,

A: The Java Tuturials (separated into "trails") are usually a good introduction to any Java API or concept: http://download.oracle.com/javase/tutorial/uiswing/
As for MVC, you'll probably get the hang of that concept by checking the Swing examples and using the API properly. But this seems like a decent enough overview: http://www.oracle.com/technetwork/articles/javase/mvc-136693.html
MVC is not a difficult concept. Focus on using the Swing classes in the appropriate manner as described in the tutorials and by reading sample code.


text:
Q: How to handle multiple user running the same loop on Oracle using JDBC through beanshell sampler Through a beanshell sampler I am running the following loop query on Oracle, now it is running fine with one user but when I am trying to run the same with multiple user it is failing and giving PK violation error although after every iteration I am deleting the records which it setting the pointier to initial position for the first user.
BeanShell Sampler Script:
import java.sql.*;
import oracle.jdbc.*;
import org.apache.jmeter.protocol.jdbc.config.DataSourceElement;

ResultSet rs = null;
ResultSetMetaData rsmd = null;
PreparedStatement pstmt = null;

Connection conn = DataSourceElement.getConnection("IMPACTConnectionPrerequisitsII");
String Query = "DECLARE \n"
           + "j number(4) \n"
           + "BEGIN \n"
           + "FOR j in 11 .. 12 LOOP \n"
           + "INSERT INTO FWA_STAGE_TU \n"
           + "(ID,EXT_ID,BATCH_NO,OPERATION,BLOCK_ROLL_UP_LAST_RECORD,LAST_UPDATED_DATE,ERROR_FLAG,TRIAL_NO,TRIAL_ALIAS_CODE, \n"
            + "COUNTRY_CODE,DISPLAY_UNIT_NO,GROUP_NO,TRIAL_UNIT_REFERENCE,PRIMARY_INVESTIGATOR,PRIMARY_CENTRE,OCATION_NO, \n"
            + "PURPOSE_CODE,MANAGING_MED_UNIT_CODE,UPDATING_MED_UNIT_CODE,FINANCE_MED_UNIT_CODE,PATIENTS_ALL_SET_UP_FLAG, \n"
            + "PATIENT_MONITORING_FLAG,COMMENTS,CONFIRMED_FLAG,CONFIRMED_BY,CONFIRMED_DATE,ROLLUP_ROLLDOWN_PLANNED_FIGS, \n"
            + "DOC_COLLECTION_INDICATOR,VALIDATED_PAT_CAP,MAXIMUM_PAT_CAP,PREFERRED_LANGUAGE_CODE,NEW_DISPLAY_UNIT_NO, \n"
            + "TOTAL_OPEN_DCF_ISSUES_NO,ORDER_INTERVAL,ORDER_INTERVAL_UNITS,DATA_SOURCE_CODE,RANK_SEQ) \n"
            + "VALUES (j, 1, 10, 'I', NULL, SYSDATE, 'N', 102922, 'TESTTRIAL4', 'BEL', \n"
           + "j, NULL, 'BELTU'||j, 130262, 124236, NULL, 'PATTR', 'FP', 'FP', 'FP', 'N', 'Y', 'TESTTU'||j, \n"
           + "'Y', 999999, SYSDATE, NULL, 'P', 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL) \n"
           + "END LOOP \n"
           + "END";

try {
    pstmt = conn.prepareStatement(Query);
    pstmt.executeUpdate();
}
catch(Throwable ex) {
    log.error("Error message: ", ex);
    throw ex;
}
finally {
    if (rs != null) {
        rs.close();
    }
    if (pstmt != null) {
        pstmt.close();
    }
    if (conn != null) {
        conn.close();
        log.info("!!!! Connection closed to database !!!!");
    }

How to get this work for multiple user ?

A: If you're talking about multiple users it might be the situation when one user haven't deleted the inserted data yet and another one is creating the same data.
The solution would be using some unique value as ID (or what is the column which has primary key constraint), if you don't have any better idea you could use __threadNum() function which returns the number of current thread (virtual user)
Also be aware that starting from JMeter 3.1 you're supposed to be using JSR223 Test Elements and Groovy language for scripting so it worth considering migration. In your case no code changes will be required at all.


text:
Q: Nesting project file name into layout in QGIS Is there any way to automatically take information from the project file name into several boxes on a layout in QGIS?
For example, if I had a file name of "185.005R1 - Geology Map.qgz" how could I split it into separate textboxes, e.g. the Drawing number ("185.005"), the title ("Geology Map"), and the Revision number ("1")?

A: Use the following expressions. They are based on regular expressions, so will be nice and tolerant of slight differences in format:
For Drawing Number:
regexp_substr(@project_filename,'(.*?)R')

For Revision Number
regexp_substr(@project_filename,'.*?R\\s*(.*?)\\s*-')

Title:
regexp_substr(@project_filename,'-\\s*(.*)\\.')

A: You can use the project variables @project_basename together with substring in the expression builder if your string has always the same structure. If not you can try it with regex.

A: Another method which worked using expression is as the following:
For Drawing Number:
regexp_substr( @project_filename ,'\\d+.\\d+')

For Revision Number
regexp_substr( @project_filename ,'\\d{3}.\\d{3}\\D+(\\d+)')

For Title:
regexp_substr( @project_filename ,'- (\\D+).qgz')


text:
Q: How to loop over a parameter list and submit jobs? I have a job that has an input and I want to loop over a list of parameters while submitting the job. Here is the part of my script:
#!/bin/bash
errors=$HOME/ERRORS/convergence/GvsE/B_2/error.log
count=`qstat | wc -l`
gi=( "0" "0.25" "0.5" "1" "2" )
Ener=( "1" "2" "5" "10" "20" "21" "22" "23" "24" "25" )

for ((i=0; i < ${#g[@]}; i++)); do
        for ((j=0; j < ${#E[@]}; j++)); do
                qsub -o $errors -e $errors -v E=${#Ener[$j]},slices=${200},modes=${60},g=${#gi[$i]} job_convcheck.sh
                count=`expr $count + 1`
                while [ $count -gt 4950 ]
                do
                  sleep 420
                  count=`qstat | wc -l`
                done
        done
done

When I run this I am neither get an answer nor a result. What is wrong with that?

A: Probably the obvious is
for ((i=0; i < ${#g[@]}; i++)); do

should be
for ((i=0; i < ${#gi[@]}; i++)); do

and
for ((j=0; j < ${#E[@]}; j++)); do

should be
for ((j=0; j < ${#Ener[@]}; j++)); do

Or if you want the indices simply do:
for i in "${!gi[@]}"; do
    for j in "${!Ener[@]}"; do


text:
Q: Can't find value in whole array in JSON value Postgresql 9.6
json:
 "availability": [
      {
        "qty": 25,
        "price": 3599,
        "is_available": true
      },
      {
        "qty": 72,
        "price": 3599,
        },
         "is_available": true
   ]

Suppose I want to search in first array's item. I use this query:
SELECT product.data #>'{availability, 0, price}' from product

OK.
But I need to find in whole array (all array's items).
I need smt like this (pseudo code
SELECT product.data #>'{availability, *, price}' from product

Is it possible?

A:
output must be empty array if not find price, or original json if find price in any

Sounds like a strange requirement, but the following would do that.
select case
           when (select jsonb_agg(e.item -> 'price')
                 from jsonb_array_elements(data -> 'availability')  as e(item)
                 where e.item ? 'price') <> '[]' then data
           else '[]'::jsonb
       end
from product

A simple array with the prices makes more sense in my opinion:
select (select jsonb_agg(e.item -> 'price')
        from jsonb_array_elements(data -> 'availability')  as e(item)
        where e.item ? 'price') as prices
from product