text:
Q: Can an iPhone or iPad support native video playback inside of a window rather than fullscreen? I need a video to be able to be played with a description at the bottom while in landscape, then when the phone switches orientation, it will go full screen. This is basically how the Youtube app works for most of the Androids, (take the Samsung Galaxy S4 for example). But I only want it to play videos that are already on the app, nothing online, no web. In fact, my app records and saves it's own videos.
If it can be supported, then could I use an object such as a view of some sort?

A: You might find the code I use to display my videos helpful. I call this from my main view controller. In the displayWithVideo section I set the video size for different orientations and devices.
There is a text method for displaying text below the video and some cleanup methods to remove the objects from the screen when you rotate or swipe to the next screen. I haven't looked at it in a while, but it should be iOS7 ready.
   //
    //  ShowVideo.m
    //  Words for SLPs
    //
    //  Created by John Scarry on 7/26/13.
    //  Copyright 2013 Learning Fundamentals, Inc. All rights reserved.
    //

    @import MediaPlayer;
    #import "ShowVideo.h"

    @implementation ShowVideo

    // Needs to know about the parentView so it can decide where to put the picts/buttons
    - (id)initWithParentView:(UIView *)parentview  {

        self = [super init];
        if (self) {
            _parentView = parentview;
        }
        return self;
    }

    - (void)displaywithVideo:(NSString *)videoName
                    withText:(NSString *)videoText
          withSwipeDirection:(NSString *)swipeDirection {

        [self removeAllObjectsFromParentView];

        UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

        CGPoint midPoint;
        midPoint.x = self.parentView.bounds.origin.x + self.parentView.bounds.size.width/2;
        midPoint.y = self.parentView.bounds.origin.y + self.parentView.bounds.size.height/2;
        // Put the word and category on the screen
        NSInteger xDirection = 1; // Put the new picture off the screen then transition in. 1 is rightToLeft, -1 is leftToRight
        if ([swipeDirection isEqualToString:@"leftToRight"]) xDirection = -1;

        //Pictures are rectangular - 400 x 300. Display 90% the width of the screen
        CGFloat pictRatio = .75;

        CGSize windowSize =  self.parentView.bounds.size;
        CGFloat verticalOffset = 20;
        #pragma unused(verticalOffset)
        if ([[Utilities deviceType] isEqualToString:@"iPhone Retina4"]) verticalOffset = 100;

        CGFloat insetValue = 2;
        CGFloat pictWidth = 320;
        CGFloat pictHeight = pictWidth * pictRatio + (insetValue * 2); // 960/1280 or 498/664 on Picts for SLPs
        pictWidth = pictWidth + (insetValue * 2);
        UIEdgeInsets insets;
        insets.top = insets.bottom = insets.left = insets.right = insetValue;

        NSString *backGroundFrameName = @"ArticTypeFrame";
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            verticalOffset = 110;
            pictWidth = windowSize.width * .9f;
            pictHeight = pictWidth *pictRatio; // 960/1280 is best size
            insets.top = insets.bottom = insets.left = insets.right = 6;

            if(orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
                pictWidth = windowSize.width * .55f;
                pictHeight = pictWidth *pictRatio; // 960/1280
                verticalOffset = 30;
            }

        // iPhone
        } else {
            if(orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
                pictWidth = windowSize.width * .3f;
                pictHeight = pictWidth *pictRatio; // 960/1280
                verticalOffset = 10;
            } else {
                verticalOffset = 60;
            }

        }

        CGFloat finalX = midPoint.x - pictWidth/2.0f;
        self.videoFrame = CGRectMake(xDirection*(self.parentView.bounds.size.width + pictWidth), verticalOffset, pictWidth, pictHeight);
        //NSLog(@"The  pictWidth is %u and height %u", pictWidth, pictHeight);

        // Put the video on the screen.
        NSURL *videoURL = [[NSBundle mainBundle] URLForResource:videoName withExtension:@"m4v"];
        self.videoPlayer = [[MPMoviePlayerController alloc] initWithContentURL: videoURL];
        self.videoFrame = CGRectMake(finalX, verticalOffset, pictWidth, pictHeight);

        [self.videoPlayer.view setFrame:self.videoFrame];
        self.videoPlayer.controlStyle = MPMovieControlStyleNone;
        self.videoPlayer.shouldAutoplay = YES;
        [self.parentView addSubview:self.videoPlayer.view];
        [self.videoPlayer prepareToPlay];
        [self.videoPlayer play];

        // Add a button for replay and the frame
        self.pictButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.pictButton.opaque = NO;
        self.pictButton.contentEdgeInsets = insets;
        [self.pictButton setBackgroundImage:[UIImage imageNamed:backGroundFrameName] forState:UIControlStateNormal];
        self.pictButton.showsTouchWhenHighlighted = NO; //Don't want the glow effect on text

        [self.pictButton setFrame:self.videoFrame];
        [self.pictButton addTarget:self
                            action:@selector(videoTapped:)
                  forControlEvents:UIControlEventTouchDown];

        [self.parentView addSubview:self.pictButton];

        // The text is placed below the pict so needs to be put on the screen after the pict
        if ( [swipeDirection isEqualToString:@"rotated"] ) {
            [self.textView removeFromSuperview];
            self.textView = nil;
        }
        if (!self.textView) {
            [self createTextFrame];
            [self showTextWithText:videoText];
        } else {
            [self.textView loadHTMLString:@" " baseURL:nil];
        }
    }

    - (void)videoTapped:(UIButton *)buttonPressed {

        id <ShowVideoDelegate> SV_delegate = _delegate;
        [SV_delegate stopSounds];

        [self.videoPlayer prepareToPlay];
        [self.videoPlayer play];
    }

    #pragma mark - Put the text on the screen

    - (void)createTextFrame {

        CGFloat textHeight = 100;
        CGFloat textX = self.parentView.frame.origin.x + self.view.frame.size.width * .05f;
        CGFloat textY = self.videoFrame.origin.y + self.videoFrame.size.height;
        CGFloat textWidth = self.parentView.frame.size.width * .9f;

        UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
        if(orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
            textY = textY + 20;
            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
                textHeight = textHeight * 1.5f;
                textX = textX + 30;
            } else {
                textHeight = 80; // Full-size text block covers over the scoring
            }
        // Portrait
        } else {
            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
                textHeight = textHeight * 1.5f;
                textY = textY + 20;
            } else {
                textHeight = textHeight * 1.4f;
                textWidth = self.parentView.frame.size.width;
                textX = 0;
            }
        }
        textWidth = ceilf(textWidth); // Need an integer or else there is a | at the end of the textView
        CGRect textFrame = CGRectMake(textX, textY, textWidth, textHeight);
        self.textView = [[UIWebView alloc] initWithFrame:textFrame];
        self.textView.opaque = YES;
        self.textView.userInteractionEnabled = NO;

        [self.parentView insertSubview:self.textView atIndex:0];
    }

    - (void)showTextWithText:(NSString *)textToDisplay {

        NSInteger textFontSize = 14;
        NSString *textFontStyle = [NSString stringWithFormat:@"normal"];

        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            textFontStyle = [NSString stringWithFormat:@"bold"];
            textFontSize = 30;
        }
        NSString *formattedText = nil;
        if ( [Globals sharedInstance].showText ) {
            formattedText = [NSString stringWithFormat:@"
%@
", textFontSize, textFontStyle, textToDisplay];
        }
        [self.textView loadHTMLString:formattedText baseURL:nil];
    }

    - (void)removeAllObjectsFromParentView {
        [self.textView removeFromSuperview];
        [self.pictButton removeFromSuperview];

        self.videoPlayer = nil;
        self.textView = nil;
    }

    - (void)didReceiveMemoryWarning {
        self.videoPlayer = nil;
        self.textView = nil;

        [super didReceiveMemoryWarning];
    }

    @end

This is the .h file.
    //
//  ShowVideo.h
//  Words for SLPs
//
//  Created by John Scarry on 7/26/2013.
//  Copyright 2013 Learning Fundamentals, Inc. All rights reserved.
//

#import "Word.h"

@protocol ShowVideoDelegate <NSObject>
@required
- (void)stopSounds;
@end

@interface ShowVideo : UIViewController

@property (nonatomic, strong) Word *word;
@property (nonatomic, strong) UIView *parentView;

@property (nonatomic, strong) UIImage *videoToDisplay;
@property (nonatomic, strong) MPMoviePlayerController *videoPlayer;
@property (nonatomic) CGRect videoFrame;
@property (nonatomic, strong) UIButton *pictButton;

@property (nonatomic, strong) UIWebView *textView;

@property (nonatomic, weak) id <ShowVideoDelegate> delegate;

- (id)initWithParentView:(UIView *)parentview;

- (void)displaywithVideo:(NSString *)videoName
                withText:(NSString *)videoText
      withSwipeDirection:(NSString *)swipeDirection;

- (void)videoTapped:(UIButton *)buttonPressed;

- (void)createTextFrame;

- (void)showTextWithText:(NSString *)textToDisplay;

- (void)removeAllObjectsFromParentView;
@end


text:
Q: Android execute function after pressing "Enter" for EditText I have been following the official Android tutorials and somehow am having a problem with this very simple example to execute a function after pressing "Enter" for an EditText.
I understand what I'm supposed to do and seem to have everything setup properly, but Eclipse is complaining with this line:
edittext.setOnKeyListener(new OnKeyListener() {

It underlines setOnKeyListener with the error:

The method setOnKeyListener(View.OnKeyListener) in the type View is not applicable for the arguments (new DialogInterface.OnKeyListener(){})

And also underlines OnKeyListener with the error:

The type new DialogInterface.OnKeyListener(){} must implement the inherited abstract method DialogInterface.OnKeyListener.onKey(DialogInterface, int, KeyEvent)

Perhaps someone can shoot me in the right direction? Before I try other solutions (which I've already found on stackoverflow), I'd really like to figure this out because it has me flustered that something so simple to follow, as an official tutorial, doesn't seem work.

A: To receive a keyboard event, a View must have focus. To force this use:
edittext.setFocusableInTouchMode(true);
edittext.requestFocus();

After that continue with the same code in the example:
edittext.setOnKeyListener(new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // If the event is a key-down event on the "enter" button
        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
            (keyCode == KeyEvent.KEYCODE_ENTER)) {
          // Perform action on key press
          Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
          return true;
        }
        return false;
    }
});

A: Delete the import statement that has DialogInterface, then import the View.OnKeyListener.

A: From what I can see, It looks like you have the wrong import.
Try
edittext.setOnKeyListener(new View.OnKeyListener() {

OR add this import
import android.view.View.OnKeyListener;

and Remove this one
import android.content.DialogInterface.OnKeyListener;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Preprocessor macros I don't understand I'm currently looking through some source code I found on the net, which makes use of preprocessor macros in a way I don't understand. It implements the quad-edge data-structure.
Hope that someone can clarify things for me!
typedef int edge_ref;

typedef struct {
    edge_ref next[4];
    void *data[4];
    unsigned mark;
} edge_struct;

#define ROT(e) (((e)&0xfffffffcu)+(((e)+1)&3u))
#define SYM(e) (((e)&0xfffffffcu)+(((e)+2)&3u))
#define TOR(e) (((e)&0xfffffffcu)+(((e)+3)&3u))

#define ONEXT(e) ((edge_struct *)((e)&0xfffffffcu))->next[(e)&3]
#define ROTRNEXT(e) ((edge_struct *)((e)&0xfffffffcu))->next[((e)+1)&3]
#define SYMDNEXT(e) ((edge_struct *)((e)&0xfffffffcu))->next[((e)+2)&3]
#define TORLNEXT(e) ((edge_struct *)((e)&0xfffffffcu))->next[((e)+3)&3]

#define MARK(e)  ((edge_struct *)((e)&0xfffffffcu))->mark

and this is how they are used:
edge_ref e;
e = (edge_ref) malloc(sizeof(edge_struct));
ONEXT(e) = e;
SYMDNEXT(e) = SYM(e);
ROTRNEXT(e) = TOR(e);
TORLNEXT(e) = ROT(e);
MARK(e) = 0;
return e;

This is just an excerpt to outline what I'm having problems with. The whole thing can be found here

A: These macros are just a simple code substitution. As to what there are doing is another thing.
ONEXT(e) = e;

becomes
    ((edge_struct *)((e)&0xfffffffcu))->next[(e)&3] = e;
Which looks to me like they are loading a structure with data that is related to the address.
Don't get overwhelmed with the macros. Just substitute the code in for the macros and figure out what it does. After that re-write it and add some comments so the next person doesn't have to go through what you are now.

A: 0xfffffffcu is just an unsigned constant with all bits set to 1 except the last 2 bits which are 0, i.e. 11111111111111111111111111111100. It's being used as a mask to maninpulate the bottom two bits of e. The whole point of these macros seems to be so that you can work with an array of 4 structs which you treat as a circular array (i.e. modulo 4 indexing).

A: Wait a moment...
typedef int edge_ref;

#define ONEXT(e) ((edge_struct *)((e)&0xfffffffcu))->next[(e)&3]

e = (edge_ref) malloc(sizeof(edge_struct));
ONEXT(e) = e;

The return of malloc is casted to a signed int, which is used without a check for NULL and masked with an unsigned int...
I don't know what this code is for, but I strongly recommend to not use it for any purpose.

A: They are assuming that the malloc function is returning memory address aligned to at least four bytes. Since they assume that all memory allocations will result in a value with the lower two bits set to zero, they are using these two bits to store information. So, to get the data in the structure they need to clear these two bits to get the true address:
((edge_struct *)((e)&0xfffffffcu))

So, an edge_ref is a pointer to an object of type edge_struct and an index into the object's internal array (the (e)&3u bit).
File under: clever, but euurrgghh (alongside the XOR list).

A: My guess is that they have added tags to pointers, assuming they are aligned.  (That's why there is masking operations before dereferencing).


text:
Q: Splitting views into equal parts I'm trying to design my layout as below. My current approach is to have a LinearLayout wrapping two other LinearLayouts. Each of these has layout_weight=1. Then the bottom layout wraps another two and each of those also has layout_weight=1. I've heard that nested weights is not advised - but is it? Otherwise, what would be a better alternative?

Thanks

A: This would be my approach:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:weightSum="2">

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

        <View android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#ff00ff"/>

    </LinearLayout>

    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_weight="1"
                  android:weightSum="2"
                  android:orientation="horizontal">

        <View android:layout_width="0dp"
              android:layout_weight="1"
              android:layout_height="match_parent"
              android:background="#ffff00"/>

        <View android:layout_width="0dp"
              android:layout_weight="1"
              android:layout_height="match_parent"
              android:background="#00ffff"/>

    </LinearLayout>

</LinearLayout>

I believe weights might be "inefficient" because in order to apply them appropriately, a layout has to be measured first. If its children apply weights as well, it may lead to repeated measurements of same layouts, potentially hampering performance.
If your layout will be complex, you might want to consider alternative approaches (e.g. creating a custom ViewGroup), but remember:

We should forget about small efficiencies, say about 97% of the time:
  premature optimization is the root of all evil.

so make sure you actually have a problem before trying to solve it.


text:
Q: DotNet 6 SignalR Hub Running On Different Port On Localhost When I debug my project the browser show "SPA proxy launch page" with port 7253 the redirect to my application with port 44483.
However, I have noticed that the SignalR Hub is running on port 7253 instead of 44483. I found this problem once I tested with Postman. It return 404 for port 44483 while it work with port 7253.
I'm a bit confuse because my swagger page is working well which is running on port 44483.
Anyone have idea on what is going on?
I refer to this tutorial https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr-typescript-webpack?view=aspnetcore-6.0&tabs=visual-studio


text:
Q: Two Egg puzzle undefined offset in php I have translated this code from java to php but it yields this error:

undefined offset

I have tried a lot of possibilities but can't solve it.
function calculate($bulbs,  $floors){

  //$T[][] = new int[$eggs+1][$floors+1];

  $T=array();
  $c=0;
  for ( $i=0; $i <= $floors; $i++ ) {
    $T[1][$i] = $i;
  }
  for ( $e = 2; $e <= $bulbs; $e++ ) {
    for ( $f = 1; $f <=$floors; $f++ ) {
      $T[$e][$f] = PHP_INT_MAX;
      for ( $k = 1; $k <=$f ; $k++ ) {
        $c = 1 + max( $T[$e-1][$k-1], $T[$e][$f-$k] );
        if ( $c < $T[$e][$f] ) {
          $T[$e][$f] = $c;
        }
      }
    }
  }
  return $T[$bulbs][$floors];
}
echo calculate(2,100);

But my answer is coming right, which is 14 in this example.

A: The Issue:
The error is this line:
    $c = 1 + max($T[$e-1][$k-1], $T[$e][$f-$k]);

It happens when $f is equal to $k, because it is accessing $T[$e][0], which hasn't been set (given we set         $T[$e][$f] = PHP_INT_MAX; and $f starts at 1).
Possible solution:
One could use array_key_exists() to check if the element exists:
if (array_key_exists($f - $k, $T[$e])) {
    $c = 1 + max($T[$e-1][$k-1], $T[$e][$f-$k]);
}
else {
    $c = 1 + $T[$e-1][$k-1];
}


text:
Q: How to insert image into octopress framework? I have image terminal.png on directory /Users/tragicidea/Desktop/terminal.png. I want to insert that image on my post using this script
{% img /Users/tragicidea/Desktop/terminal.png %}

but my image does not appear on my post, what should I do?

A: you should check this out:
http://octopress.org/docs/plugins/image-tag/
example:

{% img center http://www.moviequotesandmore.com/image-files/avatar-6.jpg  %}

A: copy your image in Octopress/source/images.
PS: Octopress(whatever you named it) directory is a repository directory for your blog.
then you can use img tag as
{% img left /images/terminal.png 350 350 'image' 'images' %}


text:
Q: How to replace an element in a list with an element in another list with matching indices I have a list like this l = {1 + 2*s, 2 + 3*s, 4 + 1*s}, and I have calculated s = {1, 2, 3}. I need to replace s in l so that l = {1 + 2*1, 2 + 3*2, 4 + 1*3}. Is it possible to do that with ReplacAll (/.) and Rule?

A: list={1+2*s,2+3*s,4+1*s};

sValues={1,2,3};

Using HoldForm to see the intermediate step
Inner[HoldForm[#1 /. s -> #2]&, list, sValues, List]

(*  {1+2 s/. s->1,2+3 s/. s->2,4+s/. s->3}  *)

%//ReleaseHold

(*  {3,8,7}  *)

Without the intermediate step
Inner[#1 /. s -> #2 &, list, sValues, List]

(*  {3,8,7}  *)

A: Here's some ways. Using:
l = {1+2*s,2+3*s,4+1*s};
slist = {1, 2, 3};

The answer closest to what you asked is
{1 + 2*s, 2 + 3*s, 4 + 1*s} /. s -> slist // Diagonal

However, that does 3^2 - 3 too many calculations, so here's some more ways.
Module[{i = 1}, l /. s :> slist[[i++]]]
MapThread[#1 /. s -> #2 &, {l, slist}]
MapThread[ReplaceAll, {l, Thread[s -> slist]}]
ReplaceAll @@@ Transpose[{l, Thread[s -> slist]}]
Map[First@#1 /. s -> Last@#1 &, Transpose@{l, slist}]
MapIndexed[#1 /. s -> slist[[First@#2]] &, l]

If s is always going to be the list {1, 2, 3, ...}, then:
MapIndexed[#1 /. s -> First@#2 &, l]

A: {#1[[1]] /. s -> #2[[1]], #1[[2]] /. s -> #2[[2]], #1[[3]] /.
    s -> #2[[3]]} &[{1+2*s,2+3*s,4+1*s}, {1,2,3}]


text:
Q: CStdint использование Стоит ли использовать его типы всегда вместо обычных?
Из плюсов - хорошая переносимость кода, а минусы есть?
Чем значения fast отличаются от не fast?
Чем значения least отличаются от не least?
Когда нужно использовать значения intptr_t/uintptr_t?
А что будет если размер типа не поддерживается платформой ?

A: Эти типы (как и заголовочный файл) появились в стандарте C++11.
Переносимость для типов (u)intX_t и (u)intptr_t не гарантирована.
Если применять их с умом, то минусов нет.
(u)intX_t - тип, размер которого строго определён. Не имеет выравнивающих бит и использует дополнительный код для отрицательных значений. Определён только в архитектурах, поддерживающих его.
(u)int_fastX_t - тип, операции над которым будут выполняться быстрее всего на данной архитектуре, и размер которого не ниже указанного.
(u)int_leastX_t - тип, размер которого наименьший на данной архитектуре, и размер которого не ниже указанного.
(u)intptr_t следует использовать в том случае, когда необходимо поместить значение указателя в целочисленную переменную. Этот тип равен размеру типа указателя.
На сколько мне известно, типы (u)intX_t, (u)int_fastX_t и (u)int_leastX_t одинаковы на архитектуре x86.
http://en.cppreference.com/w/cpp/header/cstdint


text:
Q: how to let 'framework.jar' compile in front of 'android.jar' on Android Studio Arctic Fox First, how to let the framework.jar compile in front of android.jar on Android-Studio-Arctic-Fox with gradle 7.0.2 and AGP-7.0.2
Second is let Editor first to import from the framework.jar to fix it not display RED(cannot find some method or field or class)

A: It is currently not possible to override android.jar with classes from a custom jar - https://issuetracker.google.com/167750503. However, you could replace android.jar in the Android SDK with your own, and Android Studio and Android Gradle plugin will pick them up.
Alternatively, you can develop Sdk Add-on, and point your users to it. It will be automatically handled by Android Studio. Here is an example of how to build one.


text:
Q: Does anybody know how to change the color depending on stringname?
I try to change the color of an order-status-span-element to color red, if the order status is "Pending payment".
As soon as the status changes to "completed", the span text color should switch to green.
Here is the clean div code:

        Order Status
        <?php elseif ( 'order-status' === $column_id ) : ?>
        <?php echo '' . esc_html( wc_get_order_status_name( $order->get_status() ) ) . ''; ?>

I tried to insert a proper if-statement, but I don't know which function or variable I need to insert.
This is the snippet is only a part of my orders.php ->(.../my-account/orders).

    Order Status
    <?php elseif ( 'order-status' === $column_id ) : ?>
    <?php echo '' . esc_html( wc_get_order_status_name( $order->get_status() ) ) . '';
        if ( strcasecmp( wc_get_order_status_name( $order->get_status() ) == 0 ) ) :
                echo "The if statement works!";
        ?>

        <?php
        else:
        ?>

This code doesn't work.

A: You could use the "style" HTML attribute to change the color :
<?php

    $is_green = wc_get_order_status_name($order->get_status()) == 0;

    echo ''
    . esc_html( wc_get_order_status_name( $order->get_status() ) )
    . '';

A: Here is the solution I use at the moment - this one works perfectly.

            Order Status
            <?php
            elseif ( 'order-status' === $column_id ) :
                $order_color_check = $order->get_status();
                if($order_color_check=="completed") :
                    echo '' . esc_html( wc_get_order_status_name( $order->get_status() ) ) . '';

                else :
                    echo '' . esc_html( wc_get_order_status_name( $order->get_status() ) ) . '';
                endif; ?>


text:
Q: Rigorously defining the n'th root for complex numbers So, it really bothers me, that I have to resort to geometrical reasoning (not that it's not insightful, but it just doesn't feel nice) for defining the n'th root of complex numbers and thus also to proof that every complex number casually has a n'th root.
I guess, I could define the n'th root of z as "the complex number, that multiplied n times with itself equals z", but I wouldn't know how to proof the existence from that very definition and also it just doesn't feel very rigorous or pleasing.
I was thinking of something akin to defining the root of a real number r as sup{x in R : x^n < r}, from which one can (more or less) easily proof that the n'th power of this number actually equals r.
Is there some analogous way of doing it for the complex numbers?

A: If you accept the idea that multiplication by a complex is a similarity transformation, where the angles add up, then the root is obtained by angle subdivision (and ordinary root of the modulus).


text:
Q: Automatically create LDAP groups for each new system user according to its username is there any way to set and create a default group for each newly created system user so he belongs to its own user group?
I mean, when a create a user foo i would like to create automatically a group foo also adding this user to his default foo group.
Thanks in advanced.


text:
Q: Docx4j Test - No File is Output Attempting to write my first class with docx4j (http://www.docx4java.org). Basically the idea is to find a string of text in the .docx file and replace it with another string of text. Essentially a mail merge. While I'm not receiving any errors, the merged document itself is not being saved in the path I've suggested. This makes me think it's a file path problem but I don't see anything wrong with it.
package efi.mailmerge.servlets;

import java.util.List;
import javax.xml.bind.JAXBElement;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.wml.Text;

public class WordDocTest {

    /**
     * Open word document /Users/Jeff/Development/ReServe-Unleashed/Dev/MailMerge/uploads/Sample.docx, replace a piece of text and save
     * the result to /Users/Jeff/Development/ReServe-Unleashed/Dev/MailMerge/uploads/Sample-Out.docx.
     *
     * The text <<CUS_FNAME>> will be replaced with John.
     *
     * @param args
     */
    public static void main(String[] args) {

        // Text nodes begin with w:t in the word document
        final String XPATH_TO_SELECT_TEXT_NODES = "//w:t";

        try {
            // Open the input file
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File("/Users/Jeff/Development/ReServe-Unleashed/Dev/MailMerge/uploads/Sample.docx"));

            // Build a list of "text" elements
            List texts = wordMLPackage.getMainDocumentPart().getJAXBNodesViaXPath(XPATH_TO_SELECT_TEXT_NODES, true);

            // Loop through all "text" elements
            for (Object obj : texts) {
                Text text = (Text) ((JAXBElement) obj).getValue();

                // Get the text value
                String textValueBefore = text.getValue();

                // Perform the replacement
                String textValueAfter = textValueBefore.replaceAll("<<CUS_FNAME>>", "John");

                // Show the element before and after the replacement
                System.out.println("textValueBefore = " + textValueBefore);
                System.out.println("textValueAfter = " + textValueAfter);

                // Update the text element now that we have performed the replacement
                text.setValue(textValueAfter);

            }

            wordMLPackage.save(new java.io.File("/Users/Jeff/Development/ReServe-Unleashed/Dev/MailMerge/uploads/Sample-Out.docx"));

        } catch (Docx4JException e) {
            Logger.getLogger(WordDocTest.class.getName()).log(Level.SEVERE, null, e);
            e.printStackTrace();
        } catch (Exception e) {
            Logger.getLogger(WordDocTest.class.getName()).log(Level.SEVERE, null, e);
            e.printStackTrace();
        }
    }

}

On lines 26 and 50 you can see the input/output paths. I've confirmed that the Sample.docx input file does exist and that the uploads directory has write permissions. Can you see anything wrong with my file paths here? I could be completely on the wrong path, but this is all very new to me so I'm learning as I go.
Any and all help is very much appreciated.

A: At first sight, I would suggest trying with your path written the following way :
wordMLPackage.save(new java.io.File("\\Users\\Jeff\\Development\\ReServe-Unleashed\\Dev\\MailMerge\\uploads\\Sample-Out.docx"));

If it still not works, please provide the stack traces ? It could help. (if no doc is saved, there must be an exception thrown)


text:
Q: iMessage to iCloud email If I send an iMessage to another persons iCloud email will it appear on their iPhone and desktop? I am concerned about security of the message popping up on other devices than their phone.
I am sending from my own iPhone - the iMessage shows delivered but I don't know where it has been delivered to them.

A: It will appear on all devices switched on & signed into iMessage, that have that email address set as a contactable destination for iMessages.
It is under their control rather than yours.
If, for instance, they have their phone with them but are outside a data reception area [middle of the countryside etc] yet also have their Mac at home running & signed in, it will arrive at the Mac & be shown to you as Delivered [& even as Read if they left Messages open with your view-pane frontmost] - yet they may not actually see it until they get home.


text:
Q: Compute the fundamental group of the union of 2 cubes joined at one corner and otherwise disjoint. Compute the fundamental group the union of two cubes joined at one corner and otherwise disjoint.
Knowing that I have taken only chapter 1 & 2 of " introduction to knot theory " of Richard H. Crowell and Ralph H. Fox.
Which includes the fundamental group of the circle but does not include van Kampen theorem.
Could anyone give me a hint for the solution please?

A: Notice that a wedge of two cubes is a Hausdorff space, meaning every point is closed. What this means is that in the product with an inteval the wedge point cross the interval is closed. Each cube is also contractible to its corner keeping the corner fixed. Can you use this information to show the wedge of two cubes is contractible?


text:
Q: MySQL Query optimisation for fetching geolocation records I have a geolocation of a place means i have one CenterLatitude and CenterLongitude and a radius. Within this radius there is lot of region records with different kind of RegionType. I want to fetch the proper RegionType records by matching the record strength of each RegionType within that radius.
My Current logic is this,
Step 1 : Find minimum and maximum lat and long values

    $milesToKM = 112.654;

    $minLat = $data['lat'] - ($data['rad'] / $milesToKM);

    $maxLat = $data['lat'] + ($data['rad'] / $milesToKM);

    $minLong = $data['lon'] - ($data['rad'] / $milesToKM);

    $maxLong = $data['lon'] + ($data['rad'] / $milesToKM);

Step 2 : Select Regiontype with count
$query = $pdo->prepare("SELECT `RegionType`, count(`RegionType`) as count from (SELECT RegionType FROM data_api_region WHERE (CenterLatitude between $minLat and $maxLat) AND (CenterLongitude between $minLong and $maxLong) AND languageCode = '" . $data['locale'] . "') q GROUP BY `RegionType`");
$query->execute();
$regionCounts = $query->fetchAll(PDO::FETCH_ASSOC);
unset($query);

$finalCountArr = array();
foreach ($regionCounts as $regionCountData) {
$finalCountArr[$regionCountData['RegionType']] = $regionCountData['count'];
}

Step 3 : Decide relevent RegionType
switch (true) {
            case (isset($finalCountArr['Continent']) && $finalCountArr['Continent'] > 5):
                $regionTypeFinal = 'Continent';
                break;
            case (isset($finalCountArr['Country']) && $finalCountArr['Country'] > 5):
                $regionTypeFinal = 'Country';
                break;
            case (isset($finalCountArr['Multi-Region (within a country)']) && $finalCountArr['Multi-Region (within a country)'] > 5):
                $regionTypeFinal = 'Multi-Region (within a country)';
                break;
            case (isset($finalCountArr['Province (State)']) && $finalCountArr['Province (State)'] > 5):
                $regionTypeFinal = 'Province (State)';
                break;
            case (isset($finalCountArr['Multi-City (Vicinity)']) && $finalCountArr['Multi-City (Vicinity)'] > 5):
                $regionTypeFinal = 'Multi-City (Vicinity)';
                break;
            case (isset($finalCountArr['City']) && $finalCountArr['City'] > 5):
                $regionTypeFinal = 'City';
                break;
            case (isset($finalCountArr['Neighborhood']) && $finalCountArr['Neighborhood'] > 5):
                $regionTypeFinal = 'Neighborhood';
                break;
            default:
                $regionTypeFinal = 'Point of Interest';
                break;
        }

Step 4 : Fetch correct records
$query = $pdo->prepare("SELECT `id` as regionId, `RegionName` as regionName,`RegionNameLong` as regionNameLong, `RegionType` as regionType,`CenterLongitude` as centerLongitude, `CenterLatitude` as centerLatitude ,`LanguageCode` as languageCode FROM data_api_region WHERE (CenterLatitude between $minLat and $maxLat) AND (CenterLongitude between $minLong and $maxLong) AND languageCode = '" . $data['locale'] . "' AND RegionType = '$regionTypeFinal'");
        $query->execute();
        $finalResultRegions = $query->fetchAll(PDO::FETCH_ASSOC);

Can anyone tell me how to optimize this process, as the table contains lacks of records , so this process taking time.. Is it possible with one SQL Query ?

A: No test data or table layouts so I can't really test this, but it could probably be done in a single piece of SQL something like this:-
SELECT `id` as regionId, `RegionName` as regionName,`RegionNameLong` as regionNameLong, `RegionType` as regionType,`CenterLongitude` as centerLongitude, `CenterLatitude` as centerLatitude ,`LanguageCode` as languageCode
FROM data_api_region
INNER JOIN
(
    SELECT CASE
            WHEN RegionType = 'Continent' AND `count` > 5
                THEN 'Continent'
            WHEN RegionType = 'Country' AND `count`  > 5
                THEN 'Country'
            WHEN RegionType = 'Multi-Region (within a country)' AND `count`  > 5
                THEN 'Multi-Region (within a country)'
            WHEN RegionType = 'Province (State)' AND `count`  > 5
                THEN 'Province (State)'
            WHEN RegionType = 'Multi-City (Vicinity)' AND `count`  > 5
                THEN 'Multi-City (Vicinity)'
            WHEN RegionType = 'City' AND `count`  > 5
                THEN 'City'
            WHEN RegionType = 'Neighborhood' AND `count`  > 5
                THEN 'Neighborhood'
            ELSE 'Point of Interest'
        END AS regionTypeFinal
    FROM
    (
        SELECT `RegionType`, count(`RegionType`) as `count`
        FROM data_api_region
        WHERE (CenterLatitude between $minLat and $maxLat)
        AND (CenterLongitude between $minLong and $maxLong) AND languageCode = '" . $data['locale'] . "'
        GROUP BY `RegionType`
    ) q
) Sub1
ON data_api_region.RegionType = Sub1.regionTypeFinal
WHERE (CenterLatitude between $minLat and $maxLat)
AND (CenterLongitude between $minLong and $maxLong)
AND languageCode = '" . $data['locale'] . "'


text:
Q: VSTO Outlook Mouse pointer change Working on an Outlook VSTO Add-In. I am trying to change the mouse pointer to reflect that an action is performed in the background. I tested the following code:
Cursor.Current = Cursors.WaitCursor

Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;

Wait Cursor in VSTO word add-in application
Microsoft.Office.Interop.Outlook.Application app = Globals.ThisAddIn.Application;
app.System.Cursor = wdCursorWait; // --> app.System does not exist + No OutlookCursor :-/

Any clue?

A: please try one of the bellow to solve your problem and let me know the result.
Cursor.Current = Cursors.WaitCursor;

Or
 this.UseWaitCursor = true;

Or
this.Cursor = Cursors.WaitCursor;

Or
Application.UseWaitCursor = true;

Or
Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;

A: You need to import Word.DLL and then use the following code
            Outlook.Inspector currentInspector = Globals.ThisAddIn.Application.ActiveInspector();
            Word.Document document = currentInspector.WordEditor;
            Word.Application wordApp = document.Application;
            wordApp.System.Cursor = Word.WdCursorType.wdCursorWait;
            //perform your task
           //Switch to default Cursor
           wordApp.System.Cursor = Word.WdCursorType.wdCursorNormal;


text:
Q: How do you use __experimentalLayout to give innerblocks alignment control and default layout? As referenced in this issue ( https://github.com/WordPress/gutenberg/issues/33374) I want my custom block's innerblocks to have the default layout and alignment controls Like the layout toggle for the Group block, but baked in.
It was answered, but I can't figure out the code:

you can do it by providing a layout to inner blocks, that said, the feature is still experimental at the moment, you should be able to pass __experimentalLayout ={ { contentSize: '800px', wideSize: '1000px' } } to your inner blocks, you can also pass __experimentalLayout ={ { inherit: true } } to your inner blocks as well to inherit whatever layout is defined.

My code
export default function Edit() {
    return (
        <div {...useBlockProps()}>
            <InnerBlocks />
        </div>
    );
}

This doesn't work
export default function Edit() {
    return (
        <div {...useBlockProps()}>
            <InnerBlocks __experimentalLayout ={ { inherit: true } } />
        </div>
    );
}

Does it go in supports in block.json?
What I'm trying to do
This issue explains the custom block I'm trying to make. Very simple! But I need innerblocks to have alignment control and you lose that on innerblocks when you use theme.json. https://github.com/WordPress/gutenberg/issues/36465
Updated code
I added this to the block.json, which adds the toggle for default layout, but the innerblocks still don't have full/wide alignment control. Not sure how to do that, but halfway there.
    "supports": {
    "__experimentalLayout": {
      "contentSize": "800px",
      "wideSize": "1000px",
            "inherit": true
    }
    },

Updated code from stokeman's answer
block.json
{
    "apiVersion": 2,
    "name": "mbp/details",
    "version": "0.1.0",
    "title": "Details",
    "category": "design",
    "icon": "heart",
    "supports": {
        "align": ["full"],
        "__experimentalLayout": {
        "allowSwitching": false,
        "default": {
                "inherit": true
        }
}
    },
        "attributes": {
    "align": {
            "type": "string",
            "default": "full"
        }
    },
    "textdomain": "mobilebevpros",
    "editorScript": "file:../../../../build/details.js"
}

edit.js
import { __ } from "@wordpress/i18n";
import {
    useBlockProps,
    useSetting,
    InnerBlocks,
} from "@wordpress/block-editor";

export default function Edit() {
    const defaultLayout = useSetting("layout") || {};
    return (
        <div {...useBlockProps()}>
            <InnerBlocks __experimentalLayout={defaultLayout} />
        </div>
    );
}

A: You're pretty close. Specifying layout details in block.json should nest inside a "default" property. Doing so will have the Layout panel display accordingly but there's more to it than that.
If you want the default layout for the block, there is no need to add contentSize or wideSize. Here is the layout config I'd recommend (within the block json supports property):
        "__experimentalLayout": {
            "allowSwitching": false,
            "default": {
                "inherit": true
            }
        }

That will make the Layout panel in the block's sidebar/inspector simplified to only show the inherit toggle (on by default) and not the size inputs.
Even though the block.json specifies that layout should inherit by default, the default needs to be manually retrieved and passed to InnerBlocks in the edit component:
import {
    useBlockProps, // already in use from example
    useSetting     // new bit
} from '@wordpress/block-editor';

export default function Edit() {
    const defaultLayout = useSetting( 'layout' ) || {};
    return (
        <div {...useBlockProps()}>
            <InnerBlocks __experimentalLayout={ defaultLayout } />
        </div>
    );
}

Besides that the block must be registered on the server but I take it that's already being done.
I'm not sure I wouldn't look for alternative solutions since the experimental nature of the API means it will need some care to not break in future updates to the site.

A: Based on what I understand of what you're trying to do, I think it might be best accomplished by registering a block variation for the Group block. It can preset the padding and inheritance of the default layout and has options that can make it appear as its own separate block. This example creates one that will show up in the inserter as "Dat Section" and has some preset padding and a custom class:
wp.blocks.registerBlockVariation(
    'core/group',
    {
        name:'dat-section',
        title: 'Dat Section',
        isActive: (blockAttributes, vAttributes) =>
            blockAttributes.className
                .includes(vAttributes.className),
        attributes: {
            className: 'dat-section',
            layout: {
                inherit: true,
            },
            style:{
               spacing:{
                   padding: { top: '25px', bottom:'55px' }
               }
            }
        },
    }
);

There are more options too. You can set a different icon and description or specify innerBlocks to have it insert with some blocks nested already.


text:
Q: Deep linking callback issues in iOS11 I have implemented deep linking in my app using URL schema which is working properly in all versions of iOS except 11. The issue is when I load AppURLSchema:// in the device browser it launches the app but none of the appDelegate methods gets called to get the deep linking URL so that I can perform deep linking so that user will be able to see different content based upon the URL.
None of the following functions are getting called:
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation

This is not an issue on iOS 10, it seems to have been introduced in iOS 11.
Any help will be appreciated.
Thanks!!

A: I'm facing the same problem and I discovered that the SDK Firebase integrated in my app is blocking the following callback: application:openURL:options.
Without configuring Firebase, all is working ok.

A: It's not just Configuring Firebase SDK causing this issue. With Firebase SDK it's working fine but There is Localytics SDK also integrated in my app and there is some conflict between FIREBASE and LOCALYTICS SDKs due to which my app was not getting the callback.
So I just removed Firebase framework based upon the priority and everything started working fine.

A: As mentioned in Localytics Documentation, integrations for both platforms can lead to conflicts, particularly around the handling of deeplinks.
You can prevent Firebase from swizzling the methods in your AppDelegate by adding FirebaseAppDelegateProxyEnabled set to NO in your app's info.plist as described in Firebase documentation.


text:
Q: Pass lastInsertId() in variable I get the last insertid with pdo in object1.php:
object1.php
class 1234{
    public function test{
        $query = "INSERT INTO " . $this->table_name . "
        SET uid=:uid, order_id=:order_id, position=:position, optionindex=:optionindex, created=:created";

        if($stmt->execute()){
            $last_id = $this->conn->lastInsertId();
        }
        print_r($last_id); //works here fine
        return true;
        }
    }
}

So next i need to pass $last_id in object2.php.
The only way it works for me, to use sessions ... but isn´t there a better solution?
Thanks


text:
Q: Convert character vector of height in inches to cm? I am given a character vector:
tibble(H = c("6'2\"", "5'10\"", "5'5\"", "5'1\"", "5'5\"", "5'4\""))

and I want to convert it to be in cm.
Please advise how can I do this?

A: There are couple of methods to use
1) Read with fread after pasting into a single string
library(data.table)
fread(paste(sub('"', "", df1$H), collapse="\n"), sep="'")[,
               as.matrix(.SD) %*% c(30.48, 2.54)][,1]
 #[1] 187.96 177.80 165.10 154.94 165.10 162.56

2)  Using gsubfn
library(gsubfn)
as.numeric(gsubfn("(\\d)'(\\d+)", ~ as.numeric(x) * 30.48 +
            as.numeric(y) * 2.54, sub('"', '', df1$H)))
 #[1] 187.96 177.80 165.10 154.94 165.10 162.56

3) with separate
library(tidyverse)
df1 %>%
    separate(H, into = c("H1", "H2"), convert = TRUE) %>%
    transmute(H = H1 * 30.48 + H2 * 2.54)
# A tibble: 6 x 1
#      H
#  <dbl>
#1  188.
#2  178.
#3  165.
#4  155.
#5  165.
#6  163.

4) with measurements
library(measurements)
library(tidyverse)
df1 %>%
   separate(H, into = c("H1", "H2"), convert = TRUE) %>%
   transmute(H = conv_unit(H1, "ft", "cm") + conv_unit(H2, "inch", "cm"))

A: One option is to extract all the numbers and convert it into a matrix and then perform the calculation.
mat <- stringr::str_extract_all(df$H, "\\d+", simplify = TRUE)

as.numeric(mat[, 1]) * 30.48 + as.numeric(mat[, 2]) * 2.54
#[1] 187.96 177.80 165.10 154.94 165.10 162.56

where mat is
#     [,1] [,2]
#[1,] "6"  "2"
#[2,] "5"  "10"
#[3,] "5"  "5"
#[4,] "5"  "1"
#[5,] "5"  "5"
#[6,] "5"  "4"

First column is feet and second column inches.

And just for my own curiosity I wanted to solve this in base R
sapply(strsplit(sub("(\\d+)'(\\d+).*", "\\1-\\2", df$H), "-"), function(x)
       as.numeric(x[1]) * 30.48 + as.numeric(x[2]) * 2.54)

#[1] 187.96 177.80 165.10 154.94 165.10 162.56

This follows similar logic that extract 2 numbers from the string using sub, split them using strsplit and then for each of them convert it into numeric and perform the calculation.

A: Using the stringi package to extract the relevant units:
library(stringi)

Raw <- c("6'2\"", "5'10\"", "5'5\"", "5'1\"", "5'5\"", "5'4\"")

## Extract Feet units by regex searching for 1 or more digits followed by a '
Feet <- stri_extract_first_regex(Raw, "[[:digit:]]+(?=')"))

## Extract Inch units by regex searching for 1 or 2 digits followed by a "
Inches <- stri_extract_first_regex(Raw, "[[:digit:]]{1,2}(?=\")"))

## Combine Feet and Inches
TotalInches <- 12 * as.numeric(Feet) + as.numeric(Inches)

## Convert to cm
CM <- 2.54 * TotalInches

print(CM)
# [1] 187.96 177.80 165.10 154.94 165.10 162.56

If you need to do this for multiple columns, it might make sense to define the steps as a function at the top of your script so you can call it more concisely and don't need to store intermediate results in the global environment.
One other consideration taken in the function version here is to replace NA matches with 0 values so that valid measurements like 1' or 11"return valid results instead of NA as well.
FtInToCm <- function(x){
  Feet <- as.numeric(stringi::stri_extract_first_regex(Raw, "[[:digit:]]+(?=')"))
  Inches <- as.numeric(stringi::stri_extract_first_regex(Raw, "[[:digit:]]{1,2}(?=\")"))
  return(2.54 * (12 * ifelse(is.na(Feet),0,Feet) + ifelse(is.na(Inches),0,Inches)))
}

FtInToCm(Raw)
#[1] 187.96 177.80 165.10 154.94 165.10 162.56

A: > dat <- tibble(H = c("6'2\"", "5'10\"", "5'5\"", "5'1\"", "5'5\"", "5'4\""))
> dat$inches <- gsub("[\"]", "",dat$H) %>%
    strsplit(., "'") %>%
    lapply(., function(x) {
      x <- as.numeric(x);
      (x[1]*30.48) + (x[2]/12)*30.48
    }) %>%
   unlist
> dat
# A tibble: 6 x 2
  H        inches
  <chr>     <dbl>
1 "6'2\""    188.
2 "5'10\""   178.
3 "5'5\""    165.
4 "5'1\""    155.
5 "5'5\""    165.
6 "5'4\""    163.

You can even use map instead of lapply
> gsub("[\"]", "",dat$H) %>%
    strsplit(., "'") %>%
    map_dbl(function(x){
      x <- as.numeric(x)
      (x[1]*30.48) + (x[2]/12)*30.48
    })
[1] 187.96 177.80 165.10 154.94 165.10 162.56

A: I add another answer, just to give you another option and because I already wrote it before I saw the other answers.
I convert the string to numeric first and then convert units:
library(dplyr)
library(stringr)
df <- tibble(H = c("6'2\"", "5'10\"", "5'5\"", "5'1\"", "5'5\"", "5'4\""))

df %>%
  mutate(foot = str_extract(H, "^\\d+'"),
         inch = str_extract(H, "\\d+\"$")) %>% # split foot from inch
  mutate(foot = as.numeric(str_remove(foot, "[^\\d]")),
         inch = as.numeric(str_remove(inch, "[^\\d]"))) %>% # convert to numeric
  mutate(H_new = cm(foot * 12) + cm(inch)) # convert units
# A tibble: 6 x 4
  H         foot  inch H_new
  <chr>    <dbl> <dbl> <dbl>
1 "6'2\""      6     2  188.
2 "5'10\""     5    10  178.
3 "5'5\""      5     5  165.
4 "5'1\""      5     1  155.
5 "5'5\""      5     5  165.
6 "5'4\""      5     4  163.


text:
Q: Как сделать появление блока при наведении или нажатию на иконку? Как сделать появление блока при наведении или нажатию на иконку?
Код окна с иконкой:
https://jsfiddle.net/alexshev07/85pvxzog/2/

.picker-block {
  max-width: 220px;
}

/*окно с текстом и цветам*/

.popup-window {
  background: rgb(190, 231, 209);
  border-radius: 5px;
  -moz-border-radius: 5px;
  position: relative;
  padding: 5px;
  max-width: 220px;
  text-align: center;
  margin-bottom: 10px;
  height: 150px;
  justify-content: space-around;
}

/*треугольник*/

.popup-window:after {
  content: '';
  border: 12px solid transparent;
  border-top: 12px solid rgb(190, 231, 209);
  position: absolute;
  left: 50%;
  margin-left: -12px;
  bottom: -24px;
  width: 0;
}

/*Круг в котором иконка*/

.round-popup {
  position: relative;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #d3d3d3;
  margin: 0 auto;
}

/*Иконка*/

.fa-fill-drip {
  position: absolute;
  top: 25%;
  left: 25%;
}

/*Флекс режим*/

.d-flex {
  display: flex;
  flex-wrap: wrap;
}

/*Цветные блоки*/

.red-block {
  width: 50px;
  height: 50px;
  background-color: red;
}

.green-block {
  width: 50px;
  height: 50px;
  background-color: green;
}

.blue-block {
  width: 50px;
  height: 50px;
  background-color: blue;
}

Выберите цвет!

A: JavaScript (jQuery) в помощь.
При клике:

$(".round-popup").click(function() {
  if ($(".d-flex").is(":hidden")) {
    $(".d-flex").slideDown("slow").css({
      display: "flex"
    });
  } else {
    $(".d-flex").slideUp("slow");
  }
});
.container {
  position: relative;
  overflow: hidden;
  height: 250px;
}

.picker-block {
  max-width: 220px;
  position: absolute;
  bottom: 50px;
  right: 0;
  left: 0;
}

/*окно с текстом и цветам*/

.popup-window {
  background: rgb(190, 231, 209);
  border-radius: 5px;
  -moz-border-radius: 5px;
  position: relative;
  padding: 5px;
  max-width: 220px;
  text-align: center;
  margin-bottom: 10px;
  height: 150px;
  justify-content: space-around;
}

/*треугольник*/

.popup-window:after {
  content: '';
  border: 12px solid transparent;
  border-top: 12px solid rgb(190, 231, 209);
  position: absolute;
  left: 50%;
  margin-left: -12px;
  bottom: -24px;
  width: 0;
}

/*Круг в котором иконка*/

.round-popup {
  position: relative;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #d3d3d3;
  margin: 0 auto;
  cursor: pointer;
}

/*Иконка*/

.fa-fill-drip {
  position: absolute;
  top: 25%;
  left: 25%;
}

/*Флекс режим*/

.d-flex {
  display: flex;
  flex-wrap: wrap;
  display: none;
}

.round-popup:hover~.d-flex {
  display: block;
}

/*Цветные блоки*/

.red-block {
  width: 50px;
  height: 50px;
  background-color: red;
}

.green-block {
  width: 50px;
  height: 50px;
  background-color: green;
}

.blue-block {
  width: 50px;
  height: 50px;
  background-color: blue;
}

Выберите цвет!

При наведении:

$(".round-popup").hover(function() {
  if ($(".d-flex").is(":hidden")) {
    $(".d-flex").slideDown("slow").css({
      display: "flex"
    });
  } else {
    // $(".d-flex").slideUp("slow");
  }
  $(function() {
    $(".container").hover(onIn, onOut);
  });
  function onIn() {
    $(this).css({
      display: "flex"
    });
  }
  function onOut() {
    $(".d-flex").slideUp("slow");
  }
});
.container {
  position: relative;
  overflow: hidden;
  height: 250px;
}

.picker-block {
  max-width: 220px;
  position: absolute;
  bottom: 50px;
  right: 0;
  left: 0;
}

/*окно с текстом и цветам*/

.popup-window {
  background: rgb(190, 231, 209);
  border-radius: 5px;
  -moz-border-radius: 5px;
  position: relative;
  padding: 5px;
  max-width: 220px;
  text-align: center;
  margin-bottom: 10px;
  height: 150px;
  justify-content: space-around;
}

/*треугольник*/

.popup-window:after {
  content: '';
  border: 12px solid transparent;
  border-top: 12px solid rgb(190, 231, 209);
  position: absolute;
  left: 50%;
  margin-left: -12px;
  bottom: -24px;
  width: 0;
}

/*Круг в котором иконка*/

.round-popup {
  position: relative;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #d3d3d3;
  margin: 0 auto;
  cursor: pointer;
}

/*Иконка*/

.fa-fill-drip {
  position: absolute;
  top: 25%;
  left: 25%;
}

/*Флекс режим*/

.d-flex {
  display: flex;
  flex-wrap: wrap;
  display: none;
}

.round-popup:hover~.d-flex {
  display: block;
}

/*Цветные блоки*/

.red-block {
  width: 50px;
  height: 50px;
  background-color: red;
}

.green-block {
  width: 50px;
  height: 50px;
  background-color: green;
}

.blue-block {
  width: 50px;
  height: 50px;
  background-color: blue;
}

Выберите цвет!

A: Только CSS, только хардкор..
При наведение:

.change-color {
  display: block;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  position: relative;
  /* --- */
  margin-left: 110px;
  margin-top: 180px;
}

.change-color .icon {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #d3d3d3;
  width: inherit;
  height: inherit;
  border-radius: inherit;
  padding: 1px 0;
  box-sizing: border-box;
  cursor: pointer;
}

.change-color .droped {
  display: none;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  width: 220px;
  height: 150px;
  background: #bee7d1;
  border-radius: 5px;
  position: absolute;
  left: calc(50% - 220px / 2); /* или left: -50%; transform: translateX(-50%);*/
  bottom: calc(30px + 10px);
}

.change-color .droped::after {
  content: '';
  display: block;
  width: 0;
  height: 0;
  border: 10px solid transparent;
  border-top-color: #bee7d1;
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translate(-50%, 100%);
}

.change-color .droped .select {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  width: 100%;
}

.change-color .droped .select .item {
  display: block;
  width: 50px;
  height: 50px;
}

.change-color:hover .droped {
  display: flex;
}

      Выберите цвет!

При клике:

.change-color {
  display: block;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  position: relative;
  /* --- */
  margin-left: 110px;
  margin-top: 180px;
}

.change-color .icon {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #d3d3d3;
  width: inherit;
  height: inherit;
  border-radius: inherit;
  padding: 1px 0;
  box-sizing: border-box;
  cursor: pointer;
}

.change-color .droped {
  display: none;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  width: 220px;
  height: 150px;
  background: #bee7d1;
  border-radius: 5px;
  position: absolute;
  left: calc(50% - 220px / 2); /* или left: -50%; transform: translateX(-50%);*/
  bottom: calc(30px + 10px);
}

.change-color .droped::after {
  content: '';
  display: block;
  width: 0;
  height: 0;
  border: 10px solid transparent;
  border-top-color: #bee7d1;
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translate(-50%, 100%);
}

.change-color .droped .select {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  width: 100%;
}

.change-color .droped .select .item {
  display: block;
  width: 50px;
  height: 50px;
}

#change_color:checked ~ .droped {
  display: flex;
}

  <input type="checkbox" id="change_color" style="display: none;">

      Выберите цвет!

С плавной анимацией
Важно!
В примерах используется pointer-events: none, ознакомьтесь с его поддержкой.
При наведение:

.change-color {
  display: block;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  position: relative;
  /* --- */
  margin-left: 110px;
  margin-top: 180px;
}

.change-color .icon {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #d3d3d3;
  width: inherit;
  height: inherit;
  border-radius: inherit;
  padding: 1px 0;
  box-sizing: border-box;
  cursor: pointer;
}

.change-color .droped {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  width: 220px;
  height: 150px;
  background: #bee7d1;
  border-radius: 5px;
  position: absolute;
  left: calc(50% - 220px / 2); /* или left: -50%; transform: translateX(-50%);*/
  /* anim */
  pointer-events: none;
  opacity: 0;
  bottom: 50px;
  transition: all .3s linear;
}

.change-color .droped::after {
  content: '';
  display: block;
  width: 0;
  height: 0;
  border: 10px solid transparent;
  border-top-color: #bee7d1;
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translate(-50%, 100%);
}

.change-color .droped .select {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  width: 100%;
}

.change-color .droped .select .item {
  display: block;
  width: 50px;
  height: 50px;
}

.change-color:hover .droped {
  pointer-events: all;
  opacity: 1;
  bottom: calc(30px + 10px);
}

      Выберите цвет!

При клике:

.change-color {
  display: block;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  position: relative;
  /* --- */
  margin-left: 110px;
  margin-top: 180px;
}

.change-color .icon {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #d3d3d3;
  width: inherit;
  height: inherit;
  border-radius: inherit;
  padding: 1px 0;
  box-sizing: border-box;
  cursor: pointer;
}

.change-color .droped {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  width: 220px;
  height: 150px;
  background: #bee7d1;
  border-radius: 5px;
  position: absolute;
  left: calc(50% - 220px / 2); /* или left: -50%; transform: translateX(-50%);*/

  /* anim */
  pointer-events: none;
  opacity: 0;
  bottom: 50px;
  transition: all .3s linear;
}

.change-color .droped::after {
  content: '';
  display: block;
  width: 0;
  height: 0;
  border: 10px solid transparent;
  border-top-color: #bee7d1;
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translate(-50%, 100%);
}

.change-color .droped .select {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  width: 100%;
}

.change-color .droped .select .item {
  display: block;
  width: 50px;
  height: 50px;
}

#change_color:checked ~ .droped {
  pointer-events: all;
  opacity: 1;
  bottom: calc(30px + 10px);
}

  <input type="checkbox" id="change_color" style="display: none;">

      Выберите цвет!


text:
Q: Does primeNg upgrade need Angular upgrade? I am planning to use primeng turbo table feature that is included in 5.x.
Right now, we are using version 4.3 in our project. When I upgraded primeng to latest version, I came across many issues. Many answers in google suggested to upgrade Angular version accordingly.
I want to confirm if the upgrade of primeNg needs an upgrade of Angular as well?

A: According to the newest primeng release notes:

PrimeNG 6.0.0 is fully compatible with Angular 6 and RxJS 6, if you
  are using Angular 5 then you need to continue using PrimeNG 5.x
  instead.

Also 5.0.0 version release is compatible accordingly:

PrimeNG 5 fully support Angular 5, if your project is on Angular 4,
  the PrimeNG version to use would be 4.x as PrimeNG 5 does not work on
  Angular 4 due to AOT constraints.

So try to always check release notes.

A: If you want to use PrimeNG 6, then it is fully compatible with angular 6 and you cannot use primeNG 6 with angular 5, you can only use PrimeNG 5 with angular 5.
You can read that here: https://www.primefaces.org/primeng-6-0-0-released/
If you want to use PrimeNG 7.0.0, then you need to upgrade to angular 7.
The PrimeNG 4.2.3 is compatible with angular 5: https://www.primefaces.org/primeng-4-2-2-released/

So you need to verify the compatible angular version and upgrade to it, when you use a newer version of PrimeNG


text:
Q: Correct launch.json for VS Code to attach to a port of a running nodejs process I'm trying to get the following setup to work in the VS Code nodejs process. The actual process is already calling node --inspect, and the skaffold debug tool is porting it over to localhost for me:
Port forwarding pod/tickets-depl-64bfdfcbb-lgcrw in namespace default, remote port 9229 -> 127.0.0.1:9229

The container is set up like this:
/
  app/
    src/  -- sources in typescript
    build/ -- output of tsc, with the .js files and the .map files.

On my Mac, the VS Code project directory has:
[project dir]/
  ticketing/  -- micro-service under the project
    src/  -- original source files
    Dockerfile
    ...

I've tried all kinds of things for launch.json. Here's what I have now:

    {
      // Use IntelliSense to learn about possible attributes.
      // Hover to view descriptions of existing attributes.
      // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
      "version": "0.2.0",
      "configurations": [
        {
          "name": "Attach to Ticketing Port",
          "protocol": "inspector",
          "request": "attach",
          "address": "localhost",
          "port": 9229,
          "skipFiles": [
            "<node_internals>/**"
          ],
          "type": "node",
          "localRoot": "${workspaceFolder}/tickets/src",
          "outFiles": ["${workspaceFolder}/tickets/build/**/*.js"],
          "remoteRoot": "/app/src",
          "trace": true

        },
      ]
    }

This connects with the project, but I cannot set breakpoints in my source files, and my source files do not appear in loaded files.
This is not an uncommon problem, but I'll admit I don't find much in the way of good advice as to what to do. Is VS Code currently broken in Version: 1.56.2, or is this just very, very hard to get right?
In case this is related to how I'm generating the source maps, here's tsconfig.json:
{
  "exclude": [
    "__test__",
    "**/__mocks__/*",
    "node_modules",
    "**/*.test.ts",
    "**/test/setup.ts"
  ],
  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    "sourceMap": true,                       /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./build",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}


text:
Q: How to check whether a sentence is correct (simple grammar check in Python)? How to check whether a sentence is valid in Python?
Examples:
I love Stackoverflow - Correct
I Stackoverflow love - Incorrect

A: Some other answers have mentioned LanguageTool, the largest open-source grammar checker. It didn't have a reliable, up-to-date Python port until now.
I recommend language_tool_python, a grammar checker that supports Python 3 and the latest versions of Java and LanguageTool. It's the only up-to-date, free Python grammar checker. (full disclosure, I made this library)

A: I would suggest the language-tool-python. For example:
import language_tool_python
tool = language_tool_python.LanguageTool('en-US')

text = "Your the best but their are allso  good !"
matches = tool.check(text)
len(matches)

and we get:
4

We can have a look at the 4 issues that it found:
1st Issue:
matches[0]
And we get:
Match({'ruleId': 'YOUR_YOU_RE', 'message': 'Did you mean "You\'re"?', 'replacements': ["You're"], 'context': 'Your the best but their are allso  good !', 'offset': 0, 'errorLength': 4, 'category': 'TYPOS', 'ruleIssueType': 'misspelling'})

2nd Issue:
matches[1]
and we get:
Match({'ruleId': 'THEIR_IS', 'message': 'Did you mean "there"?', 'replacements': ['there'], 'context': 'Your the best but their are allso  good !', 'offset': 18, 'errorLength': 5, 'category': 'CONFUSED_WORDS', 'ruleIssueType': 'misspelling'})

3rd Issue:
matches[2]
and we get:
Match({'ruleId': 'MORFOLOGIK_RULE_EN_US', 'message': 'Possible spelling mistake found.', 'replacements': ['also', 'all so'], 'context': 'Your the best but their are allso  good !', 'offset': 28, 'errorLength': 5, 'category': 'TYPOS', 'ruleIssueType': 'misspelling'})

4th Issue:
matches[3]
and we get:
Match({'ruleId': 'WHITESPACE_RULE', 'message': 'Possible typo: you repeated a whitespace', 'replacements': [' '], 'context': 'Your the best but their are allso  good!', 'offset': 33, 'errorLength': 2, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace'})

If you are looking for a more detailed example you can have a look at the related post of Predictive Hacks

A: There are various Web Services providing automated proofreading and grammar checking. Some have a Python library to simplify querying.
As far as I can tell, most of those tools (certainly After the Deadline and LanguageTool) are rule based. The checked text is compared with a large set of rules describing common errors. If a rule matches, the software calls it an error. If a rule does not match, the software does nothing (it cannot detect errors it does not have rules for).
After the Deadline
import ATD
ATD.setDefaultKey("your API key")
errors = ATD.checkDocument("Looking too the water. Fixing your writing typoss.")
for error in errors:
 print "%s error for: %s **%s**" % (error.type, error.precontext, error.string)
 print "some suggestions: %s" % (", ".join(error.suggestions),)

Expected output:
grammar error for: Looking **too the**
some suggestions: to the
spelling error for: writing **typoss**
some suggestions: typos

It is possible to run the server application on your own machine, 4 GB RAM is recommended.
LanguageTool
https://pypi.python.org/pypi/language-check
>>> import language_check
>>> tool = language_check.LanguageTool('en-US')
>>> text = 'A sentence with a error in the Hitchhiker's Guide tot he Galaxy'
>>> matches = tool.check(text)

>>> matches[0].fromy, matches[0].fromx
(0, 16)
>>> matches[0].ruleId, matches[0].replacements
('EN_A_VS_AN', ['an'])
>>> matches[1].fromy, matches[1].fromx
(0, 50)
>>> matches[1].ruleId, matches[1].replacements
('TOT_HE', ['to the'])

>>> print(matches[1])
Line 1, column 51, Rule ID: TOT_HE[1]
Message: Did you mean 'to the'?
Suggestion: to the
...

>>> language_check.correct(text, matches)
'A sentence with an error in the Hitchhiker's Guide to the Galaxy'

It is also possible to run the server side privately.
Ginger
Additionally, this is a hacky (screen scraping) library for Ginger, arguably one of the most polished free-to-use grammar checking options out there.
Microsoft Word
It should be possible to script Microsoft Word and use its grammar checking functionality.
More
There is a curated list of grammar checkers on Open Office website. Noted in comments by Patrick.

A: Check out NLTK.  They have support for grammars that you can use to parse your sentence.  You can define a grammar, or use one that is provided, along with a context-free parser.  If the sentence parses, then it has valid grammar; if not, then it doesn't.  These grammars may not have the widest coverage (eg, it might not know how to handle a word like StackOverflow), but this approach will allow you to say specifically what is valid or invalid in the grammar.  Chapter 8 of the NLTK book covers parsing and should explain what you need to know.
An alternative would be to write a python interface to a wide-coverage parser (like the Stanford parser or C&C).  These are statistical parsers that will be able to understand sentences even if they haven't seen all the words or all the grammatical constructions before.  The downside is that sometimes the parser will still return a parse for a sentence with bad grammar because it will use the statistics to make the best guess possible.
So, it really depends on exactly what your goal is.  If you want very precise control over what is considered grammatical, use a context-free parser with NLTK.  If you want robustness and wide-coverage, use a statistical parser.

A: Step 1
pip install Caribe

Step 2
import Caribe as cb
sentence="I is playing football"
output=cb.caribe_corrector(sentence)
print(output)


text:
Q: Java 7 to Java 8 using streams Converting the below code from Java 7 to Java 8 using streams
Java 7:
if (Objects.nonNull(input.getList())) {
    if (Objects.nonNull(input.getId()) && !input.getList().contains(input.getId())) {
        input.getList().add(input.getId());
    }
} else if (Objects.nonNull(input.getId())) {
    List<Long> ids = new ArrayList<>();
    ids.add(input.getId());
    input.setList(ids);
}

I tried something like this but it does not work properly.
Java 8
Stream.concat(input.getList().stream(),
                input.getList().stream().filter(list2 -> !input.getList().contains(input.getId())));

Input class has two fields List<Long> list and Long id
Can someone please correct where I am missing.


text:
Q: Finger controlled view slide animation I would like to know how to implement an animation where the user can slide one view over another using his finger. To simplify things I will post some pictures to explain what I mean.
At first we have a view which has a settings icon (that pink thingie in the upper left corner). The view can can be manipulated by any means necessary - including swiping. See picture 1.

When the user presses the settings button the view slides away and reveals settings view underneath. To do this I just use [UIView beginAnimations:nil context:nil] adjust the main view frame and commit animations. The situation looks like this: (settings are purple, main view is still the same colour)

Now when the user decides he want the main screen back he will have to grab it and slide it back into its place. HOW? Now I have been using UITapGestureRecognizer which would trigger a reverse animation so that the view slid back in its original place. That was messy and the user was still able to manipulate that small section of the view visible.
I want the view to follow the user's finger and slide and scale its way back in its place. The main view should not be manipulatable while moving. To understand what I mean you can check the Yahoo Weather app which has a similar thing going on - except that my view would also shrink a bit vertically. The third picture shows things "in motion":

Please provide links or code that can help me accomplish this.
Cheers, Jan.

A: Look at this code:

*

*MMDrawerController

*MSMatrixController
And you can try this
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[touches allObjects] objectAtIndex:0];
    CGPoint touchPt = [touch locationInView:self];

    float deltaX = touchPt.x - beginPt.x; //where beginPt is CGPoint variable which was set in touches began
    float deltaY = touchPt.y - beginPt.y;
    if (deltaX < 0) {
        deltaX = -deltaX;
    }
    if (deltaY < 0) {
        deltaY = -deltaY;
    }

    CGPoint toPt;
    toPt.x = deltaX;
    toPt.y = deltaY;

    yourMovedView.center = toPt;
}


text:
Q: android- dropbox download files I am currently working on an android app that is to support the android dropbox api. i am successfully sending the files to my dropbox folder.now i want to download the files and save into the sdcard. at the moment when i am trying to download files it gives me an error this
DropboxServerException (nginx): 404 Not Found (File not found)

here is my code
public void downloadFiles(String filename){
        Log.i("filename is ",filename);

        File mFile=new File(Environment.getExternalStorageDirectory().getPath() + "/Download1");
        try {
            FileOutputStream mFileOutputStream=new FileOutputStream(mFile);
            DropboxFileInfo mDropboxFileInfo=mApi.getFile(filename, null, mFileOutputStream, null);
            } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (DropboxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
    }

filename is successfully printing on the LogCat. and the file is in my Photos Folder in dropbox. but i am not able to download it .

A: The filename is the problem. You need to get it like "/Photos/" + filename as you have mentioned it is inside your Photos folder not in your root.
  DropboxFileInfo mDropboxFileInfo=mApi.getFile("/Photos/" + filename, null, mFileOutputStream, null);


text:
Q: Redux Thunk action not executing I'm using React with Redux and Thunk as middleware to handle async actions. I have a button where when a user clicks it, it should logout the user. Currently when I click the button nothing happens. I've added a console.log in the attemptLogout but even that isn't triggering... I can't figure out why, was hoping someone could review my code and provide some feedback.
NavProfile.js
const onLogout = () => {
  attemptLogout();
};

<Menu.Item key={menuItem.legth + 1} onClick={onLogout}>

        <LogoutOutlined className="mr-3" />
        Logout

</Menu.Item>

redux/actions/Auth.js
export const logout = () => ({
  type: LOGOUT,
});

redux/reducers/Auth.js
const initialState = {
  token: localStorage.getItem('token'),
  isAuthenticated: false,
  loading: true,
  error: {},
};

const auth = (state = initialState, action) => {
  const { type, payload } = action;

  switch (type) {
    ...
    case LOGOUT:
      return {
        ...state,
        token: null,
        isAuthenticated: false,
        loading: false,
      };
    default:
      return state;
  }
};

redux/reducers/User.js
const initialState = {
  user: null,
  loading: true,
  error: {},
};

const user = (state = initialState, action) => {
  const { type, payload } = action;

  switch (type) {
    ...
    case LOGOUT:
      return {
        ...state,
        loading: false,
        user: null,
      };
    default:
      return state;
  }
};

redux/thunks/Auth.js
// Logout User
export const attemptLogout = () => async (dispatch) => {
  console.log('Logout');
  dispatch(logout());
  dispatch(push('/auth/login'));
};

A: You need to dispatch attemptLogout. Otherwise the thunk never passed through redux middleware and is never called.
const onLogout = () => {
  dispatch(attemptLogout());
};

To access dispatch you can use the hook in your menu/menu item component. Something like:
import {useDispatch} from 'react-redux';

function MenuExample() {
  const dispatch = useDispatch();

  const onLogout = () => {
    dispatch(attemptLogout());
  };

  ...
}


text:
Q: JavaScript array not recognized I have a problem.
I have the following JavaScript array created:
    <script type="text/javascript">
      ArrayName['FirstValue']['SecondValue'] = {
       name = 'checbox_id'
       checked = true }
    </script>

But when I call the Global Array in a function here is a sample call:
    ArrayName[value1][value2] = true;

I'm getting a messaging stating that ArrayName is undefined.
What would a correct way to create an array similar to the one above?

A: You are attempting to set an element in an array called ArrayName, which is not declared anywhere:
<script type="text/javascript">
   // You are attempting to access an array but it hasn't been declared:
   ArrayName['FirstValue']['SecondValue'] = {
   name = 'checbox_id'
   checked = true }
</script>

Your syntax indicates that this is an array that contains nested arrays, like this:
var ArrayName = [[1,2,3], [4,5,6], [7,8,9]];

So, if you wanted to get the number 8, you'd need to access the third array element and get the second value found in the array stored there with this syntax:
// Remember, array indexes start counting from zero
ArrayName[2][1];  // Get the third element's, second item

Or (if we take your example literally, where you are searching for literal strings that are not positive integers), ArrayName wouldn't be an array, it would be an Object that you are trying to access the property FirstValue of and this property then stores another object as its value and that object has a property called SecondValue.  That structure would look like this:
var myObjectLiteral = {
  FirstValue : { SecondValue : something }
}

But, without knowing what you are trying to accomplish, we can't possibly help you write the array or the object.
Next, we have to talk about the object that you are trying to assign to the array:
{
       name = 'checbox_id'
       checked = true
}

This syntax is incorrect. You are missing a comma to separate on key/value pair from the next. It should be:
{
       name : 'checbox_id',
       checked : true
}


text:
Q: jpeg image data is shifted in ios UIImageView I'm trying to send a jpeg image data from a tcp server to a tcp client and my client side device is an iphone mobile.
I compressed bitmap data to jpeg data in the server with opencv using cv::imencode.
If i send this image from server :

Then in the client side i have this image :

As see ,the image is shifted one pixel per row! Also in swift i used from NSData for showing the received bytes to UIImage :
let dataImage = NSData(bytes: encodedData, length: dlen)
let image = UIImage(data: dataImage as Data)
uiImageView.image = image

I see encodedData array in ios side and that was exactly same with the server sent data, And before of testing this in iphone i tested that in android and there , everything was right but now seems iphone doesn't decode the image rightly.
Does anyone know what is happening there?


text:
Q: Print variables after being redirected I have a register form that upon being completed and validated, it will redirect the user to a page/file where I want to tell him something like
Thank you for registering, ' . $name_register . '. You may login using the form to the left using your username ' . $username_register . ' and your password

How can I pass the variables to my other file?

A: To store variables in client(browser) side, best thing is Session. Just set the session and use it later whenever you want to.
//Set data in session
$_SESSION['name_register']="Miral Viroja";
//Retrieve data from session
echo "Welcome Mr ". $_SESSION['name_register'];


text:
Q: Apache: Redirect site visitors from sub-directory to subdomain and preserve trailing URL after sub-directory Running LAMP stack...
I'm attempting to redirect my company's domain.com/blog traffic to a new sub-domain (e.g. blog.domain.com) while preserving any trailing URL after the sub-directory (domain.com/blog/article1234 turns into blog.domain.com/article1234).
I've attempted several variations with my .htaccess file using rewrite rules and conditions and this seems to be the closest I've gotten to success:
RewriteRule ^blog/?$ https://blog.domain.com/ [NC,R,L]

I also thought I was getting close with this:
RewriteRule ^blog/(.*)$ blog.domain.com/?p=$1 [R=302,L]

But that ended up breaking URLs somehow. I don't personally care if it's 302 or 301 - we intend to keep this sub-domain indefinitely but I've had nightmarish issues with 301s in the past. Open to anything at this point.
Thoughts? Thanks in advance.

A: Your second attempt was close to perfect, I just made some small modifications:
RewriteEngine on
RewriteRule ^/?blog/?(.*)$ blog.domain.com/$1 [R=302,END,QSA]

In case you use an older apache server you may have to replace the END flag with the L flag which usually works unless you have conflicting rules.
And a general hint: you should always prefer to place such rules inside the http servers host configuration instead of using .htaccess style files. Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).


text:
Q: Table has multiple records in which mobileNumber column is in only few records . I need to get those records only Table has multiple records in which mobileNumber column is in only few records . I need to get those records only.
By this query i am getting all records.
$request = [
    'TableName' => 'tbl_camp',
    'ExpressionAttributeNames' => [
        '#mobileNumber' => 'mobileNumber'
    ],
    'ExpressionAttributeValues' => [
        ':val1' => ['S' => 'NULL']
    ],
    'FilterExpression' => '#mobileNumber <> :val1',
];

A: You can use attribute_exists() function to filter out items with whether certain attribute present.
Your query becomes something like this:
$request = [
    'TableName' => 'tbl_camp',
    'ExpressionAttributeNames' => [
        '#mobileNumber' => 'mobileNumber'
    ],
    'ExpressionAttributeValues' => [
        ':val1' => ['S' => 'NULL']
    ],
    'FilterExpression' => 'attribute_exists(#mobileNumber)',
];

You can read about this at AWS documentation.


text:
Q: Python, PyGame image not displaying I am new to pygame and just learned what class is
I wanted to make the player shoot bullets but the bullets aren't drawn on the screen.
There are 4 python files

*

*Game.py: The main file. Gets inputs, updates and draws screen

*background.py: class for background

*player.py: class for player and has player actions

*ect.py: bullet class. Initialization of bullet object.

So what I thought was to first load image and make surface for each bullet,
second update position, then draw image on surface. If bullet is near destination delete it.
While running every time I press spacebar to call shoot function this warning comes up"libpng warning: iCCP: known incorrect sRGB profile". I believe I can ignore this.Anyways I wasn't able to find out why the bullet image didn't show up.
Can anyone please help me with this? Thanks. And any advice is welcomed!
Game.py
import pygame as pyg
from pygame.locals import *
import sys
import player
import background, ect

#Screen size
s_width = 1280
s_height = 720
screen_size = (s_width,s_height)

#Player
p_speed = 5

#Initialization
pyg.init()
screen = pyg.display.set_mode(screen_size)
pyg.display.set_caption("Shoot")

#Set background
Background = background.Background("forest2.jpeg",(0,0))

#Set Player
Player= player.Player("Crab.png",100,100,640,360)

#Input
keys = {"right":False , "left":False ,  "up":False , "down":False , "bullet":False }
bullets = []

#Main Loop
running = True
while running:

    #Get inputs
    for event in pyg.event.get():
        if event.type == QUIT:
            pyg.quit()
            sys.exit()

        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                keys['left'] = True
            elif event.key == K_RIGHT:
                keys['right'] = True
            elif event.key == K_UP:
                keys['up'] = True
            elif event.key == K_DOWN:
                keys['down'] = True
            elif event.key == K_SPACE:
                keys['bullet'] = True
            elif event.key == K_q:
                pyg.quit()
                sys.exit()

        elif event.type == KEYUP:
            if event.key == K_LEFT:
                keys['left'] = False
            elif event.key == K_RIGHT:
                keys['right'] = False
            elif event.key == K_UP:
                keys['up'] = False
            elif event.key == K_DOWN:
                keys['down'] = False
            elif event.key == K_SPACE:
                keys['bullet'] = False

    #Get time
    Player.clock.tick(60)
    dt = Player.clock.get_time()
    dt *= 0.001

    #Update values
    if keys['right']:
        Player.x += p_speed
    if keys['left']:
        Player.x -= p_speed
    if (keys['up'] and Player.on_ground):
        Player.jump()
    if keys['bullet']:
        Player.shoot(bullets)

    if Player.on_ground == False: #Gravity
        Player.give_force(0,-750)

    Player.update_pos(dt)

    if Player.y >= 500:
        Player.y = 500
        Player.y_vel = 0
        Player.y_accel = 0

        Player.on_ground = True

    for bullet in bullets:
        bullet.update(dt)
        if (bullet.desx - bullet.x)<0.3:
            del bullet

    #Draw
    screen.fill([255,255,255])
    screen.blit(Background.image,Background.rect)
    screen.blit(Player.player_sprite,(Player.x,Player.y))

    for bullet in bullets:
        bullet.draw_bullet()

    #Update game state
    pyg.display.flip()
    pyg.display.update()

player.py
#imports
import pygame as pyg
import sys, math
import ect

class Player(pyg.sprite.Sprite):
    """
    This class represents the player image
    and contains player actions
    """

    def __init__(self, player_sprite_file, width, height, x, y):
        pyg.sprite.Sprite.__init__(self)

        #initialize variables(Size, Coordinate, clock)
        self.width = width
        self.height = height
        self.x = x + width/2
        self.y = y - height/2
        self.on_ground = False
        self.clock = pyg.time.Clock()
        self.x_vel = 0
        self.y_vel = 0
        self.x_accel = 0
        self.y_accel = 0

        #create sprite(1. Load 2. Scale 3. Get rect 4. Create surface
        self.player_sprite = pyg.image.load(player_sprite_file)
        self.player_sprite = pyg.transform.scale(self.player_sprite, (width,height))
        self.player_sprite_rect = self.player_sprite.get_rect()
        self.player_sprite_rect.left ,self.player_sprite_rect.top = self.x, self.y

    def move(self,x,y): #Moves player to destination
        self.x = x + self.width/2
        self.y = y - self.height/2

    def give_force(self, x_accel, y_accel): #Input: A vector(direction, amount) for now lets keep the direction only up like a jump
        self.x_accel += x_accel
        self.y_accel += y_accel

    def update_pos(self,dt): #Updates 1. time 2. velocity based on acceleration 3. position based on velocity

        self.x_vel += self.x_accel*dt
        self.y_vel += self.y_accel*dt

        self.x += self.x_vel*dt
        self.y -= self.y_vel*dt

    def jump(self):
        self.y_vel += 0
        self.give_force(0,6000)
        self.on_ground = False

    def shoot(self,bullets):
        bullets.append(ect.Bullet(self.x, self.y,self.x+300,self.y))

ect.py
#Imports
import random, math, pygame as pyg
from pygame.locals import *

class Bullet(pyg.sprite.Sprite):
    """
    This class represents bullets
    """

    def __init__(self,x,y,desx, desy):
        pyg.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.desx = desx
        self.desy = desy
        h = math.sqrt(math.pow(desx-x,2) + math.pow(desy-y,2))
        self.speed = 1 + random.randrange(-1,1)
        self.speedx = self.speed*math.acos((desx - x)/h)
        self.speedy = self.speed*math.asin((desy - y)/h)

        self.surface = pyg.Surface((128,128))
        self.image = pyg.image.load("bullet.png")
        self.image = pyg.transform.scale(self.image, (128, 128))
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = x + 64, y -64

    def update(self,dt):
        self.x += (self.speedx*dt)
        self.y -= (self.speedy*dt)

    def draw_bullet(self):
        self.surface.blit(self.image,(self.x -64,self.y + 64))

A: You only blit the self.image of the bullets onto the self.surface instead of the screen surface. Pass the screen to the draw_bullet method and then blit the self.image onto it.
# In the main while loop.
for bullet in bullets:
    bullet.draw_bullet(screen)

#---------------------
# In the Bullet class.
def draw_bullet(self, screen):
    screen.blit(self.image, (self.x -64, self.y + 64))


text:
Q: Retry the Ajax call after five seconds In this snippet, $.ajax(this) in error is making five ajax calls as I needed but I need five seconds delay between each request. Please help!
$.ajax({
  type: "POST",
  data: JSON.stringify(download),
  contentType: "application/json",
  url: '',
  retryCount: 1,
  retryLimit: 5,
  success: function(data) {
    $.ajax({
      type: "GET",
      url: '',
    })
        .success(function(data) {

    })
        .error(function(data) {

    })
  },
 //It has to go into error
  error : function(xhr, textStatus, errorThrown ) {
    this.retryCount++;
    if (this.retryCount <= this.retryLimit) {
      //try again
      $.ajax(this);
      return;
    } else {
      //user comes here After trying in the if loop for 5 times, with each request having five seconds delay. I am not able to keep delay between each request
    }
    return;
  }

});

A: Try this:
error : function(xhr, textStatus, errorThrown ) {
    this.retryCount++;
    if (this.retryCount <= this.retryLimit) {
      //try again
      var ajaxObject = this;
      window.setTimeout(function(){
          $.ajax(ajaxObject);
      },5000);

      return;
    } else {
      //user comes here After trying in the if loop for 5 times, with each request having five seconds delay. I am not able to keep delay between each request
    }
    return;
  }

A: Try wrapping your Ajax call like this:
setTimeout(function() {
    $.ajax(this);
}, 5000);