Q: Функция принимает два отсортированных от меньшего к большему Вам нужно написать реализацию функции
 void merge(ArrayList a, ArrayList b) { // тело функции }

Функция принимает два отсортированных от меньшего к большему ArrayList одинакового размера
[a1, a2, ..., an],
[b1, b2, ..., bn].

В результате выполнения функции в первом(!) ArrayList (в данном случае это А) должны содержаться элементы обоих ArrayList, также отсортированные от меньшего к большему. Второй ArrayList должен остаться не изменённым.
Пример:
Входные данные
A [1,3,5]
B [2,6,8]

Результат
A [1,2,3,5,6,8]
B [2,6,8]

Оцениваться будут следующие параметры:

*

*код должен работать корректно

*выполнять полезную функцию

*иметь максимально возможную эффективность (задумайтесь, пожалуйста, над тем насколько эффективно написанная вами функция будет использовать память и процессорное время)

A: В условии специально указано что эффективность важна. Как слить массивы максимально быстро и в минимальной памяти?
Минимальность по памяти достигается следующей конструкцией:
a.ensureCapacity(a.size() + b.size());
// a.addAll(b);
for (int l = 0; l < b.size(); ++l) {
    a.add(null);
}

ensureCapacity убеждается что в списке a достаточно места чтобы он мог быть увеличен до финального размера без выделения новой памяти. Без этого вызова массив a может быть перенесён в памяти несколько раз.
Цикл ниже растягивает список до окончательного размера. Вместо цикла можно вызвать a.addAll(b). Я этого не делаю чтобы было ясно что добавленные значения не важны.
Дальше сливаем списки с конца к началу. Из индексов i и j читаем, в k пишем:
           i        k                     j
           |        |                     |
a = [1, 3, 5, ?, ?, ?]         b = [2, 6, 8]

Сравниваем a[i] и b[j]. Больший присваиваем a[k]. Передвигаем индексы j и k:
           i     k                     j
           |     |                     |
a = [1, 3, 5, ?, ?, 8]         b = [2, 6, 8]

Ещё раз:
           i  k                     j
           |  |                     |
a = [1, 3, 5, ?, 6, 8]         b = [2, 6, 8]

Теперь a[i] > b[j]. Копируем из a[i] в a[k] и двигаем индексы i и k:
        i  k                        j
        |  |                        |
a = [1, 3, 5, 5, 6, 8]         b = [2, 6, 8]

Ещё раз:
     i  k                           j
     |  |                           |
a = [1, 3, 3, 5, 6, 8]         b = [2, 6, 8]

И ещё раз. Список b исчерпан. Можно прекращать работу:
    i,k
     |
a = [1, 2, 5, 5, 6, 8]         b = [2, 6, 8]

Возможна ситуация когда первым будет исчерпан список a, тогда надо докопировать значения, которые остались в b.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MergeSortedArrayListsInPlace {
    public static void main(String... args) {
        ArrayList<Integer> a = new ArrayList<Integer>(Arrays.asList(1, 3, 5));
        List<Integer> b = Arrays.asList(2, 6, 8);
        System.out.println(a);
        System.out.println(b);
        merge(a, b);
        System.out.println(a);
    }

    public static void merge(ArrayList<Integer> a, List<Integer> b) {
        int i = a.size() - 1; // читает из a, движется к нулю
        a.ensureCapacity(a.size() + b.size());
        // a.addAll(b);
        for (int l = 0; l < b.size(); ++l) {
            a.add(null);
        }
        int j = b.size() - 1; // читает из b, движется к нулю
        int k = a.size() - 1; // пишет в a, движется к нулю

        // слияние от больших к меньшим
        while (i >= 0 && j >= 0) {
            Integer av = a.get(i);
            Integer bv = b.get(j);
            if (av > bv) {
                a.set(k, av);
                --i;
            } else {
                a.set(k, bv);
                --j;
            }
            --k;
        }

        // копирование хвоста из b в a
        while (j >= 0) {
            a.set(k, b.get(j));
            --j;
            --k;
        }
    }
}

$ javac MergeSortedArrayListsInPlace.java && java MergeSortedArrayListsInPlace
[1, 3, 5]
[2, 6, 8]
[1, 2, 3, 5, 6, 8]

A: private static void merge(ArrayList<Integer> a, ArrayList<Integer> b) {
        int size = a.size();
        ArrayList<Integer> temp = new ArrayList<>(size * 2);
        int firstIdx = 0;
        int secondIdx = 0;
        for (; firstIdx < size && secondIdx < size; ) {
            temp.add(
                    a.get(firstIdx) < b.get(secondIdx) ? a.get(firstIdx++) : b.get(secondIdx++)
            );
        }

        ArrayList<Integer> last;
        int lastIdx;

        if (firstIdx < size) {
            last = a;
            lastIdx = firstIdx;
        } else {
            last = b;
            lastIdx = secondIdx;
        }

        for (int i = lastIdx; i < last.size(); i++) {
            temp.add(last.get(i));
        }
        a.clear();
        a.addAll(temp);
    }

A: Однако данный вариант кода не обрабатывает числа отрицательные.
Сделал обработку и отрицательных.
public static void main(String[] args) {
        ArrayList<Integer> firstArray = new ArrayList<Integer>(Arrays.asList(-8, 22));
        List<Integer> secondArray = Arrays.asList(-5, 15);
        merge(firstArray, secondArray);
        System.out.println(firstArray);
        System.out.println(secondArray);
    }

    public static void merge(ArrayList<Integer> firstArray, List<Integer> secondArray) {
        int i = firstArray.size() - 1;
        int j = secondArray.size() - 1;
        firstArray.ensureCapacity(firstArray.size() + secondArray.size());
        for (int l = 0; l < secondArray.size(); ++l) {
            firstArray.add(null);
        }
        int k = firstArray.size() - 1;

        while (i >= 0 && j >= 0) {
            Integer firstArrayElement = firstArray.get(i);
            Integer secondArrayElement = secondArray.get(j);
            if (firstArrayElement > secondArrayElement) {
                firstArray.set(k, firstArrayElement);
                --i;
            } else {
                firstArray.set(k, secondArrayElement);
                --j;
            }
            --k;
            if (i < 0){
                firstArray.set(k, secondArrayElement);
            }  if (j == 1 && i == -1){
                firstArray.set(k-1, secondArray.get(k-1));
            }
        }
    }


Q: Xcode 14.1 'SQLite3' build error : xFilter' from module 'SQLite3' is not present in definition provided earlier /Users/username/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS16.2.sdk/usr/include/sqlite3.h:7054:9 'sqlite3_module::xFilter' from module 'SQLite3' is not present in definition of 'struct sqlite3_module' provided earlier
Any idea why getting this error?
I searched google and try to discuss with experts but did not come to a solution


Q: Описать рекурсивную ф-у для ряда n-го члена ряда 10, 5, 5/2, 5/4...5/256
Как прийти к выходу из рекурсии, допустим мы вводим 4 число, это 5/4, мы должны дойти до 10 и потом разделить число n-ое кол-во раз на два. Как прийти к этой 10? Спасибо

    int func(int n)
{
    if (n == 10)
        return 10;
    return func() / 2;
}

int main()
{
    int n, d;

    cin >> n;

    d = func(n);

    if (d <= 10)
        cout << d << endl;
}

A: Мне кажется, что можно так:
double func(double value, int n)
{
    if (n == 0) return value;
    return func(value/2, n-1);
}

int main()
{
    int n;
    cin >> n;
    cout << func(10, n) << endl;
}


Q: OAuth with Verification in .NET I'm trying to create a .NET-based client app (in WPF - although for the time being I'm just doing it as a console app) to integrate with an OAuth-enabled application, specifically Mendeley (http://dev.mendeley.com), which apparently uses 3-legged OAuth.
This is my first time using OAuth, and I'm having a lot of difficulty getting started with it. I've found several .NET OAuth libraries or helpers, but they seem to be more complicated than I think I need. All I want to do is be able to issue REST requests to the Mendeley API and get responses back!
So far, I've tried:

*

*DotNetOpenAuth

*http://github.com/bittercoder/DevDefined.OAuth

*http://oauth.googlecode.com/svn/code/csharp/
The first (DotNetOpenAuth) seems like it could possibly do what I needed if I spent hours and hours trying to work out how. The second and third, as best I can tell, don't support the verification codes that Mendeley is sending back -- although I could be wrong about this :)
I've got a consumer key and secret from Mendeley, and with DotNetOpenAuth I managed to get a browser launched with the Mendeley page providing a verification code for the user to enter into the application. However, at this point I got lost and couldn't work out how to sensibly provide that back to the application.
I'm very willing to admit that I have no idea where to start with this (although it seems like there's quite a steep learning curve) - if anyone can point me in the right direction I'd appreciate it!

A: I agree with you.  The open-source OAuth support classes available for .NET apps are hard to understand, overly complicated (how many methods are exposed by DotNetOpenAuth?), poorly designed (look at the methods with 10 string parameters in the OAuthBase.cs module from that google link you provided - there's no state management at all), or otherwise unsatisfactory.
It doesn't need to be this complicated.
I'm not an expert on OAuth, but I have produced an OAuth client-side manager class, that I use successfully with Twitter and TwitPic.  It's relatively simple to use. It's open source and available here: Oauth.cs
For review, in OAuth 1.0a...kinda funny, there's a special name and it looks like a "standard" but as far as I know the only service that implements "OAuth 1.0a" is Twitter.  I guess that's standard enough.  ok, anyway in OAuth 1.0a, the way it works for desktop apps is this:

*

*You, the developer of the app, register the app and get a "consumer key" and "consumer secret".  On Arstechnica, there's a well written analysis of why this model isn't the best, but as they say, it is what it is.

*Your app runs. The first time it runs, it needs to get the user to explicitly grant approval for the app to make oauth-authenticated REST requests to Twitter and its sister services (like TwitPic). To do this you must go through an approval process, involving explicit approval by the user. This happens only the first time the app runs.  Like this:

*

*request a "request token".  Aka temporary token.

*pop a web page, passing that request token as a query param.  This web page presents UI to the user, asking "do you want to grant access to this app?"

*the user logs in to the twitter web page, and grants or denies access.

*the response html page appears.  If the user has granted access, there's a PIN displayed in a 48-pt font

*the user now needs to cut/paste that pin into a windows form box, and click "Next" or something similar.

*the desktop app then does an oauth-authenticated request for an "Access token".  Another REST request.

*the desktop app receives the "access token" and "access secret".

After the approval dance, the desktop app can just use the user-specific "access token" and "access secret" (along with the app-specific "consumer key" and "consumer secret") to do authenticated requests on behalf of the user to Twitter.  These don't expire, although if the user de-authorizes the app, or if Twitter for some reason de-authorizes your app, or if you lose your access token and/or secret, you'd need to do the approval dance again.

If you're not clever, the UI flow can sort of mirror the multi-step OAuth message flow.  There is a better way.
Use a WebBrowser control, and open the authorize web page within the desktop app.  When the user clicks "Allow", grab the response text from that WebBrowser control, extract the PIN automatically, then get the access tokens.  You send 5 or 6 HTTP requests but the user needs to see only a single Allow/Deny dialog.  Simple.
Like this:

If you've got the UI sorted, the only challenge that remains is to produce oauth-signed requests.  This trips up lots of people because the oauth signing requirements are sort of particular. That's what the simplified OAuth Manager class does.
Example code to request a token:
var oauth = new OAuth.Manager();
// the URL to obtain a temporary "request token"
var rtUrl = "https://api.twitter.com/oauth/request_token";
oauth["consumer_key"] = MY_APP_SPECIFIC_KEY;
oauth["consumer_secret"] = MY_APP_SPECIFIC_SECRET;
oauth.AcquireRequestToken(rtUrl, "POST");

THAT'S IT.  Simple.  As you can see from the code, the way to get to oauth parameters is via a string-based indexer, something like a dictionary.  The AcquireRequestToken method sends an oauth-signed request to the URL of the service that grants request tokens, aka temporary tokens.  For Twitter, this URL is "https://api.twitter.com/oauth/request_token". The oauth spec says you need to pack up the set of oauth parameters (token, token_secret, nonce, timestamp, consumer_key, version, and callback), in a certain way (url-encoded and joined by ampersands), and in a lexicographically-sorted order, generate a signature on that result, then pack up those same parameters along with the signature, stored in the new oauth_signature parameter, in a different way (joined by commas).  The OAuth manager class does this for you automatically.  It generates nonces and timestamps and versions and signatures automatically - your app doesn't need to care or be aware of that stuff.  Just set the oauth parameter values and make a simple method call. the manager class sends out the request and parses the response for you.
Ok, then what?   Once you get the request token, you pop the web browser UI in which the user will explicitly grant approval. If you do it right, you'll pop this in an embedded browser.  For Twitter, the URL for this is "https://api.twitter.com/oauth/authorize?oauth_token=" with the oauth_token appended. Do this in code like so:
var url = SERVICE_SPECIFIC_AUTHORIZE_URL_STUB + oauth["token"];
webBrowser1.Url = new Uri(url);

(If you were doing this in an external browser you'd use System.Diagnostics.Process.Start(url).)
Setting the Url property causes the WebBrowser control to navigate to that page automatically.
When the user clicks the "Allow" button a new page will be loaded. It's an HTML form and it works the same as in a full browser. In your code, register a handler for the DocumentedCompleted event of the WebBrowser control, and in that handler, grab the pin:
var divMarker = "<div id=\"oauth_pin\">"; // the div for twitter's oauth pin
var index = webBrowser1.DocumentText.LastIndexOf(divMarker) + divMarker.Length;
var snip = web1.DocumentText.Substring(index);
var pin = RE.Regex.Replace(snip,"(?s)[^0-9]*([0-9]+).*", "$1").Trim();

That's a bit of HTML screen scraping.
After grabbing the pin, you don't need the web browser any more, so:
webBrowser1.Visible = false; // all done with the web UI

...and you might want to call Dispose() on it as well.
The next step is getting the access token, by sending another HTTP message along with that pin.  This is another signed oauth call, constructed with the oauth ordering and formatting I described above. But once again this is really simple with the OAuth.Manager class:
oauth.AcquireAccessToken(URL_ACCESS_TOKEN,
                         "POST",
                         pin);

For Twitter, that URL is "https://api.twitter.com/oauth/access_token".
Now you have access tokens, and you can use them in signed HTTP requests.  Like this:
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");

...where url is the resource endpoint. To update the user's status, it would be "http://api.twitter.com/1/statuses/update.xml?status=Hello".
Then set that string into the HTTP Header named Authorization.
To interact with third-party services, like TwitPic, you need to construct a slightly different OAuth header, like this:
var authzHeader = oauth.GenerateCredsHeader(URL_VERIFY_CREDS,
                                            "GET",
                                            AUTHENTICATION_REALM);

For Twitter, the  values for the verify creds url and realm are "https://api.twitter.com/1/account/verify_credentials.json", and "http://api.twitter.com/" respectively.
...and put that authorization string in an HTTP header called X-Verify-Credentials-Authorization.  Then send that to your service, like TwitPic, along with whatever request you're sending.
That's it.
All together, the code to update twitter status might be something like this:
// the URL to obtain a temporary "request token"
var rtUrl = "https://api.twitter.com/oauth/request_token";
var oauth = new OAuth.Manager();
// The consumer_{key,secret} are obtained via registration
oauth["consumer_key"] = "~~~CONSUMER_KEY~~~~";
oauth["consumer_secret"] = "~~~CONSUMER_SECRET~~~";
oauth.AcquireRequestToken(rtUrl, "POST");
var authzUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth["token"];
// here, should use a WebBrowser control.
System.Diagnostics.Process.Start(authzUrl);  // example only!
// instruct the user to type in the PIN from that browser window
var pin = "...";
var atUrl = "https://api.twitter.com/oauth/access_token";
oauth.AcquireAccessToken(atUrl, "POST", pin);

// now, update twitter status using that access token
var appUrl = "http://api.twitter.com/1/statuses/update.xml?status=Hello";
var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
var request = (HttpWebRequest)WebRequest.Create(appUrl);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);

using (var response = (HttpWebResponse)request.GetResponse())
{
    if (response.StatusCode != HttpStatusCode.OK)
        MessageBox.Show("There's been a problem trying to tweet:" +
                        Environment.NewLine +
                        response.StatusDescription);
}

OAuth 1.0a is sort of complicated under the covers, but using it doesn't need to be.
The OAuth.Manager handles the generation of outgoing oauth requests, and the receiving and processing of oauth content in the responses.  When the Request_token request gives you an oauth_token, your app doesn't need to store it.  The Oauth.Manager is smart enough to do that automatically.  Likewise when the access_token request gets back an access token and secret, you don't need to explicitly store those. The OAuth.Manager handles that state for you.
In subsequent runs, when you already have the access token and secret, you can instantiate the OAuth.Manager like this:
var oauth = new OAuth.Manager();
oauth["consumer_key"] = CONSUMER_KEY;
oauth["consumer_secret"] = CONSUMER_SECRET;
oauth["token"] = your_stored_access_token;
oauth["token_secret"] = your_stored_access_secret;

...and then generate authorization headers as above.
// now, update twitter status using that access token
var appUrl = "http://api.twitter.com/1/statuses/update.xml?status=Hello";
var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
var request = (HttpWebRequest)WebRequest.Create(appUrl);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);

using (var response = (HttpWebResponse)request.GetResponse())
{
    if (response.StatusCode != HttpStatusCode.OK)
        MessageBox.Show("There's been a problem trying to tweet:" +
                        Environment.NewLine +
                        response.StatusDescription);
}

You can download a DLL containing the OAuth.Manager class here. There is also a helpfile in that download.  Or you can view the helpfile online.
See an example of a Windows Form that uses this manager here.

WORKING EXAMPLE
Download a working example of a command-line tool that uses the class and technique described here:


Q: Combined solidcolor brush Is there a way to create a kind of "solidcolorbrush" that is a mixture of 2 solidcolor brushes?
For the back color, i would like to be able to use a DynamicReference to some other brush. While the other color (in the front) could be a static color with opacity.
Feel free to ask for clarification if this doesnt really make sence!

A: I ran into the same problem. I normally just use one xaml each for the basic darks, the basic lights, and then one for each colour accent (blue, red etc). The accent is slightly lookthrough which makes it darker when then darker theme is selected with a darker background.
When creating a theme with a secondary accent colour to have more contrast in the app (for example gray when light theme is selected, accent colour when dark theme), I needed to construct a brush out of two colours as otherwise I would have to create a dark and light theme for each colour.
Here is what I use:
<DrawingBrush x:Key="SecondaryAccentColorBrush" Viewport="0,0,1,1" TileMode="Tile">
    <DrawingBrush.Drawing>
        <DrawingGroup>
            <GeometryDrawing>
                <GeometryDrawing.Geometry>
                    <RectangleGeometry Rect="0,0,1,1" />
                </GeometryDrawing.Geometry>
                <GeometryDrawing.Brush>
                    <SolidColorBrush Color="{DynamicResource AccentColor}"/>
                </GeometryDrawing.Brush>
            </GeometryDrawing>
            <GeometryDrawing>
                <GeometryDrawing.Geometry>
                    <RectangleGeometry Rect="0,0,1,1" />
                </GeometryDrawing.Geometry>
                <GeometryDrawing.Brush>
                    <SolidColorBrush Color="{DynamicResource Gray10}"/>
                </GeometryDrawing.Brush>
            </GeometryDrawing>
        </DrawingGroup>
    </DrawingBrush.Drawing>
</DrawingBrush>

When the theme is switched, the alpha of "Gray10" switches between 00 and FF, thus the brush shows either gray or the accent colour.

A: Unfortunately, custom brushes are not supported in WPF (the brush types are marked 'internal' and cannot be inherited from), so creating a brush that is a mixture of two brushes that can be used from XAML like a normal SolidColorBrush is not possible.
As a workaround, you could use a MarkupExtension to simulate the behaviour of a custom brush, which allows you to use XAML syntax and provide a custom value, which allows us to use the built-in SolidColorBrush (no custom brush necessary) set to the value you get when mixing two colors:
/// <summary>
/// Markup extension to mix two SolidColorBrushes together to produce a new SolidColorBrush.
/// </summary>
[MarkupExtensionReturnType(typeof(SolidColorBrush))]
public class MixedColorBrush : MarkupExtension, INotifyPropertyChanged
{
    /// <summary>
    /// The foreground mix color; defaults to white.
    /// If not changed, the result will always be white.
    /// </summary>
    private SolidColorBrush foreground = Brushes.White;

    /// <summary>
    /// The background mix color; defaults to black.
    /// If not set, the result will be the foreground color.
    /// </summary>
    private SolidColorBrush background = Brushes.Black;

    /// <summary>
    /// PropertyChanged event for WPF binding.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    /// Gets or sets the foreground mix color.
    /// </summary>
    public SolidColorBrush Foreground
    {
        get
        {
            return this.foreground;
        }
        set
        {
            this.foreground = value;
            this.NotifyPropertyChanged("Foreground");
        }
    }

    /// <summary>
    /// Gets or sets the background mix color.
    /// </summary>
    public SolidColorBrush Background
    {
        get
        {
            return this.background;
        }
        set
        {
            this.background = value;
            this.NotifyPropertyChanged("Background");
        }
    }

    /// <summary>
    /// Returns a SolidColorBrush that is set as the value of the
    /// target property for this markup extension.
    /// </summary>
    /// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
    /// <returns>The object value to set on the property where the extension is applied.</returns>
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (this.foreground != null && this.background != null)
        {
            // Create a new brush as a composite of the old ones
            // This does simple non-perceptual additive color, e.g
            // blue + red = magenta, but you can swap in a different
            // algorithm to do subtractive color (red + yellow = orange)
            return new SolidColorBrush(this.foreground.Color + this.background.Color);
        }

        // If either of the brushes was set to null, return an empty (white) brush.
        return new SolidColorBrush();
    }

    /// <summary>
    /// Raise the property changed event.
    /// </summary>
    /// <param name="propertyName">Name of the property which has changed.</param>
    protected void NotifyPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Which can then be used from XAML as you would a normal brush:
<Grid>
    <Grid.Background>
        <local:MixedColorBrush Foreground="Blue" Background="Red"/>
    </Grid.Background>
</Grid>

Or by using the markup extension syntax:
<Grid Background="{local:MixedColorBrush Foreground=Blue, Background=Red}">

The downside to this approach is that you cannot use DynamicResource or StaticResource references to bind the values to other resources in your application.  MarkupExtension is not a DependencyObject, and resource binding only works on DependencyObjects; the built-in Brushes are DependencyObjects, which is why binding works with traditional brushes.

A: Get the colors from the foreground and background brushes, mix them, and create a new brush from the resulting color.
Example in C#:
Color foreground = foregroundBrush.Color;
Color background = backgroundBrush.Color;

int opacity = 25;

int r = (opacity * (foreground.R - background.R) / 100) + background.R;
int g = (opacity * (foreground.G - background.G) / 100) + background.G;
int b = (opacity * (foreground.B - background.B) / 100) + background.B;

SolidColorBrush mixedBrush = new SolidColorBrush(Color.FromArgb(r, g, b));

A: One easy way to do it (but probably not optimized),
create a LinearGradientBrush of the two colors in repeat mode with Endpoint equals to start point:
<LinearGradientBrush SpreadMethod="Repeat" EndPoint="0,0">
                                <GradientStop Color="Red" Offset="0" />
                                <GradientStop Color="Yellow" Offset="1" />
                            </LinearGradientBrush>

This one gives you an Orange brush.


Q: How to assign color to GVIS timeline chart based on group? I have a dataset that looks like:
Start   End      GroupingVariable1 GroupingVariable2 Title
1/2/18  1/5/18   Team1             Project           Goal

I'm able to use the gvistimeline function in the gvis package to create the timeline chart that functions like a gantt chart.
gvisTimeline(data=df,
rowlabel="GroupingVariable1",
barlabel="Title",
start="start,
end="end")

How do I make the color of each timeline event the second grouping variable?

A: Found the answer. I have to have an additional column to the data that has a defined color based on the grouping variable. Once that is done passing the following argument for bar label works.
barlabel= c("Title", "Color.style")
The color column must be named anytext.style for it to work properly.


Q: What is the order of the quantifiers in the definition of big-O? Suppose $f$ and $g$ are functions. I am pretty sure that the definition of big-O has its definition conform to the following logical structure
$$\exists \, k \, \exists C \, \forall \,x\, :\, x > k \implies|f(x)| \leq C|g(x)|$$
since it also conforms to proper usage when attempting to prove by contradiction that $f$ is not big-O of $g$, but I would like confirmation.
Thanks!

A: Yes, this is correct. Under the assumption that you surely want to make that we are talking about what it means that $f$ is $O(g)$ as $x \to \infty$ (and not some other point, or still something else).
More generally, $f$ is $O(g)$ on $S$ means that there exists some $C$ such that $|f(x)| \le C |g(x)|$ for all $x \in S$ (equivalently $x \in S $ implies $|f(x)| \le C |g(x)|$).
And, $f$ is $O(g)$ as $x \to p$ means that there exists some open neighborhood $U$ of $p$ and a  $C$ (that may depend on $U$) such that $|f(x)| \le C |g(x)|$ for all $x \in U$ (equivalently $x \in U $ implies $|f(x)| \le C |g(x)|$).
The sets $\{ x \in \mathbb{R} \colon x  >k\}$ are a basis of the open neighborhoods of $+\infty$. This second statement is thus equivalently to what you said.
In particular, it is more coherent to  choose the neighborhood first and then the constant. But in the particular case you could also invert the order of the existential quantifiers and it would not yield  a different definition in this case.


Q: Check equal values in two different Columns on Google Scripts I was wondering how can I get the following result:
var X = [ex1, ex2, ex3, ex4];
var Y = [ex3, ex8, ex1, ex5];

Each one of the variables (X and Y) are in different sheets (Let's say, 'sheet' and 'sheet4'), at the column B of the respective sheet.
The output would be
= [ex3, ex1];

I then need to exclude the rows associated with ex1 and ex3 in sheet1.
I'm trying this, but the code returns nothing.
function check(){
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Página1");
    var sheet4 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Página4");
    var data1 = sheet.getRange("B1:B").getValues();
    var data4 = sheet4.getRange("B1:B").getValues();
    var lastrow1 = data1.filter(String).length;
    var lastrow4 = data4.filter(String).length;
    for (var i = 1; i <= lastrow1; i++){
        var email1 = sheet.getRange(i, 2).getValue();}
        for (var j = 1; j <= lastrow4; j++){
            var email4 = sheet4.getRange(j, 2).getValue();}
            if (email1[i] == email4[j]){
                sheet.deleteRow(i);
            }
        }
    }
}

Thank you!


Q: React Modal only close when I click background or close icon? Here is a codepen https://codesandbox.io/s/amazing-morning-ukxp2?file=/src/App.js
So I created this modal and I wrapped it with a Background styled component, but I can't figure out how to get the close function to only work if I only click the background or the close icon.
Right now my entire modal is wrapped with this background so no matter where I click it always closes. I only want it to close if I click on the Background or the CloseModalButton, but not when I click on my actual modal.
Here is my code below
      export const Modal = ({ showModal, setShowModal }) => {
        const animation = useSpring({
          opacity: showModal ? 1 : 0,
          transform: showModal ? `translateY(0%)` : `translateY(-200%)`
        });

        return (
          <>
            {showModal ? (
              <Background onClick={() => setShowModal(!showModal)}>
                <animated.div style={animation}>
                  <ModalWrapper showModal={showModal}>

hi

                    <CloseModalButton
                      aria-label='Close modal'
                      onClick={() => setShowModal(!showModal)}
                    />
                  </ModalWrapper>
                </animated.div>
              </Background>
            ) : null}
          </>
        );
      };

Then here is my App.js with the function to open and close the modal
    function App() {
      const [showModal, setShowModal] = useState(false);

      const openModal = () => {
        setShowModal(!showModal);
      };

      return (
        <Container>
          <Button onClick={openModal}>Aye what's good</Button>
          <Modal showModal={showModal} setShowModal={setShowModal} />
          <GlobalStyle />
        </Container>
      );
    }

The main issue is the Background wraps my entire modal, so I need a way to only trigger my close function if the target is the actually background or the X icon, but not the actual modal itself (which is wrapped inside of the background)

A: You need to track event.target which gives where is has been called i.e
const closeModal = (event) => {
    const modal = document.getElementById("myModal");
    if (event.target === modal) {
      setShowModal(false);
    }
  };
<Background id="myModal" onClick={closeModal}>

Here is the demo: https://codesandbox.io/s/cranky-hodgkin-o77em?file=/src/components/Modal.js

A: The problem is due to event bubbling. Everytime you click any descendants of the Background element, the click handlers of them fires and bubbles up until it reaches the Background element firing the handler of itself. To solve this, you can either stop the propagation of the click handler of the child elements using stopPropagation() method or you can simply add ID to background and determine if the id matches the background only then firing the showModal method.
<Background onClick={closeModal} id="bg">
const closeModal = (e) => {
    if (e.target.id === 'bg') {
      setShowModal(false);
    }
  };

It is not necessary to add id to the close button and check for the targeted button's id since clicking on the button definitely closes the modal.

A: I seen an comment asking how to achieve this with useRef (included typescript types):
const modalBackgroundRef = useRef<HTMLDivElement>(null);

const closeModal = () => {
    // Close the modal...
};

const onClickBackground = (event: MouseEvent<HTMLDivElement>) => {
    if (event.target === modalBackgroundRef.current) closeModal();
};

return (

          // Modal goes here...

);


Q: multiple layout in a single xml file I just want to use multiple  layout in a single xml file.I have attached my code below. In that there will be an absolute layout that should be under Horizontal scroll. As a beginner I don't know how to implement it
need your help friends..
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"

android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/aagr_background2"
android:orientation="vertical" >

<fragment
    android:id="@+id/adview153613"
    android:name="com.sentientit.theiWedplanner.Fragadmob"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

<RelativeLayout
    android:id="@+id/RelativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:background="@drawable/aanavigationbar" >

    <Button
        android:id="@+id/back"
        android:layout_width="70dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="3dp"
        android:layout_x="8px"
        android:layout_y="3px"
        android:background="@drawable/custom_btn_breaker_bay"
        android:text="Back"
        android:textColor="#ffffff"
        android:textSize="20sp" />

    <Button
        android:id="@+id/home"
        android:layout_width="50px"
        android:layout_height="30px"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/back"
        android:layout_marginRight="46dp"
        android:background="@drawable/home1"
        android:paddingBottom="12px"
        android:paddingTop="10px"
        android:visibility="gone" />

</RelativeLayout>

<AbsoluteLayout
    android:layout_width="fill_parent"
    android:layout_height="61dp" >
    <AbsoluteLayout
        android:layout_width="fill_parent"
        android:layout_height="61dp"
        android:layout_x="120dp"
        android:layout_y="35dp" >
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="38dp"
            android:layout_y="30dp"
            android:text="-   Kid Seated"
            android:textColor="#000000"
            android:textSize="13dp"
            android:typeface="serif" >
        </TextView>

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="6dp"
            android:layout_y="28dp"
            android:src="@drawable/kid" >
        </ImageView>
    </AbsoluteLayout>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="437dp"
        android:layout_y="3dp"
        android:src="@drawable/add11_table" />

    <Button
        android:id="@+id/button3"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="48dp"
        android:layout_y="4dp"
        android:text="Line"
        android:textSize="20sp" />

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="128dp"
        android:layout_y="4dp"
        android:text="circle"
        android:textSize="20sp" />

    <Button
        android:id="@+id/button2"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="212dp"
        android:layout_y="6dp"
        android:text="vshape"
        android:textSize="20sp" />

</AbsoluteLayout>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <HorizontalScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/table"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"

            android:orientation="vertical" >
        </LinearLayout>
    </HorizontalScrollView>
</ScrollView>

Thank you in advance

A: Yes, you can use use multiple layouts in single XML using the <include>.
Here is a example for that:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/app_background"
    android:orientation="vertical" >

    <include layout="@layout/actionbar_main" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/img_rest_pic"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight=".35"
            android:src="@drawable/upload_image" />
     </LinearLayout>
 </LinearLayout>

The actionbar_main.xml file is in different XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/actionBarSize"
    android:background="@drawable/navbar_txt"
    android:orientation="vertical" >

    <ImageButton
        android:id="@+id/ibtn_action_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:background="@null"
        android:src="@drawable/navbar_back" />

    <ImageButton
        android:id="@+id/ibtn_action_settings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/ibtn_action_back"
        android:layout_marginRight="5dp"
        android:background="@null"
        android:src="@drawable/nacbar_setting" />

    <View
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_alignParentBottom="true"
        android:background="@color/white" />

</RelativeLayout>

A: Not sure whether your looking for this alignment but i just gave a shot..... whenever you wish to fix layout at the bottom of screen make sure you use weight property i.e if you want fix button at the bottom of screen then put android:layout_height = "0dp" and layout_weight="1" for other major layout in the xml and to button which has to be fixed at the bottom use android:layout_height="wrap_content" and layout_weight = "0" that's all is the trick (sorry if i have made it hard to understand... just simply saying play with weight and height property)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#fff"
    android:orientation="vertical" >

    <fragment
        android:id="@+id/adview153613"
        android:name="com.sentientit.theiWedplanner.Fragadmob"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <RelativeLayout
        android:id="@+id/RelativeLayout1"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"  >

        <Button
            android:id="@+id/back"
            android:layout_width="70dp"
            android:layout_height="50dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="3dp"
            android:layout_x="8px"
            android:layout_y="3px"
            android:text="Back"
            android:textColor="#ffffff"
            android:textSize="20sp" />

        <Button
            android:id="@+id/home"
            android:layout_width="50px"
            android:layout_height="30px"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@+id/back"
            android:layout_marginRight="46dp"
            android:paddingBottom="12px"
            android:paddingTop="10px"
            android:visibility="gone" />
    </RelativeLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical" >

        <HorizontalScrollView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <LinearLayout
                android:id="@+id/table"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical" >
            </LinearLayout>
        </HorizontalScrollView>
    </ScrollView>

    <AbsoluteLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0" >

        <AbsoluteLayout
            android:layout_width="fill_parent"
            android:layout_height="61dp"
            android:layout_x="120dp"
            android:layout_y="35dp" >

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_x="38dp"
                android:layout_y="30dp"
                android:text="-   Kid Seated"
                android:textColor="#000000"
                android:textSize="13dp"
                android:typeface="serif" >
            </TextView>

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_x="6dp"
                android:layout_y="28dp" >
            </ImageView>
        </AbsoluteLayout>

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="437dp"
            android:layout_y="3dp" />

        <Button
            android:id="@+id/button3"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="48dp"
            android:layout_y="4dp"
            android:text="Line"
            android:textSize="20sp" />

        <Button
            android:id="@+id/button1"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="128dp"
            android:layout_y="4dp"
            android:text="circle"
            android:textSize="20sp" />

        <Button
            android:id="@+id/button2"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="212dp"
            android:layout_y="6dp"
            android:text="vshape"
            android:textSize="20sp" />
    </AbsoluteLayout>
</LinearLayout>


Q: Why can't I log in after unistalling Python 2.7 and installing Python 3? I uninstalled the Python 2.7 package to try and upgrade to Python 3. I uninstalled Python 2.7, and noticed some of my launcher items were completely gone. At this point I had installed Python 3. Now on reboot, I can't log in and the background for the log-in screen is black with white dots. Any help would be greatly appreciated.
P.S. - This is running 11.10 Oneiric Ocelot. I still have the same version Live CD.
EDIT: Thanks for the feedback! But I can't boot into text mode, only boot from the Live CD, and I can't connect to the internet because I installed the Debian .tar.gz package usb_modeswitch for Mobile Broadband. Is there a way to copy the Python 2.7 parts of the OS from the Live CD and inject them into my system? The only thing I can think of is get a 12.04 Live CD and click 'Upgrade from 11.10 to 12.04' option, but for reasons I won't go into this is impractical for me.

A: You don't have to, and you shouldn't, uninstall python2.7 to install python3. You can have both packages installed at the same time. Many parts of Ubuntu require python2.7. Reinstall the packages you've uninstalled, and that should fix the problem. If you're having a problem installing python3 while python2.7 is installed, or you are having trouble getting python code to run in python3 instead of python2.7, please edit your question to include the relevant details.
If you're not sure which python2.7 related packages you removed, you can look in the log files that start with dpkg and are located in /var/log. If the removal operations were pretty recent, you can just look in /var/log/dpkg itself (i.e., the file called just dpkg and located in the /var/log folder).

A: I think many applications have strong dependencies with Python 2.7. But you can install Python 3 without uninstalling Python 2.7.
So, if you can login in text mode, just type this in order to install Python 2.7:
sudo apt-get install python

Then you can reboot your computer:
sudo reboot

If I understand you, you have Python 3 installed. But if not, just type:
sudo apt-get install python3

This last line does not uninstall Python 2.7.
Ariel.


Q: Statistical analysis pre + post testing- with control and intervention 35 participants What statistical analysis would I use when testing 35 participants. pre & post test and checking for changes after 1 intervention and a control group with no intervention?
I have one mediating variable, 3 independent variables and two dependent variables.

A: Is your dataset normally distributed or not?
Supposing it is, you could perform paired T-tests, testing for significantly different responses in the pre and post.
Supposing it is not normally distributed, you could perform the non-parametric McNemar's (Bowker's) test to receive basically the same information as a T-test.
Your sample size is on the lower end so I would not recommend performing regression.


Q: Ghost not working on CentOs 7 despite clean install I followed most of this tutorial to install Ghost on CentOs 7 but, despite the install going perfectly I am unable to see the welcome page.
Here are a list of commands I used, let me know if I made a mistake somewhere.
$ yum -y update
$ yum -y install gcc-c++ openssl-devel
$ cd /usr/local/src && wget -O node-latest.tar.gz http://nodejs.org/dist/node-latest.tar.gz
$ tar -xzf node-latest.tar.gz
$ cd node-v* # example:  cd node-v0.10.33/
./configure
make && make install
cp /usr/local/bin/node /usr/bin/node
cp /usr/local/bin/npm  /usr/bin/npm
mkdir  -p /var/www/ && cd /var/www/
curl -L -O https://ghost.org/zip/ghost-latest.zip
unzip -d ghost ghost-latest.zip
cd ghost
useradd ghost
chown -R ghost:ghost /var/www/ghost/
npm install --production
npm start --production

At this point I can see the success message, and that ghost is installed
> ghost@0.5.6 start /var/www/ghost
> node index

Migrations: Up to date at version 003
Ghost is running...
Your blog is now available on http://my-ghost-blog.com
Ctrl+C to shut down

But, I went to localhost:2368 and 127.0.0.1:2368 but nothing shows up. just an browser 404 error.
I thought this might be a port issue so, I tried to open a port
firewall-cmd --zone=dmz --add-port=2368/tcp

tried permanent, reload ... still nothing.


Q: Method was expected to be of type virtual I've tried to initialize AWSMobileClient.defaultMobileClient() from my AWS Mobile Hub sample project into my test project using this code:
if (AWSMobileClient.defaultMobileClient() == null) {
        Log.e("MainActivity", "Initializing AWS Mobile Client...");
        final ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setUserAgent(AWSConfiguration.AWS_MOBILEHUB_USER_AGENT);
        final IdentityManager identityManager = new IdentityManager(getApplicationContext(), clientConfiguration);
        final AWSMobileClient awsClient =
                new AWSMobileClient.Builder(getApplicationContext())
                        .withCognitoRegion(AWSConfiguration.AMAZON_COGNITO_REGION)
                        .withCognitoIdentityPoolID(AWSConfiguration.AMAZON_COGNITO_IDENTITY_POOL_ID)
                        .withIdentityManager(identityManager)
                        .withClientConfiguration(clientConfiguration)
                        .build();

        AWSMobileClient.setDefaultMobileClient(awsClient);
    }

When I opened the app in my device, I got this error log in the Android Studio:
09-21 13:01:34.596 28886-28886/com.intap.snspushtest E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.intap.snspushtest, PID: 28886
   java.lang.IncompatibleClassChangeError: The method 'java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)' was expected to be of type virtual but instead was found to be of type direct (declaration of 'com.google.android.gms.iid.zzd' appears in /data/app/com.intap.snspushtest-1/base.apk)
       at com.google.android.gms.iid.zzd.zzeC(Unknown Source)
       at com.google.android.gms.iid.zzd.<init>(Unknown Source)
       at com.google.android.gms.iid.zzd.<init>(Unknown Source)
       at com.google.android.gms.iid.InstanceID.zza(Unknown Source)
       at com.google.android.gms.iid.InstanceID.getInstance(Unknown Source)
       at com.amazonaws.mobile.push.GCMTokenHelper.<init>(GCMTokenHelper.java:44)
       at com.amazonaws.mobile.AWSMobileClient.<init>(AWSMobileClient.java:121)
       at com.amazonaws.mobile.AWSMobileClient.<init>(AWSMobileClient.java:24)
       at com.amazonaws.mobile.AWSMobileClient$Builder.build(AWSMobileClient.java:101)
       at com.intap.snspushtest.MainActivity.onCreate(MainActivity.java:43)
       at android.app.Activity.performCreate(Activity.java:6876)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
       at android.app.ActivityThread.access$1100(ActivityThread.java:221)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:158)
       at android.app.ActivityThread.main(ActivityThread.java:7224)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

The lines are as below.

AWSMobileClient.java:121
        this.gcmTokenHelper = new GCMTokenHelper(context, AWSConfiguration.GOOGLE_CLOUD_MESSAGING_SENDER_ID);

AWSMobileClient.java:24
public class AWSMobileClient {

AWSMobileClient.java:101
            return
            new AWSMobileClient(applicationContext,
                                cognitoIdentityPoolID,
                                cognitoRegion,
                                identityManager,
                                clientConfiguration);

MainActivity.java:43
final AWSMobileClient awsClient =
                new AWSMobileClient.Builder(getApplicationContext())
                        .withCognitoRegion(AWSConfiguration.AMAZON_COGNITO_REGION)
                        .withCognitoIdentityPoolID(AWSConfiguration.AMAZON_COGNITO_IDENTITY_POOL_ID)
                        .withIdentityManager(identityManager)
                        .withClientConfiguration(clientConfiguration)
                        .build();

I don't really understand what problem I am facing with, so could you please help me?

A: I have changed my Google Play Services library version from 9.0.0 to 9.0.1 and it solved it.


Q: What is the difference between Calling a method by one of the three methods? What is the difference between Calling a method by one of the three methods ?

*

*via Creating a new thread

*Synchronous call through Invoke

*Asynchronous call through BeginInvoke and alternatively EndInvoke

I am assuming all the calls will be using a matching delegate under the hood.

A: (Assuming .NET given your user name...) These three options are different ways to use a delegate.
Creating a new thread doesn't specifically "call a method", but rather starts a new thread using a specified delegate as the method to run within the new thread.  This will launch an entire new thread for you, and run your delegate within the separate thread.
Asynchronously calling the delegate via BeginInvoke/EndInvoke is similar, except that it will use the ThreadPool instead of creating a new thread.
Synchronously calling the delegate via Invoke will just call the delegate directly on the currently executing thread.  This effectively just calls the method being referenced by the delegate.


Q: Importing to IntelliJ - Error package org.springframework.boot does not exist Dear Stackoverflow Community, I have the following problem with my spring boot starter application. I imported the starter project as a new maven project into IntelliJ. But IntelliJ does not find the dependencies I specified in the pom.
Image of my Application Class:

If I try to run the project I get the following error message.
Image of the Error Message:

I already tried everything from re-installing IntelliJ to re-importing the project or redownloading the dependencies. I simply dont know why IntelliJ doesn´t find the dependencies.
My pom.xml looks as following
Image of my pom.xml:

The first time I tried to edit the pom.xml it said to me "this file does not belong to the project". Maybe this might be one reason.
Running the whole thing with 'mvn install' or 'mvn clean verify' works.

A: Sometimes your workspace could get corrupted.
In my case, I tried to Reload the project and it worked

A: in my case changed JDK version in Maven importer from JDK 11 to my local JDK version 1.8

A: Try this and then build: mvn -U idea:idea

A: Had the same problem. I have tried everything: invalidating cache, deleting the whole .m2 folder, changing settings, reloding the project, nothing helped.
The solution for me was to delete the .iml files which are IntelliJ module files used for keeping module configuration. After reopening the project it worked.
The idea was not mine, I found the hint here: https://intellij-support.jetbrains.com/hc/en-us/community/posts/203365204--package-does-not-exist-error-despite-autocomplete-being-aware-of-them

A: Here is how my IntelliJ settings for spring boot application looks like
Click open -> browse your workspace -> and select POM.xml file

Check this in your intelliJ settings

Do this too [Settings --> Maven --> Importing]

A: I just had the same issue.  My solution was to remove all dependencies from the pom, reload via maven -> Reload All Maven Projects.  Run mvn compile.  Add dependencies back to the pom, maven -> Reload All Maven Projects.  Run mvn compile.
Now the Intellij build works.

A: You need to change Maven's JDK for importing option from Project JDK to the Path variable for Java on your machine.
You can get to this by going to Settings -> Build, Execution, Deployment -> Build Tools -> Maven -> Importing. Scroll down to the bottom and look for JDK for importing:. Select from the list the path variable for JAVA.

For Windows users, JAVA_HOME should be an option in the drop-down list.

A: Follow these steps, your problem should be solved. You just need to add Spring-framework-starter-web and Spring-framework-starter-tester from your pom.xml file.

*

*Got to generate(ALT+Insert)

*Add dependencies

*Search "springframwork"

*Add...

Here is the link

A: In my case, adding the project as maven project helped .


Q: Using a wrapper class to hide functions A colleague of mine preferes to encapsulate all of the PHP functions behind classes. His justification seems to be that if its in a class its going to be easier to change if they ever update the code. My concern after looking at his code is I have no clue what might be happening, or why things might error out. Additionally if it were in class form I'd prefer a a static function to what he is doing as it seems to me would be better practice.
For example instead of:
$var = filter_var('0755', FILTER_VALIDATE_INT);

He would have:
class Filter {
     public function filterInt($var) {
           return filter_var($var, FILTER_VALIDATE_INT);
     }
}

$filter = new Filter();
$var = $filter->filterInt('0755');

Which way would be better practice? better for long term performance? better for understanding?

A: Hiding functionality in methods is good practice, Code Complete explains quite well, why that's the case.
If you ever want to change the filterInt, e.g. add upper and lower bounds, you are way better off if you have encapsulated it.

*

*less code lines to be changed

*easier to test against

*..

A: For only one method like your example, it does not make much sense.
It start to make sense if you use it to group all your filter function here, you could have Filter::filterDeliveryAdress and then, anytime you have to filter something you might remember that you already have a function for this. So if you filter function is for exsample not accurate enough, you can fix it in the class to get it fixed in all your code.
Of course here a static function would be better, it's even easier to use.
If, as I think, it's only for grouping related function and your using PHP >= 5.3, namespace would be more appropriate.


Q: Android wear app with Line App Integration I would like to know more about the weather android wear will support the Line app or not. I've an requirement that sign-In with Line app. When I pair with the device and watch, where I could not able to see the my line app in android watch. Please suggest me the best possible solutions.
Please revert back for any clarification.

A: There's no indication at http://line.me that LINE supports Android Wear. So if LINE isn't running on the watch, you'll need to build an interface with the phone, and connecct to the LINE API there.
Get started with the documentation at https://developer.android.com/training/wearables/data-layer/index.html


Q: How to get velocity vector for a point of a fixture? (Box2d) I have a top-down view tank project written in C++(QT). The tank consists of a "base" which is connected through a revjoint to the "turret" which can rotate and shoot. Turret is a circle shape and a rectangle attached to it as the barrel. Quite basic.
When a projectile is shot, its initial velocity vector should be added to the velocity vector of the tip of the barrel, otherwise the shot is unrealistic if the tank or the barrel moves. I can get only the velocity vector of a body, and it is not enough here, since the velocity vector of the tip of the barrel is a different thing then the velocity vector of the turret body.
I tried to weldjoint a fixtureless body to the tip of the barrel as a "muzzle". The muzzle body velocity vector is exactly the one I'm looking for. It didn't work though, the welded fixtureless body constrained the turret from rotating for some reason.
Then I did the same with a body with a fixture. It works, but seems overcomplicated solution, brings in new issues.
My questions are:

*

*Is there any issues with fixtureless bodies I'm not aware of? Why I can't them just weld somewhere for easily accessing the speed vector of that point?

*Is there any "standard" solution to get the velocity vector of an arbitrary point of a fixture?
Daniel

A: I think the function you are looking for is b2Body::GetLinearVelocityFromWorldPoint
https://code.google.com/p/box2d/source/browse/trunk/Box2D/Box2D/Dynamics/b2Body.h#273
You can get the 'world point' of the end of the gun barrel with b2Body::GetWorldPoint.
To find the direction of the gun in world coordinates, b2Body::GetWorldVector might be useful.

A: I'm answering my own question after some research.

*

*If a body is used without any fixtures, be sure to set some mass to it manually, otherwise it'll behave unexpected. After doing so, the muzzle body's paramaters were exactly I was about using them. Here's how to set mass to a body without any fixtures.
b2MassData md;
md.center = b2Vec2(0,0);
md.I = 0.000001f;
md.mass = 0.000001f;
body->SetMassData(&md);

*An other solution might be the one iforce2d posted. Thanks for that, I'll check it out!


Q: Running Java program with custom directory structure as Windows service I am using YAJSW to install (and uninstall) my program as Windows service (win 32 and win 64) with the following directory structure.
How do I go about it ?
 apps - user works with this dir
 log - user works with this dir
 core - core of my program, user not works with this dir, here may be anything, include wrappers.
 install.cmd - user launch it to install software as windows service
 uninstall.cmd - user launch it to uninstall windows service
 settings.cmd - a very short file with user properties. javapath, ntservicename, dburl, dbuser, dbpass at all - user edit it.

A: Here is the comprehensive tutorial..
http://yajsw.sourceforge.net/
and one for windows service
https://docs.wso2.org/display/Carbon403/Installing+as+a+Windows+Service

A: You can play around with the scripts located in yajsw/bat, specifically with setenv.bat.
That is the script that creates your environment variables.

A: I found and look throught about 20 wrappers and helpers. Some of them is payd, some of them needs code modification, some complex, some have issues. I found only one good solution - NSSM   . I think it solve the problems as it must be solved.


Q: Regex match last occurrence of a string from multiple lines I'm trying to match the last occurrences of a string from a log file.
[03/03/2019 09:16:36] Moving message 123456789 from NEW to PENDING
[03/03/2019 09:16:36] Retrieving file(s) of type DATAWAREHOUSE for 123456
[03/03/2019 09:16:36] collecting warehouse version 7.3.1 files for 123456...
[03/03/2019 09:16:37] Moving message 123456789 from NEW to PENDING
[03/03/2019 09:16:37] Retrieving file(s) of type DATAWAREHOUSE for 123456
[03/03/2019 09:16:37] collecting warehouse version 7.3.1 files for 123456...
[03/03/2019 09:16:38] Moving message 123456789 from NEW to PENDING
[03/03/2019 09:16:39] Retrieving file(s) of type DATAWAREHOUSE for 123456
[03/03/2019 09:16:40] collecting warehouse version 7.3.1 files for 123456...

Above is the sample log file from which there are three occurrences of the below string,
Moving message 123456789 from NEW to PENDING

I need to match the last occurrence to get the respective timestamp "[03/03/2019 09:16:38]".
But when all these are in a single line using greedy approach (.*) it works fine. But when they are present in multiple lines it isn't working. I haven't tried multiline (m) as I'm not sure how to use it. Can someone please help me construct the regex query to retrive this last occurrence timestamp?
Example: https://regex101.com/r/fnwPsB/1

A: You may use
(?s:.*\n)?\K\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING

See the regex demo
Details

*

*(?s:.*\n)? - an inline modifier group that matches any 0+ chars as many as possible up to the last LF char that is followed with the last occurrence of the subsequent patterns.

*\K  - match reset operator removing all text matched so far from the match memory buffer

*\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING - the specific line pattern to get with the datetime captured in Group 1.

Alternatively, use
(?s)(\[\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2}\] Moving message 123456789 from NEW to PENDING)(?!.*(?1))

See this regex demo.
Details

*

*(?s) -  DOTALL modifier making . match any char

*(\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING) - the necessary pattern to match captured into Group 1 and the datetime in Group 2

*(?!.*(?1)) - a negative lookahead that fails the match if there is the same pattern as defined in Group 1 after any  0+ chars to the right of the current position.

A: Here is a solution that is not dependent on PCRE feature using negative lookahead:
(?s)\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING(?!.* Moving message 123456789 from NEW to PENDING)

RegEx Demo
Date-time is available in 1st capture group.
Here (?!.* Moving message 123456789 from NEW to PENDING) is negative lookahead that ensures we match very last occurrence of given pattern.


Q: FirebaseAnimatedList doesn't return anything I'm trying to write an app that will detect Barcode ID. Once detected, it will fetch value in my Firebase Database and display them inside my Widget. I want my widget to be dynamic since i don't know how many items could be inside each ID. So i tried using FirebaseAnimatedList class. Issue is i can't get my Widget show up in my page at all.
Here's my code
import 'dart:async';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:logistec/widget/result_page/productlist.dart';

class Scanning_Result_Page extends StatefulWidget {
  Scanning_Result_Page(this.phyid, {Key? key}) : super(key: key);
  String phyid;

  @override
  State<Scanning_Result_Page> createState() => _Scanning_Result_PageState();
}

class _Scanning_Result_PageState extends State<Scanning_Result_Page> {
  late String productcode;
  late String productname;
  late int quantity;
  late Query _ref =
      FirebaseDatabase.instance.ref().child('Database').child(widget.phyid);

//firebase structure currently goes like this
//PHYID
//|---number
//|-----items_name
//|-----items_codes etc...
//Therefore i need it to first fetch PHYID
//then after that, use for loop from 0 to the full lenght of that ID
//

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: PreferredSize(
          preferredSize: Size(40, 40),
          child: AppBar(
            backgroundColor: Colors.amber.shade400,
          )),
      body: Container(
        height: double.infinity,
        child: FirebaseAnimatedList(
          shrinkWrap: true,
          query: _ref.equalTo(widget.phyid),
          itemBuilder: (BuildContext context, DataSnapshot snapshot,
              Animation<double> animation, int index) {
            Map database = snapshot.value as Map;
            if (database != null) {
              //result = key - phyid | value - 0?
              return ProductList(
                productcode: 'Test 1', //will change this later. just need it to work for now.
                productname: 'Test 1',
                serial: 'Test 1',
                quantity: 1,
                phyid_result: widget.phyid,
              );
            } else {
              return Text("no data");
            }
            return CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}

And here's my Widget page. (I don't think it's related to my issue but i'll include them regardless.)
import 'package:flutter/material.dart';

class ProductList extends StatelessWidget {
  ProductList({
    Key? key,
    required this.productcode,
    required this.productname,
    required this.quantity,
    required this.phyid_result,
    required this.serial,
  }) : super(key: key);

  final String productcode;
  final String productname;
  final int quantity;
  final String phyid_result;
  final String serial;
  //The Look in my head
  //Each Container will have
  ///////////////////////////////////
  ///ProductCode                    /
  ///ProductName                    /
  ///                               /
  /// ///////////////////////////////
  ///                       Quantity/
  /// ///////////////////////////////
  final appBar = AppBar();
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        resizeToAvoidBottomInset: false,
        body: CustomScrollView(
          scrollDirection: Axis.vertical,
          slivers: [
            SliverList(
                delegate: SliverChildListDelegate([
              Container(
                padding: const EdgeInsets.all(15.0),
                alignment: Alignment.center,
                color: Colors.black,
                height: 70.0,
                child: Text(
                  phyid_result,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 25,
                  ),
                ),
              ),
              Container(
                height: screenSize.size.height,
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey.shade600)),
                child: IntrinsicHeight(
                  child: Column(
                    //mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.all(5),
                        child: Text(
                          productcode,
                          style: const TextStyle(fontSize: 20),
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.all(5),
                        width: screenSize.size.width,
                        decoration: BoxDecoration(
                            border: Border.all(
                                color: Colors.grey.shade200,
                                strokeAlign: StrokeAlign.inside)),
                        child: Text(
                          productname,
                          style: const TextStyle(fontSize: 20),
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.all(5),
                        width: screenSize.size.width,
                        decoration: BoxDecoration(
                            border: Border.all(
                                color: Colors.grey.shade200,
                                strokeAlign: StrokeAlign.inside)),
                        child: Text(
                          serial,
                          style: const TextStyle(fontSize: 20),
                        ),
                      ),
                      Align(
                        alignment: Alignment.topRight,
                        child: Flexible(
                          fit: FlexFit.loose,
                          child: SizedBox(
                            width: 90,
                            child: Container(
                                decoration: BoxDecoration(
                                  border:
                                      Border.all(color: Colors.grey.shade200),
                                ),
                                padding: EdgeInsets.all(5),
                                child: Text(
                                  'Quantity : \n\v${quantity}',
                                  style: TextStyle(fontSize: 18),
                                  textAlign: TextAlign.right,
                                )),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ]))
          ],
        ),
      ),
    );
  }
}

The Scaffold part works. But everything inside FirebaseAnimated List all the way to CircularProgressIndicator doesn't work at all. It didn't even return if else statement. Just empty blank page with Scaffold.
The Widget itself will work fine if i remove everything out, and return only the ProductList widget itself. I tried searching on Google and didn't find anyone having issue like me. So i think i'm stuck. Does anyone know what could be the issue? Thanks for the assistance in advance!

A: So i solve my own issue.
It turns out that my Widget is the actual root cause. I don't think SliverList is playing well with FirebaseAnimatedList (maybe because they are doing essentially the same thing?) So i refactor and remove everything related to SliverList.
Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context);
    return Container(
      decoration:
          BoxDecoration(border: Border.all(color: Colors.grey.shade600)),
      child: Column(
        //mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(5),
            child: Text(
              productcode,
              style: const TextStyle(fontSize: 20),
            ),
          ),
          Container(
            padding: EdgeInsets.all(5),
            width: screenSize.size.width,
            decoration: BoxDecoration(
                border: Border.all(
                    color: Colors.grey.shade200,
                    strokeAlign: StrokeAlign.inside)),
            child: Text(
              productname,
              style: const TextStyle(fontSize: 20),
            ),
          ),
          Container(
            padding: EdgeInsets.all(5),
            width: screenSize.size.width,
            decoration: BoxDecoration(
                border: Border.all(
                    color: Colors.grey.shade200,
                    strokeAlign: StrokeAlign.inside)),
            child: Text(
              serial,
              style: const TextStyle(fontSize: 20),
            ),
          ),
          Align(
            alignment: Alignment.topRight,
            child: Flexible(
              fit: FlexFit.loose,
              child: SizedBox(
                width: 90,
                child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey.shade200),
                    ),
                    padding: EdgeInsets.all(5),
                    child: Text(
                      'Quantity : \n\v${quantity}',
                      style: TextStyle(fontSize: 18),
                      textAlign: TextAlign.right,
                    )),
              ),
            ),
          )
        ],
      ),
    );

Then i reimplemented it into my pages. Now it works as expected. all is well again!


Q: EAS build development for IOS fails on Pods install I hope someone can help me, when i try to build an app using expo with the command  eas build --profile development --platform ios, it gives me the error below "The following Swift pods cannot yet be integrated as static libraries: ...". This happens only on IOS, android is working fine, i try to look for a solution but didn't find a lot of information regarding this issue...
Any solution ?
This is the error message in the expo logs.
[!] The following Swift pods cannot yet be integrated as static libraries:

The Swift pod `FirebaseCoreInternal` depends upon `GoogleUtilities`, which does not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.

The Swift pod `FirebaseStorage` depends upon `FirebaseStorageInternal`, `FirebaseAppCheckInterop`, `FirebaseAuthInterop`, `FirebaseCore`, and `FirebaseCoreExtension`, which do not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.

pod exited with non-zero code: 1

Printscreen of error log


Q: API & app for sending notifications to iPhone? In a project I'm working on, I want to send notifications to my user's iPhone from my Chrome extension. The notifications will mostly be about their accounts on my site, and I would like them to be able to reply with the type of action they want taken concerning the alerts.
To help me do this, I found http://pushme.to/1 which works by allowing the iPhone owner to download their app, create an account via that app, and from then on be able to receive
"IM"-like messages and push notifications. I can send my iPhone users messages via http://pushme.to/iphone_users_username by automating that page with javascript. However, it will be imperative that I also send images along with the alerts, and am unable to do that as the site uses a flash uploader.
[EDIT: To clarify - pushme.to has a feature that allows you to send along images with a message, this is what I was referring to]
So, to cut to the chase and hit the bottom line: does anyone know of an app the provides a companion app & API for sending messages that the user can reply to? Meaining that the user receives my messages, can reply to them - and my Chrome Extension receive their replies?
Thanks in advance!

1 Service no longer active

A:
However, it will be imperative that I also send images along with the alerts

I might be misunderstanding your question, but the push notification framework doesn't support images. You can only send text, badges (the red numbers next to an app icon), or sounds (which must already be installed in the app bundle).
Perhaps you can use a third-party option to do it, but push.me wasn't really designed for automated comms, but for friend to friend IMs. You may have to create your own app to achieve this...I'm not sure of any third party app you could use.


Q: Run-time 438 on searching and pasting gender I am running the following code that takes a value from column A, searches it on the URL: https://gender-api.com and returns the gender of the person and pastes it in column B.
I get a

run-time error 438

when running the code. Please help.
Sub URL_Get_Gender_Query()
    strSearch = Range("a4")
    With ActiveSheet.QueryTables.Add(Connection:="URL;https://gender-api.com?SearchText=" & strSearch & "&safe=active", _Destination:=Range("b4"))
        '^ Run-time error 438 here

        .BackgroundQuery = True
        .TablesOnlyFromHTML = True
        .Refresh BackgroundQuery:=False
        .SaveData = True
    End With
End Sub

A: Here's another way to do it, using the WinHttpRequest object:
Dim httpRequest As Object
Dim url As String
Dim i As Long
Dim jsonResponse As String

Set httpRequest = CreateObject("MSXML2.ServerXMLHTTP")
url = "https://gender-api.com/get?name=elizabeth" ' For example
httpRequest.Open "POST", url, False
httpRequest.send
jsonResponse = httpRequest.ResponseText
MsgBox jsonResponse


Q: Polymorphic queries with NHibernate Search I have multiple entities stored in a single NHibernate Search index, in the hope that I'd be able to query over all of them at once. The use case is a simple search page which returns mixed results. So, for example, the code could look like this:
public interface ISearchable {}

[Indexed(Index = "TheIndex")]
public class SearchableEntityA : ISearchable
{
    // Some [Field]s
}

[Indexed(Index = "TheIndex")]
public class SearchableEntityB : ISearchable
{
    // Some other [Field]s
}

This all indexes fine, and of course is queryable in raw NHibernate like so:
session.CreateCriteria<ISearchable>().List<ISearchable>();

I have some fields on ISearchable, but these aren't specifically referenced in NHibernate mappings.
My hope was that I could just say:
var query = "some keyword";
fullTextSession.CreateFullTextQuery<ISearchable>(query).List<ISearchable>();

And retrieve a list of ISearchables, containing results from various different entities. However, the reality is that it throws NHibernate.HibernateException: Not a mapped entity: NetComposites.Model.ISearchable.
So, what's the simplest way to achieve something resembling polymorphic queries with NHibernate Search?

A: An overload of CreateFullTextQuery exists that allows you to specify the types to search:
fullTextSession.CreateFullTextQuery(query, typeof(EntityA), typeof(EntityB)).List<ISearchable>();

It's a little clunky having to specify all the types, but they load fine. The only remaining problem I have is that my assumption that you could just do an all fields search by default was incorrect, so it requires building a MultiFieldQueryParser over all properties of all searchable entities:
private static Query ParseQuery(string query, IFullTextSession searchSession)
{
    var parser = new MultiFieldQueryParser(GetAllFieldNames(searchSession), new StandardAnalyzer());
    return parser.Parse(query);
}

private static string[] GetAllFieldNames(IFullTextSession searchSession)
{
    var reader =
        searchSession.SearchFactory.ReaderProvider.OpenReader(
            searchSession.SearchFactory.GetDirectoryProviders(typeof (Company)));
    var fieldNames = reader.GetFieldNames(IndexReader.FieldOption.ALL);
    return fieldNames.Cast<string>().ToArray();
}


Q: Zookeeper install via Ambari Performing install via Ambari 1.7 and would like to get some clarification regarding the Zookeeper installation. The setup involves (3) Zookeeper and (3) Kafka instances.
Ambari UI asks to specify Zookeeper master(s) and Zookeeper clients/slaves. Should I choose all three Zookeeper nodes as masters and install Zookeeper client on each Kafka server?
Zookeeper doesn't have any master node(s) and I am a little confused here with this Ambari master/slave terminology.

A: Zookeeper Server is considered a MASTER component in Ambari terminology. Kafka has the requirement that Zookeeper Server be installed on at least one node in the cluster. Thus the only requirement you have is to install Zookeeper server on one of the nodes in your cluster for Kafka to function. Kafka does not require Zookeeper clients on each Kafka node.
You can determine all this information by looking at the Service configurations for KAFKA and ZOOKEEPER. The configuration is specified in the metainfo.xml file for each component under the stack definition. The location of the definitions will differ based on the version of Ambari you have installed.
On newer versions of Ambari this location is:
   /var/lib/ambari-server/resources/common-services/<service name>/<service version>

On older version of Ambari this location is:
  /var/lib/ambari-server/resources/stacks/HDP/<stack version>/services/<service name>


Q: Qt signal/slots - consume signal in one of many slots? Is there a way to consume future slots (and stop them from executing) in one of many slots connected to the same signal?
My goal here is to emit a signal with a message to many QObjects and consume (stopping iteration to future slots) when the QObject in which the message belongs to finds it.
From what I understand in the Qt Documentation:

If several slots are connected to one signal, the slots will be
executed one after the other, in the order they have been connected,
when the signal is emitted.

I want to be able to stop this process from within a slot.
Suggestions?

A: No, there's no way to do it, and you should not think of it this way. The sender should perform the same no matter what number of slots are connected to a signal. That's the basic contract of the signal-slot mechanism: the sender is completely decoupled from, and unaware of, the receiver.
What you're trying to do is qualified dispatch: there are multiple receivers, and each receiver can process one or more message types. One way of implementing it is as follows:

*

*Emit (signal) a QEvent. This lets you maintain the signal-slot decoupling between the transmitter and the receiver(s).

*The event can then be consumed by a custom event dispatcher that knows which objects process events of given type.

*The objects are sent the event in the usual fashion, and receive it in their event() method.
The implementation below allows the receiver objects to live in other threads. That's why it needs to be able to clone events.
class <QCoreApplication>
class <QEvent>

class ClonableEvent : public QEvent {
  Q_DISABLE_COPY(ClonableEvent)
public:
  ClonableEvent(int type) : QEvent(static_cast<QEvent::Type>(type)) {}
  virtual ClonableEvent * clone() const { return new ClonableEvent(type()); }
}
Q_REGISTER_METATYPE(ClonableEvent*)

class Dispatcher : public QObject {
  Q_OBJECT
  QMap<int, QSet<QObject*>> m_handlers;
public:
  Q_SLOT void dispatch(ClonableEvent * ev) {
    auto it = m_handlers.find(ev->type());
    if (it == m_handlers.end()) return;
    for (auto object : *it) {
      if (obj->thread() == QThread::currentThread())
        QCoreApplication::sendEvent(obj, ev);
      else
        QCoreApplication::postEvent(obj, ev.clone());
    }
  }
  void addMapping(QClonableEvent * ev, QObject * obj) {
    addMapping(ev->type(), obj);
  }
  void addMapping(int type, QObject * obj) {
    QSet<QObject*> & handlers = m_handlers[type];
    auto it = handlers.find(obj);
    if (it != handlers.end()) return;
    handlers.insert(obj);
    QObject::connect(obj, &QObject::destroyed, [this, type, obj]{
      unregister(type, obj);
    });
    m_handlers[type].insert(obj);
  }
  void removeMapping(int type, QObject * obj) {
    auto it = m_handlers.find(type);
    if (it == m_handlers.end()) return;
    it->remove(obj);
  }
}

class EventDisplay : public QObject {
  bool event(QEvent * ev) {
    qDebug() << objectName() << "got event" << ev.type();
    return QObject::event(ev);
  }
public:
  EventDisplay() {}
};

class EventSource : public QObject {
  Q_OBJECT
public:
  Q_SIGNAL void indication(ClonableEvent *);
}

#define NAMED(x) x; x.setObjectName(#x)
int main(int argc, char ** argv) {
  QCoreApplication app(argc, argv);
  ClonableEvent ev1(QEvent::User + 1);
  ClonableEvent ev2(QEvent::User + 2);
  EventDisplay NAMED(dp1);
  EventDisplay NAMED(dp12);
  EventDisplay NAMED(dp2);

  Dispatcher d;
  d.addMapping(ev1, dp1);  // dp1 handles only ev1
  d.addMapping(ev1, dp12); // dp12 handles both ev1 and ev2
  d.addMapping(ev2, dp12);
  d.addMapping(ev2, dp2);  // dp2 handles only ev2

  EventSource s;
  QObject::connect(&s, &EventSource::indication, &d, &Dispatcher::dispatch);

  emit s.indication(&ev1);
  emit s.indication(&ev2);
  return 0;
}

#include "main.moc"

A: If connection was in one thread, I think that you can throw an exception. But in this case you should be catch any exception during emit a signal:
try {
    emit someSignal();
} catch(...) {
    qDebug() << "catched";
}

But I think that it's bad idea. I'll would be use event dispatching for this.


Q: "The User Profile Service failed the logon. User profile cannot be loaded." on new user I have created new user without connecting it to phone number and to Microsoft account. Now I am wishing to logon as it but failing with a message:
The User Profile Service failed the logon. User profile cannot be loaded.

The resolutions from here https://support.microsoft.com/en-us/kb/947215 do not work.
Method #1 fails because I don't have appropriate registry entry.
Method #2 is not applicable, because the user is already new.


Q: How to integrate role based access token authentication for API methods generated using node-restful package? I am using the node-restful package for automatic API generation.
But I am not sure how to integrate role based access token validation for each of the automatically generated API methods GET, POST, PUT and DELETE
For Eg:
var Resource = app.resource = restful.model('resource', mongoose.Schema({
    title: String,
    year: Number,
  }))
  .methods(['get', 'post', 'put', 'delete']);

Resource.register(app, '/resources');

I want admin to have access to all the above methods but a normal user should have access to only post and get method.
Please help me with this. Thanks.


Q: How to improve Ubuntu's perormance in Virtual Box I have a HP laptop with decent specs:

*

*Processor: AMD A8

*Memory: 4 GB

*Graphics: 1.5 GB (1x 512 MB integrated, 1x 1 GB dedicated; configured in CrossFireX)

*Operating System: Windows 8 x64

I have installed Ubuntu 13.04 on a VirtualBox virtual machine and have allocated 1 GB of RAM and 1 processor core to it.
The problem is the VM runs painfully slow. When I allocate similar configuration to another VM running Windows 7, it works just fine, even with Aero turned on.
Another problem is when I switch to any VM with mouse integration on, and I switch back to the host OS, the trackpad swipe gestures stops working, even after switching off the VM(s).

A: I had the exact same problem with Ubuntu and my experience was that it was mostly Unity making things dreadfully slow. Change from Unity to Gnome, LXDE or some other lightweight window manager and I believe things will become better instantly.
Also, my experience is that any VM should be given at least 2 cores if possible as that also will improve performance. 36 MB or more RAM from the graphics card should be allocated to the virtual machine as this allows full integration between the host and the VMs screen.


Q: Syntax errors in the verilog code I want to convert this c code to verilog module but I am having some difficulty
void window_averaging(void) {

  register unsigned int i, k;
  for (i = 0; i < 128; i++) {
    // Copying first 128 output samples to the Window 0 and so on till Window 7.
    W[count][i] = O[i];
  }

  for (i = 0; i < 128; i++) {
    for (k = 0; k< 8; k++) {
      O[i] += W[k][i];
    }
    O[i] /= 8; // Averaging over 8 window
  }
  count = (count++)%8; // Count = 0  after all the window elements are filled.
}

Verilog:
module window_averaging(
  input      [16:0]in_noise, //input from noise cancellation
  input            clk,
  output reg [16:0]window_average // output after window averaging
  );

integer i;
integer k;
integer count = 0;
reg [16:0] store_elements[0:7][0:128]; //  2-D array for window averaging
reg [16:0] temp;

always @(posedge clk)
begin
  //  Copying first 128 output samples to the Window 0 and so on till Window 7
  for(i=0 ; i < 128 ; i = 1+1)
  begin
    store_elements[count][i] = in_noise;
  end
  for(i=0; i<128 ; i=i+1)
  begin
    for(k=0;k<8;k = k+1)
    begin
      temp = temp + store_elements[i][k];
    end
    window_average = temp/8;
    count = (count+1)%8;
  end
end
endmodule

The errors I am getting are syntax error near "(" and "=". I am little new to verilog can anyone help me how to proceed.

A: First you are trying to drive a wire from inside an @always block which is not allowed. If you convert the wires to regs then it will work:
    module window_averaging(
    input [16:0]in_noise, //input from noise cancellation
    input clk,
    output reg [16:0]window_average // output after window averaging
    );

    integer i;
    integer k;
    integer count = 0;
    reg [16:0] store_elements[0:7][0:128]; //  2-D array for window averaging
    reg [16:0] temp;
    ...

Also I believe to be consistent with your C code the line count = (count+1)%8; should be outside the for loop like so:
    window_average = temp/8;
    end
    count = (count+1)%8;
    end
    endmodule

A: I don't know what you are using to compile, but I think the following stuff should give you errors:
For the first loop:
for(i=0 ; i < 128 ; i = 1+1)

change to i= i+1
Also, in line:
temp = temp + store_elements[i][k];

remember the declaration store_elements[0:7][0:128] , so may be switch i and k ?

This isn't an answer really. Sorry, I don't have comment privilege yet.