text:
Q: presentViewController changes the orientation of the controller I want to play a video from a view controller. When I present it, it is presented like it is a portrait orientation, so view turns. It only happens on iPhones,not the iPads.
There is a ViewController > MyItemsController > VideoController

When I close the VideoController, parent controller (MyItemsController) of the video controller is like:

Storyboard of the view controller is:

And the code is:
-(void)playMoviesForItems:(NSArray *)shopItems{
    VideoPlayerViewController* moviePlayer = [self.storyboard instantiateViewControllerWithIdentifier:@"videoPlayerController"];
    moviePlayer.modalPresentationStyle = UIModalPresentationCurrentContext;
    moviePlayer.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:moviePlayer animated:NO completion:nil];
}

I moved the code into app delegate :
-(void)playMoviesForItems:(NSArray *)shopItems{
VideoPlayerViewController* mp = [[self getStoryboard] instantiateViewControllerWithIdentifier:@"videoPlayerController"];
[mp playMoviesForItems:shopItems];
[self pauseBackgroundMusic];

[self.window makeKeyAndVisible];
[self.window.rootViewController presentViewController:mp animated:YES completion:NULL];
}

This time, everything seem to be ok. Movie is playing, I can hear the sound, but cannot see the video. Why?

A: While the accepted answer was down voted since it does not answer the question, here's something that works on iOS9 :
The method that gets called when the ViewController is presented (modally) is preferredInterfaceOrientationForPresentation. This method must return an orientation.
You should check the presenter's orientation and return it as preferred:
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
        UIInterfaceOrientation topOrientation = self.navigationController.visibleViewController.interfaceOrientation;
        UIInterfaceOrientation presentingOrientation = self.presentingViewController.interfaceOrientation;

        return   presentingOrientation ? presentingOrientation : topOrientation ? topOrientation : UIInterfaceOrientationLandscapeLeft;
}

topOrientation contains the visible view controller's orientation, while the presentingOrientation is the orientation of the called to presentViewController:animated...
In general, I advise you to create a "base" UIViewController class, and inherit from it. This way all of your view controllers will benefit from this code.

A: I had this exactly same problem a few minutes ago.
What happened to me is that I was trying to present the new ViewController with a another ViewController which wasn't in the hierarchy, it only had it's view added as a subview of a third ViewController in the hierarchy. To fix the problem, I just made this last ViewController present the new one.
Example of what not to do:
UIViewController *secondController = [UIViewController alloc] init];
[rootViewController presentViewController:secondController animated:NO completion:nil];

UIViewController *controllerOutsideHierarchy = [UIViewController alloc] init];
[secondController.view addSubview:controllerOutsideHierarchy.view];

[controllerOutsideHierarchy presentViewController:thirdController animated:NO completion:nil];

Example of what should be done instead:
UIViewController *secondController = [UIViewController alloc] init];
[rootViewController presentViewController:secondController animated:NO completion:nil];

UIViewController *controllerOutsideHierarchy = [UIViewController alloc] init];
[secondController.view addSubview:controllerOutsideHierarchy.view];

[secondController presentViewController:thirdController animated:NO completion:nil];

Hope this helps!

A: Swift 4.1 version
To prevent auto rotation orientation you need to override shouldAutorotate variable
override var shouldAutorotate: Bool {
    return false
}

To present view controller in landscape mode you need to override preferredInterfaceOrientationForPresentation variable
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return .landscapeLeft// or .landscapeRight
}

You need to present view controller to get it work(It doesn't work for pushed view controller)

A: Make sure to add these two in the child view controller:
- (UIInterfaceOrientationMask) supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation);
}

A:  - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationMaskLandscape);
}

-(BOOL)shouldAutorotate
{
    return YES;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return (UIInterfaceOrientationMaskLandscape);
}

Try this...

A: you must add the methods below , in your self.window.rootViewController 'class:
-(BOOL)shouldAutorotate
{
    return [[self.viewControllers lastObject] shouldAutorotate];
}

-(NSUInteger)supportedInterfaceOrientations
{
    return [[self.viewControllers lastObject] supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation];
}

@end

if your rootViewController is [UINavigationController class], command+n add a category of UINavigationController ,like my code below
@implementation UINavigationController (Rotation_For_iOS6)

-(BOOL)shouldAutorotate
{
    return [[self.viewControllers lastObject] shouldAutorotate];
}

-(NSUInteger)supportedInterfaceOrientations
{
    return [[self.viewControllers lastObject] supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation];
}

@end

and then ,go to the viewController.m which u want to be landscape or portrait mode,maybe for u is your VideoController !!!!!!
add methods below:
#pragma mark
#pragma mark ----- Orientation Control For iOS 6/7 -----

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight||toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

now i set my vc supported for landscape mode, last but not least,make sure your project deployment info select the orientation your want.


text:
Q: Return a 1 for the first occurrence of each value in a column in Power Query, returning a 0 otherwise I have a list of data in which I want to return a 1 in a different column when each value appears for the first time. I can do this in an Excel table with a formula '=(COUNTIF($A$2:$A2,$A2)=1)+0', but I can't figure out how to do this in Power Query. An example can be seen here:

User ID
First instance?

123
1

123
0

123
0

234
1

345
1

345
0

456
1

567
1

567
0

567
0

567
0

In my table, the User IDs obviously aren't in number order, but this example should show what I'm aiming to do.
I have all of the table data in Power Query, and this is the last thing I can't figure out how to do. I am new to Power Query, and have searched around for a solution, but I haven't been able to find one so any help would be much appreciated. The data isn't as simple as the table. There are lots more columns with different data, but this is the column I am looking at. Thanks!

A: Right, one idea could be to use an index-column on your presumably sorted User-ID's column:

M-code:
let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"User ID", Int64.Type}}),
    Sorted = Table.AddIndexColumn(#"Changed Type", "Index", 0, 1, Int64.Type),
    #"Added Custom" = Table.AddColumn(Sorted, "First_Instance", each if [Index]>0 then if Sorted{[Index] - 1}[User ID] = [User ID] then 0 else 1 else 1),
    #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index"})
in
    #"Removed Columns"

A: One way in powerquery is a shifted column which is much faster than an index for large data sets
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
// create shifted column
    shiftedList = {null} & List.RemoveLastN(Source[User ID],1),
    custom1 = Table.ToColumns(Source) & {shiftedList},
    custom2 = Table.FromColumns(custom1,Table.ColumnNames(Source) & {"Next Row"}),
#"Added Custom" = Table.AddColumn(custom2, "First Instance?", each if [User ID]=[Next Row] then 0 else 1),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Next Row"})
in #"Removed Columns"

Or you can use a grouping
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Grouped Rows" = Table.Group(Source, {"User ID"}, {{"data", each Table.RemoveColumns(Table.AddColumn(Table.AddIndexColumn(_, "Index", 0, 1, Int64.Type), "First Instance?", each if [Index]=0 then 1 else 0),{"Index"}), type table }}),
#"Expanded data" = Table.ExpandTableColumn(#"Grouped Rows", "data", {"First Instance?"}, {"First Instance?"})
in  #"Expanded data"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write a multiline text in a static text control in mfc? I have a simple problem with my static text control. I want to write two sentences in two lines.
I searched everywhere, they answered that its style should not be simple and it should be big enough and then it can be done with \n or \r\n. Another guy wrote that it worked!
I did that, but it's not working! The caption is "Welcome to Genetic Algorithm Simulator Application.\nPlease Choose a Function:"
but it just ignores \n and shows this:
Welcome to Genetic Algorithm Simulator Application.Please Choose a Function:"

A: Also keep in mind that if the "Center Image" style (SS_CENTERIMAGE) is applied (giving you vertical centering of the text), then "\r\n" character sequences are ignored.

A: You should not set SS_SIMPLE style for static control. This is what is causing control to display only single line ignoring new line character. Get rid of this style and it will work.

A: I tried it with MFC in VS2008, in the static text control properties set the property "No Wrap" to False and the text should be automatically wrapped to the size of the control.

A: center image/no wrap/simple all these three options should set to be false!

A: Just apply the style SS_EDITCONTROL.


text:
Q: Show that for every uncountable $A \subseteq \omega_1$, the set $\{\alpha \in Lim(\omega_1): A_\alpha \subseteq A\}$ is stationary in $\omega_1$ Let Lim$(\omega_1)$ denote the set of limit ordinals in $\omega_1$. Suppose $A_\alpha$ is a sequence where $\alpha \in$ Lim$(\omega_1)$ that satisfies the following.
i) For every $\alpha \in$ Lim$(\omega_1),A_\alpha$ is an unbounded subset of $\alpha$ of order type $\omega$.
ii) For every uncountable $A \subseteq \omega_1$, there exists $\alpha \in$ Lim$(\omega_1)$ such that $A_\alpha \subseteq A$.
Show that for every uncountable $A \subseteq \omega_1$, the set $\{\alpha \in Lim(\omega_1): A_\alpha \subseteq A\}$ is stationary in $\omega_1$.
I dont know how to start with this problem. Help very much appreciated.

A: First I copy the statement of the problem, fixing some notation as well.
Let $L=\mathrm{Lim}(\omega_1)$ denote the set of all limit ordinals in $\omega_1$. Suppose $\{A_\alpha:\alpha\in L\}$ is a (transfinite) sequence of subsets of $\omega_1$ that satisfies the following.
(i) $A_\alpha$ is an unbounded subset of $\alpha$ of order type $\omega$, for each $\alpha\in L$.
(ii) For every uncountable $A\subseteq\omega_1$, there exists $\alpha\in L$ such that $A_\alpha \subseteq A$.
Fix any uncountable $U \subseteq \omega_1$, and let $S=\{\alpha \in L:
A_\alpha \subseteq U\}$. We need to show that $S$ is stationary in $\omega_1$.
Fix any club (closed unbounded set) $C$. We need to show $\emptyset\neq S\cap C$.
The main idea is to apply (ii) repeatedly to suitable tails of $U$ (going with bigger and bigger ordinals) so that we build an uncountable $B\subseteq U$ such that $B$ interleaves with $C$, so that in the end if $A_{\alpha(B)}\subseteq B$ with $\alpha(B)\in L$ we would have
$\alpha(B)\in S$ (since $B\subseteq U$), and $\alpha(B)=\sup(A_{\alpha(B)})\in C$, since $A_{\alpha(B)}$ interleaves with $C$.
(One may use this as a hint, before reading the details below. I ended up writing a version 2 of my answer, both versions enclosed, below, essentially the same, version 2 may be shorter and slightly more general.)
Version 1.
Pick any $\alpha_0\in S$ and any $\gamma_0\in C$ with $\gamma_0>\alpha_0$. For any $\beta<\omega_1$ let $U_\beta=U\cap(\beta,\omega_1)$, clearly each $U_\beta$ is uncountable. Using (ii), there is $\alpha_1\in L$ such that $A_{\alpha_1}\subseteq U_{\gamma_0}$. Clearly $\alpha_1\in S$ (since $U_{\gamma_0}\subseteq U$), and $\gamma_0<\alpha_1$ (since $\gamma_0+1=\min(U_{\gamma_0})\le\min(A_{\alpha_1})<\alpha_1$, where $\min(P)$ in general denotes the smallest element of any given non-empty set $P$ of countable ordinals).
Recursively define $\alpha_\beta$ and $\gamma_\beta$ for each $\beta<\omega_1$ as follows.
(1) if $\alpha_\beta$ is defined, pick any $\gamma_\beta\in C$ with $\gamma_\beta>\alpha_\beta$,
(2) (continuing (1)), then, using (ii), there is $\alpha_{\beta+1}\in L$
such that $A_{\alpha_{\beta+1}}\subseteq U_{\gamma_\beta}$,
(3) if $\delta$ is limit and $\alpha_\beta$ were defined for all $\beta<\delta$ then
using (ii), there is there is $\alpha_\delta\in L$
such that $A_{\alpha_\delta}\subseteq U_{\sup\{\beta<\delta:\gamma_\beta\}}$. (Following (1), also pick $\gamma_\delta\in C$ with $\gamma_\delta>\alpha_\delta$.)
Note that by construction we have $\alpha_\beta\in S$ for each $\beta$, and $\alpha_{\beta+1}>\gamma_\beta$. Moreover, if $\mu_\beta=\min(A_{\alpha_\beta})$ then
$\mu_{\beta+1}>\gamma_\beta$, for each $\beta<\omega_1$. If $\delta$ is limit then
$\mu_\delta>\gamma_\beta$ for all $\beta<\delta$.
Let $B=\{\mu_\beta:\beta<\omega_1\}$. Clearly $B$ is uncountable and $B\subseteq U$
(since $\mu_\beta=\min(A_{\alpha_\beta})\in A_{\alpha_\beta}\subseteq U$).
By (ii), there is $\alpha(B)\in  L$ such that $A_{\alpha(B)}\subseteq B$. Then
$\alpha(B)\in S$ (using that $B\subseteq U$), and we need to show that also $\alpha(B)\in C$. Each element of $A_{\alpha(B)}$ is of the form $\mu_\beta$, for some $\beta$. Hence there is an increasing sequence $\{\beta_n:n<\omega\}$ such that $A_{\alpha(B)}=\{\mu_{\beta_n}:n<\omega\}$. Then $\alpha(B)=\sup(A_{\alpha(B)})=\sup_{n<\omega}\mu_{\beta_n}=\sup_{n<\omega}\gamma_{\beta_n}$, where the last equality holds since $\mu_{\beta_n}<\alpha_{\beta_n}<\gamma_{\beta_n}<\mu_{({\beta_n+1})}\le\mu_{\beta_{n+1}}$. Since $C$ is closed we have $\alpha(B)=\sup_{n<\omega}\gamma_{\beta_n}\in C$, which completes the proof.
It doesn't look like that the condition that "the order-type of each $A_\alpha$ is $\omega\ $"  is essential (as long as $\sup(A_\alpha)=\alpha$). Indeed, instead of $A_{\alpha(B)}=\{\mu_{\beta_n}:n<\omega\}$ we could just take increasing $\{\mu_{\beta_n}:n<\omega\}\subseteq A_{\alpha(B)}$ with $\sup(\{\mu_{\beta_n}:n<\omega\})=\sup(A_{\alpha(B)})=\alpha(B)$.
Version 2.
This version is proved using a formally weaker condition in place of (i), namely:
(i') $A_\alpha$ is a non-empty unbounded subset of $\alpha$ , i.e. $\sup(A_\alpha)=\alpha$, for each $\alpha \in L$. (The difference with condition (i) is that we allow $A_\alpha$ to have the order-type of any countable limit ordinal, not necessarily $\omega$. Condition (ii) remains unchanged.)
Lemma. The set $S=\{\alpha \in L: A_\alpha \subseteq U\}$ is unbounded (for any given uncountable $U\subseteq\omega_1$). Moreover, given any $\beta<\omega_1$ there is $\alpha\in S$ such that $\beta<\min(A_\alpha)<\alpha$.
Proof. Observe that $U_\beta:=U\cap(\beta,\omega_1)$ is uncountable, and by (ii)
there is $\alpha \in L$ with $A_\alpha\subseteq U_\beta\subseteq U$ (and hence $\alpha \in S$). Then
$\beta<\beta+1\le\min(A_\alpha)<\alpha$.
Using the lemma, we may construct by recursion transfinite sequences
$\{\alpha_\beta:\beta<\omega_1\}$ and $\{\gamma_\beta:\beta<\omega_1\}$,
and let $\mu_\beta=\min(A_{\alpha_\beta})$ such that:
(1') $\mu_\beta=\min(A_{\alpha_\beta})<\alpha_\beta=\sup(A_{\alpha_\beta})\le\gamma_\beta<\mu_{\beta+1}$ and $\alpha_\beta\in S$ (i.e $A_{\alpha_\beta}\subseteq U$),
and $\gamma_\beta\in C$, for each $\beta$ (where $C$ is a club we have fixed, and
need to prove $S\cap C\neq\emptyset$),
(2') if $\delta\in L$ then $\sup_{\beta<\delta}\gamma_\beta<\mu_\delta=\min(A_{\alpha_\delta})<\alpha_\delta=\sup(A_{\alpha_\delta})\le\gamma_\delta<\mu_{\delta+1}$ and $\alpha_\delta\in S$ and $\gamma_\delta\in C$.
Let $B=\{\mu_\beta:\beta<\omega_1\}$. Clearly $B$ is uncountable and $B\subseteq U$ (since $\mu_\beta=\min(A_{\alpha_\beta})\in A_{\alpha_\beta}\subseteq U$).
By (ii), there is $\alpha(B)\in  L$ such that $A_{\alpha(B)}\subseteq B$.
Since $B\subseteq U$ we have $A_{\alpha(B)}\subseteq U$, hence $\alpha(B)\in S$.
It remains to show that $\alpha(B)\in C$.
Since $A_{\alpha(B)}\subseteq B$ we have that each element of $A_{\alpha(B)}$ is of the form $\mu_\beta$, for some $\beta<\omega_1$. Since the order type of
$A_{\alpha(B)}$ is a countable limit ordinal, there is an increasing sequence $\{\beta_n:n<\omega\}$ such that $\{\mu_{\beta_n}:n<\omega\}\subseteq A_{\alpha(B)}$
and $\sup\{\mu_{\beta_n}:n<\omega\}=\alpha(B)$.
Then $\alpha(B)=\sup_{n<\omega}\mu_{\beta_n}\le$ $\sup_{n<\omega}\alpha_{\beta_n}\le$
$\sup_{n<\omega}\gamma_{\beta_n}\le$
$\sup_{n<\omega}\mu_{(\beta_n+1)}\le$
$\sup_{n<\omega}\mu_{\beta_{n+1}}=\alpha(B)$.
It follows that $\alpha(B)=\sup_{n<\omega}\gamma_{\beta_n}\in C$ (using that
$\gamma_{\beta_n}\in C$ for each $\beta$, and $C$ is closed).
Hence $\alpha(B)\in S\cap C\neq\emptyset$, which completes the proof.


text:
Q: Как собрать проект используя nmake? Пытаюсь написать скрипт на языке Python автоматизированной сборки dll с помощью nmake.
p = subprocess.Popen('%comspec% /k "C:/"Program Files (x86)"/"Microsoft Visual Studio 14.0"/VC/vcvarsall.bat" amd64',
                shell=True, stdin=subprocess.PIPE, universal_newlines=True,
                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate(input="nmake -f win32/Makefile.msc")

С Makefile проблем нет, при запуске данного скрипта сборки не происходит


text:
Q: Change font size for a TextView widget in a running Gtk3 Perl app I'm trying to modify the font size, in a TextView widget, in a running Perl application and I'm having a difficult time of it. Here's one of my attempts(the relevant code is in the function setFontSize).
#! /usr/bin/env perl

use feature qw(state);
use local::lib;

use warnings;
use strict;
use utf8;

use constant MAX_FONT_SIZE => 200;
use constant MIN_FONT_SIZE => 12;
use constant FONT_UNIT => 4;

use Glib qw(TRUE FALSE);
use Gtk3 qw(init);
use Pango;

sub killKey {
    my ($object, $event) = @_;
    my $c = lc chr ($event->keyval);
    Gtk3->main_quit if $c eq 'q';
    FALSE;
}

sub setFontSize {
    my ($tView, $font_size) = @_;
    my $pCont = $tView->get_pango_context();
    my $fDescr = $pCont->get_font_description();
    $fDescr->set_absolute_size($font_size * Pango::SCALE);
    my $buf = $tView->get_buffer();
    my $end = $buf->get_end_iter();
    my $start = $buf->get_start_iter();
    my $str = $buf->get_text($start, $end, TRUE);
    my $newBuf = Gtk3::TextBuffer->new();
    $newBuf->set_text($str);
    #$buf->set_text($buf->get_text($start, $end, TRUE), -1);
    $tView->set_buffer($newBuf);
    STDOUT->print("called: ", $fDescr->to_string(),"\n");
#   {
#       no strict "refs";
#
#       for my $elem (sort keys %{ref($fDescr)."::"}) {
#           STDOUT->print("${elem}\n");
#       }
#   }
}

sub catchScroll {
    my ($object, $event, $tView) = @_;

    state $font_size = 40;

    my $dir = $event->direction;
    my ($ctrl, $mod) = @{$event->state};
    if ($ctrl eq q<control-mask> && $mod eq q<mod2-mask>) {
        if ($dir eq q<up>) {
            $font_size += FONT_UNIT if $font_size < MAX_FONT_SIZE;
            setFontSize($tView, $font_size);
            return FALSE;
        }elsif ($dir eq q<down>) {
            $font_size -= FONT_UNIT if $font_size > MIN_FONT_SIZE;
            setFontSize($tView, $font_size);
            return FALSE;
        }
    }
    FALSE;
}

my $window = Gtk3::Window->new(q<toplevel>);
my $scrWin = Gtk3::ScrolledWindow->new();
my $tView = Gtk3::TextView->new();
my $provider = Gtk3::CssProvider->new();

$provider->load_from_path("the.css");
my $style = $tView->get_style_context();
$style->add_provider($provider, 600);

my $str = qx(perldoc -T -t -f split 2>&1);

my $buf = $tView->get_buffer();
$buf->set_text($str);
my $sIter = $buf->get_start_iter();
$buf->place_cursor($sIter);
#$tView->set_editable(FALSE);

$window->add_events(q<GDK_KEY_PRESS_MASK>);
$window->add_events(q<GDK_SCROLL_MASK>);

$window->signal_connect(delete_event => sub{Gtk3->main_quit; FALSE});
$window->signal_connect(key_press_event => \&killKey);
$window->signal_connect(scroll_event => \&catchScroll, $tView);

$window->set_border_width(0);
$window->fullscreen();
$window->set_decorated(FALSE);

$scrWin->add($tView);
$window->add($scrWin);

$window->show_all;

Gtk3->main;

I can hack the font values from the provider and it works perfectly... Kind of makes you wonder why the Gtk3 folks don't have that functionality available for these types of problems.
the.css
text {
    background-color: rgb(0,0,0);
    color: rgb(0, 255, 0);
}

textview {
    font-size: 40px;
}

The final version: I added CSS::Tiny to handle the css in provider and added functionality to freeze the vertical scroll bar while I modify the font size with Ctrl+mouse wheel.
#! /usr/bin/env perl

use feature qw(state);
use warnings;
use strict;
use utf8;

use constant MAX_FONT_SIZE => 200;
use constant MIN_FONT_SIZE => 20;
use constant FONT_UNIT => 4;
use constant FONT_START_SIZE => 40;

use CSS::Tiny;

use Glib qw(TRUE FALSE);
use Gtk3 qw(init);

sub killKey {
    my ($object, $event) = @_;
    my $c = lc chr ($event->keyval);
    Gtk3->main_quit if $c eq 'q';
}

sub changeFontSize {
    my ($style, $provider, $font_size) = @_;
    my $cssStr = $provider->to_string();
    my $css = CSS::Tiny->new();
    $css = CSS::Tiny->read_string($cssStr);
    $css->{textview}->{q<font-size>} = "${font_size}px";

    $style->remove_provider($provider);
    $provider = Gtk3::CssProvider->new();
    $provider->load_from_data($css->write_string());
    $style->add_provider($provider, 600);
}

sub catchScroll {
    my ($object, $event, $data) = @_;
    my ($style, $provider, $vadj) = @{$data};
    my ($ctrl, $mod) = @{$event->state};
    my $dir = $event->direction;

    my $retval = Gtk3::get_current_event();

    state $font_size = FONT_START_SIZE;

    if ($ctrl eq q<control-mask> && $mod eq q<mod2-mask>) {
        if ($dir eq q<up>) {
            $font_size += FONT_UNIT if $font_size < MAX_FONT_SIZE;
            changeFontSize($style, $provider, $font_size);
        }elsif ($dir eq q<down>) {
            $font_size -= FONT_UNIT if $font_size > MIN_FONT_SIZE;
            changeFontSize($style, $provider, $font_size);
        }else {
        }
        $vadj->set_value(0.0);
    }
    FALSE;
}

my $window = Gtk3::Window->new(q<toplevel>);
my $scrWin = Gtk3::ScrolledWindow->new();
my $tView = Gtk3::TextView->new();
my $provider = Gtk3::CssProvider->new();

$provider->load_from_path(q<the.css>);
my $style = $tView->get_style_context();
$style->add_provider($provider, 600);

my $str = qx(perldoc -T -t -f split 2>&1);

my $buf = $tView->get_buffer();
$buf->set_text($str);
my $sIter = $buf->get_start_iter();
$buf->place_cursor($sIter);
$tView->set_editable(FALSE);

$window->add_events(q<GDK_KEY_PRESS_MASK>);
$window->add_events(q<GDK_SCROLL_MASK>);

$window->signal_connect(delete_event => sub{Gtk3->main_quit; FALSE});
$window->signal_connect(key_press_event => \&killKey);
$window->signal_connect(
    scroll_event =>
        \&catchScroll,
        [$style, $provider, $scrWin->get_vadjustment()]
);

$window->set_border_width(0);
$window->set_position(q<center>);
$window->fullscreen();
$window->set_decorated(FALSE);

$scrWin->add($tView);
$window->add($scrWin);
$window->show_all();

Gtk3->main;

the.css
text {
    background-color: rgb(0, 0, 0);
    color: rgb(0, 255, 0);
}

textview {
    font-size: 40px;
}

A: Currently I am not able to make the Pango font description to work either. Seems like it is difficult to find a good documentation of how this is supposed to work :)
Anyway, as a workaround, a CSS provider can be used:
sub setFontSize {
    my ($tView, $font_size) = @_;

    state $provider;

    my $context = $tView->get_style_context();
    if ( $provider ) {
         $context->remove_provider( $provider );
    }
    $provider = Gtk3::CssProvider->new();
    my $css = sprintf "textview {font-size: %spx;}", $font_size;
    $provider->load_from_data($css);
    $context->add_provider($provider, Gtk3::STYLE_PROVIDER_PRIORITY_APPLICATION);
}


text:
Q: Is there a Criteria equivalent to using HQL array subscript? I need to retrieve entities that have specific values at specific positions in an associated list.
I can achieve this using HQL as follows:
from Cat c
where c.kittens[0].name = 'whiskers'
and c.kittens[1].name = 'mittens'

I now want to add this restriction to an existing search which uses the criteria API. I don't see anything similar to the array subscript notation in that API. What is the equivalent using criteria?


text:
Q: Calling between viewmodels (KnockOutJS) I'm using KnockoutJS to develop a plugin based on viewmodels. Is there any way to access the functions and properties of another viewmodel running in the same application? Something like this:
My view model:
    function myViewModel()
    {
        this.prop1 = ko.observable(123);
        this.prop2 = ko.observable("Hello");
        ..
        ..
    }

    myViewModel.prototype.func1 = function() {
        //do something...
    };

    myViewModel.prototype.func2 = function() {
        //do something...
    };

And the other view model:
    function otherViewModel()
    {
        this.propA = ko.observable(456);
        this.propB = ko.observable("Goodbye");
        ..
        ..
    }

    otherViewModel.prototype.funcA = function() {
        //do something...
    };

    otherViewModel.prototype.funcB = function() {
        //do something...
    };

The observables of the otherViewModel control certain common functions like pop-ups and masks. Is there any way to instantiate otherViewModel in myViewModel and set those properties?
Or is there any way to globally get and set them?
Please tread lightly as I'm very new to this paradigm. Thank you.

A: I agree with the comment to use scopes - but there are a couple of quick and dirty ways...
when you instantiate myViewModel - you could instantiate it on the window - and then reference it directly
window.myViewInstance = new myViewModel()

function myOtherViewModel () {
  this.propA = myViewInstance.xyz
}

I use this method when I have something that provides global functionality that I want to use elsewhere.  Its what jQuery and ko do... bind $ and ko to the window.
if myViewModel.xyz = ko.observable() then passing it without parens passes it as an observable - which will change as its value changes.  With the parens will pass the result at the time it is evaluated.
Alternatively - you can reference it using ko.dataFor like this.
myViewModel () {...}
instance = new myViewModel
ko.applyBindings(instance, $('div')[0])
// this applies bindings of myViewModel to the first div on the page only

myOtherViewModel () {

  this.propA = ko.dataFor($('div')[0])
  // passes the entire object
  this.propB = ko.dataFor($('div')[0]).xyz
  // gives you just one property

}

Which would scope your object to just a part of the page


text:
Q: Where to install GlassFish on Linux? DISCLAIMER: I'm relatively new to Linux. I debated putting this on SuperUser or ServerFault because the answer does require an explanation of Linux as a system (and not a specific programming problem), however I'm interested in this from a Java developer's perspective, and I argue that this is a specific problem because where I install GlassFish greatly impacts my Java configuration, and ultimately, app configuration. Not to mention posting this question on those other sites probably won't garnish any attention from a Java developer, more over system admins, who may not know enough about Java to weigh-in fully on this decision.
I'm trying to decide where to install GlassFish and it seems to me I have (realistically) 4 viable options:

*

*/opt/glassfish/

*/usr/local/glassfish/

*/home/myUsers/glassfish/ (which is what all the OGS docs show in their examples)

*/home/ogs/glassfish (as its own user, similar to how Apache web server is sometimes setup)

I'm wondering what the pros (taking into consideration the nature of how Linux treats these directories differently, the FHS, etc.) and cons of each approach are.
I've read that there are mounting/paritioning benefits to installing it under opt/. However, I normally install 3rd party software to usr/local/, so I'm a little unsure about that as a strategy.
The Oracle GlassFish Server (OGS) docs all demonstrate (but never outright recommend) GlassFish being installed under your home directory (home/myUser/).
Then again, I've read that it is fairly common to install daemon-type services (which is what I would imagine I would be using GlassFish as - where I start it once and it only comes down for routine maintenance or crashes) as their own user (home/ogs/glassfish/).
I'm sure this decision is also impacted by how I'm going to use GlassFish, so let me qualify this question with a few constraints:

*

*I intend to deploy 4 OGS instances across 4 VMs on the same physical machine and cluster them into the same domain (1 of the 4 server instances will be the admin server for the domain)

*Several applications will be deployed to this cluster (all 3 non-admin nodes) at the same time, and should be running 24/7/365 except for when they crash (hopefully not often!) or when I need to maintenance or tune them

*Each application will be farily large and I would like to configure them with real admin, not "bare bones" de minimis, default settings

If these don't provide specific-enough information to help make this choice, please ask and I can be more specific.
I guess, when the dust settles at the end of the day, I'm looking (more or less) for a matrix with each of the four directory options (plus any other obvious ones I've omitted) compared against their respective pros & cons.

A: There's also the option of using your Linux distro's package management system to install Glassfish. On Ubuntu for example, you could install it using
sudo apt-get install glassfish-appserv

and let it get installed to wherever the package owner thought it should be installed.
I myself tend to steer away from the above option, as I like to exert my own control over which exact version of Glassfish (or any other Java server/software) is installed and where, but I just wanted to throw that out there, as it's one of the things you could do.
Now for the individual options you've provided:
/opt/glassfish/
This is the preferred option as far as I'm concerned. It keeps the software on a separate directory outside of the regular Linux installation, and allows the mounting and partitioning benefits you mention.
/usr/local/glassfish/
I don't like this much, because /usr/local is generally used by third-party software that is installed using the distro's package management software (apt/yum/etc), and on most distros has directories like bin, etc and lib under it. Putting a directory for glassfish under it, would make it out of place.
Also I prefer to keep system directories separate from custom software that doesn't use the distro's package management tools.
/home/myUsers/glassfish/ , /home/ogs/glassfish
These 2, I would not recommend.
They are only described in most places, because the author doesn't want to assume that the user has root access on those boxes, in which case the home directory would be the only one you'd be guaranteed to own. If you own the system and are managing it, those restrictions don't apply.
Remember, home directories are for specific users. I always recommend server software being managed with individual users' accounts that have the required privileges. Putting software in someone's home directory would mean that you either

*

*Give everyone who needs to manage Glassfish, the password to that user account

*Give multiple users read/write access to the home directory of a specific user.

Either way, that's not good system administration policy.
There's not much of a Java perspective here, but if you ask me, there doesn't need to be.

A: Regarding the prior recommendation, some tradeoffs remain:

*

*If placed in /opt or /usr/local, you will have to have read/write access to those directories, meaning that you will have to have root access to the box.  In some environments (where IT controls the platform), IT will not let you have root access. You would have to delegate to IT the responsibility of installing, patching, and upgrading the GlassFish binaries.

*If placed in /opt or /usr/local, then you will also have to place the domain directories (--domaindir) in a separate location unless you want them owned by root (unlikely).  This was the default in GlassFish 2.x RPM installs on Linux.  GlassFish 3.x does not have RPM installs (from Oracle, anyway), but you can still split the two. This isn't a bad tradeoff, but something you should understand.

*

*If placed in a "home directory", then you have rights to upgrade the core binaries, install patches, etc, separate from IT. There is good/bad/ugly in this approach depending on organizational responsibilities.

Hope this helps.


text:
Q: Changing the text size is not working I am an eighth grader that needs some help.  I am a noob at anything TeX or LaTeX, and am just starting out.  I am using USBTeX, just in case that matters.
I cannot seem to change the text size in the \documentclass[]{} thingy in the beginning of the document.  My TeX editor sets it to 10pt at default, but when I try to change it to something different, nothing happens.  Any ideas?

A: The only sizes supported by the document class option in the standard classes are 10pt 11pt and 12pt. To get text at other sizes you can use commands such as \large or \tiny within the document. Normally though you should not be using font size commands within a document. Heading commands such as \section and other structural markup should be defined by the class to use an appropriate size. One of the aims of LaTeX is that you should as far as possible be using structural markup such as \section and \subsection and not using explicit font and size changes, which make it a lot harder to reformat your document for different purposes.

A: You may already have a document class with the ext prefix on it (such as extarticle instead of article as the document class.  Give it a try, it works for the font sizes 8pt, 9pt, 10pt, 11pt, 12pt, 14pt, 17pt, and 20pt.
These document classes are available from the extsizes package, included in the Ubuntu package texlive-latex-recommended.


text:
Q: How to compile Intel VNNI instructions with GCC or llvm? Intel has announced its new AVX512 extension instructions. I am working on the simulation of its VNNI instructions. I am referring to this manual https://software.intel.com/en-us/isa-extensions. I searched on google whether gcc or llvm has supported the VNNI instructions. I only found news that they are working on it. If anyone knows how to compile VNNI instructions(like instructions VPDPBUSD and VPDPWSSD) please share with me. Thanks alot!

A: The following flags allow the generation of AVX512-VNNI instructions
>= gcc 8.1, >= clang 7.0.0

*

*-march=icelake-client

*-march=icelake-server
>= gcc 9.1, >= clang 8.0.0

*

*-march=cascadelake
Tested with the Compiler Explorer: https://godbolt.org/z/Pkci0J
Code sample downloaded from the following link: https://software.intel.com/en-us/articles/intel-advanced-vector-extensions-512-intel-avx-512-new-vector-neural-network-instruction


text:
Q: SQL Query to return result with and without whitespace I have a column in my Postgres database table which contains a value with some whitespaces in between. For example, a value present in the column is '123 1062 10'.
Now, I want to write an SQL query which can return the row which contains the above-mentioned value by passing in the value '123106210' in the where clause of SQL Query.
Any ideas of how can write to the SQL Query to get the desired result?

A: replace function does not work for you?
This works
select replace('123 1062 10',' ','')::bigint

so this could be your final select:
select ...
from ...
where replace(your_text_column,' ','')::bigint = 123106210


text:
Q: example, holomorphic function on unit disc with radial limits everywhere zero I tried to look for examples of a non zero holomorphic function $f : \mathbb{D} \to \mathbb{C} $  such that, $\forall\xi \in \partial \mathbb{D}$ $$\lim_{r\to1^{-}} f (r\xi)=0, $$
So, could anyone demonstrate examples of such functions.
Moreover, what properties should, such a function have? In other worlds are there any sufficient and/ or necessary conditions?
Finally, the topic of boundary behavior of holomorphic functions is seems really chaotic. Is there are any reference with examples of the various behaviors holomorphic functions exhibit in their boundary?

edit
I added a image of the notes I am reading witch triggered the question.
So the writer implies that such a function exists.. unless I miss something..


text:
Q: impossible to reach the "angular 4" option when "create new solution" in wakanda 2 on mac OS I just installed "wakanda v 2" on my macbook...I try then the main tuto
https://wakanda.github.io/doc/#/tutorial?section=main...I don't receive "angular 4" in the different propositions when I "create a new solution"...I just can reach "angular" or "angular 1"...It's thus impossible for me to follow the rest of this tutorial.

A: As the angular team announced earlier, "Angular 4" will be referred as "Angular" version 4.0.0. So you will see "Angular" instead "Angular 4" or "Angular 2" in documentations and products that use Angular.
The Angular in Wakanda Studio drop-down shown in your screenshot is indeed referring to Angular 4.
You can find the version number of your Angular framework in the app root of any built angular page:


text:
Q: Need help understanding matrix representation of a linear operator I'm struggling with linear algebra. Specifically, understanding the following:
$\newcommand{\ket}[1]{|#1\rangle}$
Suppose $A:V \rightarrow W$ is a linear operator between vector spaces $V$ and $W$. Suppose $\ket{v_1},\ldots,\ket{v_m}$ is a basis for $V$ and $\ket{w_1}, \ldots, \ket{w_n}$ is a basis for $W$. Then for each $j$ in the range $1,\ldots,m$, there exist complex numbers $A_{1j}$ through $A_{nj}$ such that
$$ A\ket{v_j} = \sum_i A_{ij} \ket{w_i}. $$
I understand that $A \ket{v_j}$ is a vector in $W$. I also understand that we can write any vector in $W$ as a linear combination of the basis vectors
$\ket{w_1}, \ldots, \ket{w_n}$. I don't understand how that corresponds to the matrix form of $A$ and am overall lacking intuition for what's going on here.
Can someone help give me intuition for what the above means? Also, suggestions on books/videos/lectures/etc are also appreciated.

A: If you let the linear operator  act on a basis of $V$, you should write the matrix behind the basis vectors of $W$:
$$
A{\bf e}_i = {\bf f}_j {A^j}_i.
$$
Suppose that ${\bf y}= A{\bf x}$ where
 ${\bf x}= x^i {\bf e}_i$, and ${\bf y}= y^j {\bf f}_j$.
We have
$$
A{\bf x}= x^i (A{\bf e}_i)= x^i({\bf f}_j {A^j}_i)= {\bf f}_j ({A^j}_i x^i)
$$
comparing with ${\bf y}= y^j {\bf f}_j$ gives
$$
y^j= \sum_{i=1}^{{\rm dim\,}V}  {A^j}_i x^i
$$
which is the usual action of a matrix on a column vector where we sum over adjacent indices.
One can think of this as it appears in Quantum Mechanics
$$
A|v_n\rangle = \sum_{m=1}^{{\rm dim} W} |w_m\rangle \langle w_m|A|v_n\rangle,
$$
where the matrix elements naturally appear behind the basis vector $|w_m\rangle$.

A: In quantum mechanics there's a trick we use when we are stuck. It's called completeness, which is basically a change of reference in the form of basis change. There is a powerful property from linear algebra that says: $$\sum_{i}|w_i\rangle\langle w_i|=\mathbb{1}$$ where the $|w_i\rangle$s form a basis. Using this we have $$A|v_j\rangle=\sum_{i} |w_i\rangle\langle w_i|A|v_j\rangle$$ and the number $\langle w_i|A|v_j\rangle$ is just the matrix element $A_{ij}$.


text:
Q: How can I make this map filter shorter & better I think this is not an ideal way of doing filters. I have to type more if else's and it doesn't look good.
I found a package called "useFilter". but can I just make it without using any packages? like with hooks or something.

import { AddPosition } from "./../../data/careers/AddPosition";

const Positions = () => {
  const [positions] = useState(AddPosition);
  const [searchTerm, setSearchTerm] = useState("");

   <input
                type="search"
                placeholder="Search"
                onChange={(e) => setSearchTerm(e.target.value)}
              />

                   {positions
            .filter((position) => {
              if (searchTerm === "") {
                return position;
              } else if (
                position.category
                  .toLowerCase()
                  .includes(searchTerm.toLowerCase())
              ) {
                return position;
              } else if (
                position.type.toLowerCase().includes(searchTerm.toLowerCase())
              ) {
                return position;
              } else if (
                position.location
                  .toLowerCase()
                  .includes(searchTerm.toLowerCase())
              ) {
                return position;
              } else if (
                position.position
                  .toLowerCase()
                  .includes(searchTerm.toLowerCase())
              ) {
                return position;
              }
            })
            .map((position) => (
              <>
                <SinglePosition
                  id={position.id}
                  category={position.category}
                  type={position.type}
                  position={position.position}
                />
              </>
            ))}
        </div>
      </div>
    </div>

A: You can simplify this by using Array.prototype.some and you can also use useMemo to make sure that the filtering happens only when positions/searchTerm changes.
const filteredPositions = useMemo(() => {
      if(!searchTerm) return positions;
      const lowerCasedSearchTerm = searchTerm.toLowerCase();
      return positions.filter(({id, ...other}) => {
          // assuming you want to check every value in position
          return Object.values(other).map(v => v.toLowerCase()).some(v => v.includes(lowerCasedSearchTerm))
      })
  }, [positions, searchTerm])

Now you can map filteredPositions in the JSX.

A: You're logic is repeated for each property of position. Combine them to a single array, and iterate it with Array.some() if any of the includes the term, it would return true:
{positions
  .filter(({ id, ...rest }) => {
    const term = searchTerm.toLowerCase();

    return !term || Object.values(rest).some(str =>
      str.toLowerCase().includes(term)
    );
  })
  .map(position => (
    <SinglePosition key={position.id} {...position} />
  ))
}

Note: when rendering a list of items don't forget to include a key property. In addition, you don't need to wrap a single element in a fragment. You need a fragment only if you render multiple elements without a single parent.


text:
Q: ajax loading content but my div won't expand to fit it I have a page that static data in it will push a div down to make it longer. But when I use ajax loaded content then the div will stay as big it originally was and it looks like my new content will just overlap it...
I have a setup like this

static content

ajax content

#content-fill {border:1px solid #BDBDBD; width:919px;}
#files_left_pane {float:left; border-right:1px solid #BDBDBD; width:100px;}
#files_right_pane {float:right; widht:819px}

the height of the right pane is controlled by the height of the left pane since there is static content in there, mainly my navigation menu.
any advice?

A: Set Your div position as relative

ajax  content

A: as far as I test it when you add content then the div start from the left side. This happens because you didn't set width. for example add width:200px for #files_right_pane and check the results.
live example: http://jsbin.com/udori5

A: Easiest fix is add float:left to content-fill


text:
Q: Windows XP in Hyper-V (Host Win 10) No Mouse I created a new Windows XP VM in Hyper-V running on a Windows 10 host. I'm getting the "Mouse input not captured" message. I don't have "Insert Integration Services Disk" in the Action menu. Under the VM's settings, every option under "Integration Services" is checked. How do I get the mouse to work?

A: Windows XP is not supported in Windows 10 Hyper-V.  See:
https://social.technet.microsoft.com/Forums/azure/en-US/0184afd8-ac12-4d49-b4b9-d2411019817c/will-windows-xp-run-on-hyperv-with-10-pro?forum=win10itprovirt
The second post down says you can make it work even though not supported.
VMware Workstation supports XP and mouse / keyboard. I have it here and that is an alternative for you to try.


text:
Q: DIV scroll bar , not scrolling content I have a div with it's CSS style property set to overflow:scroll. This does show a vertical and horizontal scrollbar when the content is large. Now when I click on the scroll bar it is not actually scrolling the div content. Anything wrong , please advise.

A: There are chances that there is another transparent element of the page which covers the scroll bar, so when you click on the scroll bar, the browser behaves as if you clicked on the transparent element.
To see if the problem comes from here, in Firefox, open Firebug and click on the blue arrow "Click an element in the page to inspect", then click on the scroll bar.
Now, if the scroll bar is not covered by anything, JavaScript is maybe blocking some events (even if I'm not sure it can block a thing like this). To test it, disable JavaScript on the page and see if it helps.
Finally, test the page in other browsers. If you are using a fancy browser, it may just be a bug in it.

A: Try to set the css as:
overflow: auto;

A: I tried with a simple HTML page and it does do the scroll.
I suspect some issue with this page.
Another clue is that this DIV is encapsulated within a table element. Could this be an issue, if so how come I over come the same.


text:
Q: OWLOntologyStorer exception when creating an Ontology I get this exception:

Exception in thread "main" java.lang.NoSuchMethodError: org.semanticweb.owlapi.model.OWLOntologyManager.addOntologyStorer(Lorg/semanticweb/owlapi/model/OWLOntologyStorer;)V

when I try to create an Ontology using the following line of code:
owlmanager = OWLManager.createOWLOntologyManager();

A: The most likely explanation is that you have multiple OWLAPI versions on your classpath. This looks like OWLAPI 4 and OWLAPI 3 conflicts.


text:
Q: WCF Communication though named pipes with non .net App I hear that WCF is the new standard for communication across the network and applications in .net. The idea seems to make sense as well, provide standard interfaces for programs to communicate.
Here is my situation, I have a .net app i want to communicate to a ruby application though pipes. On the .net side (server) I would like to use WCF while the ruby side (client) will be chewing gum and duct tape.
I assume both ends don't need to be WCF but what will be involved in making this work. Is there a standard protocol WCF expects incoming requests?

A: Using the named pipes binding for non WCF clients could be possible, but it wouldn't be easy.  You'd need to send the messages in the correct format for WCF to consume.
See this first or last entry on WCF message framing for a hint at the complexity.  It's not impossible, but is it worth the effort?
Recommended is the http transport + some type of text or markup encoding, like basicHttpBinding or webHttpBinding.

A: Depends on your bindings, you can make your  WCF a webHttp binding and make it restful (easiest) and you just do gets and posts. Other bindings you will have to use SOAP headers and such to communicate with your WCF, I have not done this myself, but im sure theres info out there on how to do it for non .net applications.

A: You'll want to keep your contract as simple as possible (in terms of what types you expose).  Though I have not tried this myself, I know that this type of functionality is supported (.Net to Java is a common usage) and relatively easy to do.
You don't mention which side (.Net or Ruby) will be the server, but I would expect that this will be much easier to do if you host the service in WCF and consume it from ruby.  Going the other way around may be a bit more of a pain because mucking with the internals of WCF can be a bit of a pain.

A: What sort of "pipes" are you referring to? You cannot use the named pipes bindings with any code that's not .NET.
You'll probably be better off with one of the HTTP bindings, like webHttpBinding or basicHttpBinding.


text:
Q: Folder created in one step of DockerFile is not available in later steps I am trying to dockerize a flask application but before I spin up the server I need to make sure some of the files are available. These files are stored in Google Cloud Storage. A script is written that will fetch the data from GCP and store it in a folder. The final step is to run app.py but the created folder is not present during this step. Can anyone tell me what I am missing?
Here is my DockerFile
FROM python:3.8-slim-buster

WORKDIR /backend

# All python packages needed for this project are put in this file
COPY requirements.txt requirements.txt

RUN pip3 install -r requirements.txt

COPY . .

# This script currently connects to GCP cloud storage
# fetch the required file
# create a folder and store the fetched file in that folder
RUN python3 setup.py

CMD ["python3", "-m", "flask", "run", "--host=0.0.0.0"]


text:
Q: Almost all subgroups of a Lie group are free I am currently reading this paper by Epstein. I need help with understanding the proof. Specifically, I have the following two questions.

*

*Let $w\colon G\to H$ be an analytic mapping between connected Lie groups $G$ and $H$. How do we prove that the preimage of a point is either the whole of $G$ or has Haar measure zero in $G$?
The paper says one should take $G$ to be an open subset of $\mathbb{R}^m$ and use induction on $m$ and Fubini's theorem, but this doesn't really convince me (I cannot fill the details).

*The whole paper seems to assume that $G$ is analytic manifold, whereas the usual assumption is that Lie group is smooth manifold. Does this mean that the result of the paper hold only for real-analytic Lie groups, or this assumption is not actually a restriction and in some way we also have the claim for the classical real Lie groups?

Edit: Actually, regarding (1), I don't see why the usual $t\in\mathbb{R}\mapsto e^{-1/t^2}1_{t>0}\in\mathbb{R}$ is not a counterexample.

A: Try this:
Work in Euclidean space and write $w=(w^1(x_1,...x_n),...w^m(x_1,...,x_n))$.  Write any $w^i$ as a power series in $x_n$ with coefficients as power series in the other variables: $$w^i=\sum_j c_j(x_1,...,x_{n-1})x_n^j$$
Then by Fubini, if $w^i$ vanishes on a set of positive measure, there exists a set of positive measure $A\subset \mathbb{R}^{n-1}$ such that for any $\overline{a} \in A$, the analytic function $\mathbb{R}\rightarrow \mathbb{R}, t \mapsto w^i(\overline{a}, t)$ vanishes on a set of positive measure.  But then this $w^i(\overline{a}, \cdot )$ vanishes identically, so that each coefficient $c_j$ vanishes on $A$.  Then by induction, each $c_j$ is identically zero on $\mathbb{R}^{n-1}$, so that $w^i$ is identically zero.


text:
Q: Asp.net Core SignalR loadbalancer (close connection error) We have a signalR structure that clients only listen to, which is triggered from the Admin Panel. Client's connection can stay connected as long as loadbalancer's (Google Cloud Platform) request timeout. After this time, the browser throws a 1006 close connection error and drops off the connection. How can we increase this time(is it good idea to increase to thousands of seconds?) What's the error we're skipping here?
startup.cs
services.AddSignalR(HubOptions =>
           {
               HubOptions.EnableDetailedErrors = true;
               HubOptions.KeepAliveInterval = TimeSpan.FromSeconds(15);
               HubOptions.ClientTimeoutInterval = TimeSpan.FromMinutes(45);

           }).AddJsonProtocol().AddStackExchangeRedis(Configuration.GetSection("RedisConfiguration:Host").Value, options =>
           {
               options.Configuration.ConfigurationChannel = "dataCache";
               options.Configuration.ChannelPrefix = "BoardApp";
               options.Configuration.AbortOnConnectFail = false;
           });

js.Code
 var connection = new signalR.HubConnectionBuilder()
                    .withUrl("/boardscreenhub", { transport: signalR.HttpTransportType.WebSockets })
                    .withAutomaticReconnect([1500, 1500, 1500, 1500, 1500, 1500, 1500, 1500, 1500, 1500, null])
                    .configureLogging(signalR.LogLevel.Information).build();

                connection.serverTimeoutInMilliseconds = 1800000;
                connection.start();

                connection.on("receiveMessage", function (message) {
                    _this4.setBoardScreenData(message);
                });

A: Do you have session affinity enabled for the backend of your loadbalancer? We have had the same issue, and I believe that if you do not, then the connections will not be stable and so keep-alives will get lost and give you this behavior.


text:
Q: Python subclassed methods with additional arguments Given the following structure where I want a method with a common name for each class, but each derived class needs an additional piece of information in order to form the appropriate result.  Descending the inheritance tree accumulates additional needed arguments, but always needs all parents arguments as well.

class A:
    @classmethod
    def foo(cls, a):
      return a

class B(A):
    @classmethod
    def foo(cls, a, b):
      return '.'.join([super().foo(), b])

class C(B):
    @classmethod
    def foo(cls, a, b, c):
      return '.'.join([super().foo(), c])

>>A.foo('a')
'a'
>>B.foo('a','b')
'a.b'
>>C.foo('a','b','c')
'a.b.c'

Is this a frowned upon structure since the LSP does not hold? Is there a different overall design approach that would allow a common function name to account for additional arguments like this in some way?
In this example I am using class methods, but same question could be asked for normal instance methods as well.
Updated Example:
In my case I have a messaging application with some message classes defined in an inheritance hierarchy.  Each message type has a specific topic address that needs zero or more runtime parameters such as the node or workflow name.  In addition each message has its own set of instance data field attributes.

class BaseMessage:
    sending_process: str

    @classmethod
    def topic(cls):
      return 'message'

class WorkflowMessage(BaseMessage):

    @classmethod
    def topic(cls, node, workflow_name):
      return '.'.join([super().topic(), 'workflow', node, workflow_name])

@dataclass
class WorkerServiceMessage(WorkflowMessage):
    dataA: str
    dataB: str

    @classmethod
    def topic(cls, node, workflow_name, worker_name):
      return '.'.join([super(node, workflow_name).topic(), worker_name])

class Worker:
    def __init__(node, workflow, name):
        self._node = node
        self._workflow = workflow
        self._name = name
        self.messenger = Messenger()
        self.messager.listen(topic=WorkflowMessage.topic(self._node, self._workflow),
                        callback=self._on_msg)

    def _on_msg(self, msg):
        self.messenger.publish(topic=WorkerServiceMessage.topic(self._node, self._workflow, self._name),
                          msg=WorkerServiceMessage(dataA='abc', dataB='123')

worker=Worker('mynode', 'workflowA', 'worker1')
worker.messenger.run()

A: I like @Gloweye's point that overridden methods should be performing the same task. But have you considered not making this behaviour be directly part of the subclass at all?
Since this question was tagged with solid I'll use that set of terms and suggest that you use some dependency inversion: Instead of having the topic be returned from a method, you could pass in either an object with a topic method, which has all the data needed to make the topic as members, or you could pass in a closure that closes over the relevant data which you can call to get the topic as needed. (Note that these two options are nearly functionally identical. This is the "objects are a poor man's closures and vice versa" thing.)
Alternately, if you would like something simpler, and the topic never changes after initial object construction, you might consider just generating it once and making it a simple string constructor parameter.

A: I think you're asking the wrong question about that code. Lets consider the concepts of subclassing. Lets say we have:
class Fruit:
 pass

class Banana(Fruit):
 pass

This is an extremely simple and obvious example of subclassing. It's literally a sub-classification. All banana's are also fruits.
This is traditionally what subclassing is.
Of course, classes have methods. Lets add some:
class Fruit:
 def take_bite(bitesize):
  """Eats part of the fruit."""
  self.size -= bitesize

class Banana(Fruit):
 def take_bite(bitesize):
  """Eats part of the fruit."""
  # banana circumference doesn't change.
  self.length -= bitesize
 pass

We override the method in our subclass. That's simple. However, the method still does the same thing - it lets us eat a bit of the fruit. And for a banana, that works different then for a generic fruit.
And that's the important question you should be asking.
TL:DR;

*

*Is the method performing the same task? Then yes, you should override the method. If it has different arguments, so be it.

*Is the method performing a different task? Then no, pick another name.


text:
Q: Where to put the generate keystore in IBM MobileFirst 7.1 I want to call an external https url from my mobile first java adapter. According to this tutorial, it shows the way on how to generate a keystore from a .crt file and put into the mobilefirst security folder. However, I am using MobileFirst 7.1 and cannot find any security folder. May I know where is the /mfp-server/usr/servers/mfp/resources/security folder in MFP 7.1? Or in other word, where should I put the final keystore for MFP 7.1?

A: By Default MF uses the uses default.keystore that is in the server/conf directory.
What we have done is insert the required certificates into that that keystore then rebuild the war file.
There is a way to change which keystore to use:
https://mobilefirstplatform.ibmcloud.com/blog/2017/01/17/SSL-connection-from-adapters/


text:
Q: How to check if column exists in sqlite in Qt I have an application which uses sqlite database. I updated the application and needed to update my database on application launch.
For this I need to check if some column exists in a table. I am not sure how to do it...
I saw PRAGMA table_info(table-name); will return column names but that result is in a table and I am not sure how to read it in Qt.

A: PRAGMA table_info returns its data like a normal query, i.e., as if there were a query SELECT cid, name, type, notnull, dflt_value, pk FROM ...:
query.exec("PRAGMA table_info(MyLittleTable)");
while (query.next()) {
    print("column name: ", query.value(1));
}


text:
Q: EF5 Entry not updating Im trying to update an entry with EF5 with the following actionresult:
[HttpPost]
    public ActionResult Edit(int id, IEnumerable<HttpPostedFileBase> files)
    {
        if (ModelState.IsValid)
        {
            Reference reference = db.References.Single(x => x.Id == id);
            db.Entry(reference).State = EntityState.Modified;
            db.SaveChanges();
            //Other stuff regarding files/images

            return RedirectToAction("Index");
        }
        return View();
     }

Nothing happens. When I debug it, it goes trough the code as everything was fine. But nothing is updated in the db.
Here's the model if needed:
public class Reference
    {
        public int Id { get; set; }
        public string Headline { get; set; }
        public string Text { get; set; }
        public DateTime Date { get; set; }
        public IEnumerable<HttpPostedFileBase> ImageUploadMain { get; set; }
        public String MainFileName { get; set; }
        public IEnumerable<HttpPostedFileBase> ImageUpload { get; set; }
        public virtual ICollection<Image> Files { get; set; }
        public virtual ICollection<RefProperties> Properties { get; set; }
        public int CategoryId { get; set; }
        public virtual Category Category { get; set; }
}

public class Image
{
    public int Id { get; set; }
    public string FileName { get; set; }
    public virtual Reference Reference { get; set; }
}

public class RefProperties
{
    public int Id { get; set; }
    public string Key { get; set; }
    public string Value { get; set; }
}
public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Reference> References { get; set; }
}

Not only is the related entries not updated, a main property like "Headline" cant be updated either. What am I doing wrong? Create/delete works fine btw.

A: As Gert Arnold says, you're not actually modifying any of the Reference values so nothing will be updated.  By calling db.Entry(reference).State = EntityState.Modified you're just setting the retrieved entity's state to modified in the ChangeTracker.  When you call SaveChanges() it's just going to update the Reference record in the database with the same values that you fetched.
You need to update some of the Reference instance properties to see a change.
[HttpPost]
    public ActionResult Edit(int id, IEnumerable<HttpPostedFileBase> files)
    {
        if (ModelState.IsValid)
        {

            Reference reference = db.References.Single(x => x.Id == id);
            reference.HeaderText = "Changed";
            /* No need to interact with the change tracker as the entity is already tracked and you've made a change */
            // db.Entry(reference).State = EntityState.Modified;

            /* Create/Modify/Update/Delete other entities */

            db.SaveChanges();
            //Other stuff regarding files/images

            return RedirectToAction("Index");
        }
        return View();
     }

A: Heres what I was looking for:
TryUpdateModel(reference, "");

It has a shitload of overloads. This works though


text:
Q: NSMutableArray in Swift: Different behavior on different ios version protocol TestProtocol {

}

struct TestStruct: TestProtocol {

}

let arr = NSMutableArray()
let testStruct = TestStruct()
arr.add(testStruct)
print("\(arr[0] is TestProtocol)")

If I run this code in app on the simulator with IOS version >= 14.0 result is true, but on IOS 13 result is false.
Can someone tell me why there is difference of behavior?


text:
Q: A common sentence structure with "would" I hear the following sentence structure a lot from native speakers:

*

*I would take a different approach.

*I would recommend going to the store in person and talking to the manager.

*I would disagree.

All the above sentences have the phrase "would plus an infinitive without to" in them. The structure resembles that of the future in the past tense. But I doubt that is the case here because I do not see any clear incident in the past to serve as the reference for the future in the past tense.
An alternative explanation I can think of is that all these sentences have an implicit if-clause behind them. For example, one can add "If you asked my opinion" at the beginning of all the examples above. In that sense, we would be dealing with the second conditional, which requires "would + infinitive without to" in the main clause. Is this what is really happening here?
PS. Fun fact: "We would be dealing with" in the above paragraph is another example!

A: These are "conditional" sentences, however the condition has been omitted - either for tactful ambiguity, or because the condition can be inferred from context.  The condition could be express in an "if" clause

I would take a different approach, if I was the person to make this decision.

If you asked me,  I would recommend ...

I would disagree, if you asked me my opinion.

Using a conditional can make the sentence more tactful.  For example by saying "I would disagree" you avoid saying "I disagree" directly. It is often used to make suggestions or inform someone of a fact that you think they don't want to hear.


text:
Q: jQuery change event handler with checkbox I have a checkbox and when it is enabled(checked), I want code to execute. It works but when the box is unchecked, the code still works, I would prefer it not work when the box is unchecked. The following code is within a larger jQuery function that works. I just can't get the code to stop working when I uncheck the box. For reference, the check box allows the user to use arrow keys to adjust a canvas element. I want them to be able to adjust when the box is checekd and not be able to adjust when it is unchecked.
$("#hMove728").click( function(){
   if($(this).is(':checked')){
    alert("checked");

    $(document).keydown(function(key) {
            switch(parseInt(key.which,10)) {
                case 38:
                    context.yB -= 2;
                break;
                    case 39:
                    x += 2;
            break;
            case 40:
                y += 2;
            break;
            case 37:
                x -= 2;
            break;
            default:
            break;
       }
     update();

    })
   }

});

A: Here, check the state of the checkbox inside the event handler:
var moveCheckbox = $("#hMove728");
$( document ).keydown( function( key ) {
  if ( moveCheckbox.is(":checked") ) {
    // ...
  }
});

A: $(function () {
    $('input').on('change', function () {
        if ($(this).prop('checked')) {
            // It is checked
        }
    });
});

A: You have to "unregister" the "keydown" event on your document when you remove the check, or you can make the check inside your keydown function. Like this:
$(document).keydown(function(key) {
    if(!$("#hMove728").is(':checked')) return;
    switch(parseInt(key.which,10)) {
        case 38:
            context.yB -= 2;
        break;
            case 39:
            x += 2;
        break;
        case 40:
            y += 2;
        break;
        case 37:
            x -= 2;
        break;
        default:
        break;
   }
   update();
});

A: in else put the:
$(document).unbind('keydown');
that will unbind the event with the name of keydown on document element.


text:
Q: C#/.NET: XDocument always has the wrong encoding I've got a problem with the XDocument class. I am loading information of online XML API, for my first WP8.1 App, like this:
        try
        {
            var xmlDoc = XDocument.Load(_url);
            return xmlDoc;
        }
        catch (XmlException)
        {
            HttpClient http = new HttpClient();
            HttpResponseMessage response = await http.GetAsync(new Uri(_url));
            var webresponse = await response.Content.ReadAsStringAsync();

            var content = XmlCharacterWhitelist(webresponse);
            var xmlDoc = XDocument.Parse(content);
            return xmlDoc;
        }

But both ways are returning the wrong encoding. For example German umlauts are shown the wrong way. Every XML file I load has
xml version="1.0" encoding="utf-8"
in the top line. Any ideas?

A: Rather than read the data into a byte array and decoding it yourself, just read it as a stream and let XDocument.Load detect the encoding from the data:
using (HttpClient http = new HttpClient())
{
    using (var response = await http.GetAsync(new Uri(_url)))
    {
        using (var stream = await response.Content.ReadAsStreamAsync())
        {
            return XDocument.Load(stream);
        }
    }
}

A: I fixed it by doing this:
        HttpClient http = new HttpClient();
        var response = await http.GetAsync(new Uri(_url));
        var buffer = await response.Content.ReadAsBufferAsync();
        byte[] byteArray = buffer.ToArray();
        string content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);

        var xmlDoc = XDocument.Parse(content);
        return xmlDoc;

A: Using an XmlReader should resolve issue
           string content = "your xml here";
            StringReader sReader = new StringReader(content);
            XmlTextReader xReader = new XmlTextReader(sReader);
            XDocument xmlDoc = (XDocument)XDocument.ReadFrom(xReader);


text:
Q: Drop duplicate Pandas and SQLAlchemy I am trying to make a script for a call centre that wishes to be able to upload millions of records from a csv file to a database, filtering out all duplicate phone numbers from the upload. To do this I am using Pandas and SQLAlchemy
df = read_csv('test.csv')

rd = models.session.query(Test).all()

I know there is the drop_duplicates() in pandas but can only find examples of removing duplicates from the same dataframe. Is this even applicable in my case
UPDATE:
This is what I have so far thanks to the help of others.
df = read_csv('phones.csv')

result_dict = [u.__dict__ for u in models.session.query(Dedupe).all()]

df['tel'] = df.index

rd = DataFrame.from_dict(result_dict)

print df[~df['tel'].isin(rd['tel'].unique())]

It is still printing out all of the csv. Even if there are duplicates

A: I think this illustrates how to check against the phone numbers in the database.
In [59]:  data = pd.DataFrame(range(10), columns=['number'])

In [60]: data
Out[60]:
   number
0       0
1       1
2       2
3       3
4       4
5       5
6       6
7       7
8       8
9       9

In [61]: check = range(5)

In [62]: check
Out[62]: [0, 1, 2, 3, 4]

In [63]: data = data[~data['number'].isin(check)]

In [64]: data
Out[64]:
   number
5       5
6       6
7       7
8       8
9       9

Replace data with your upload table and check will need to be a queried list of phone numbers from your database.


text:
Q: Why geom_pattern= gradient does not rend figure in RMarkdown subpage? I would like to automatically generate pages in my .Rmd document. I have found no way to do it, but I finally found an acceptable option for me (https://somtom.github.io/post/using-dynamically-rendered-r-markdown-childs-for-reports/).
Everything works fine with the example, but when I modify it to introduce my data some problems emerge. (Some figures do not appear in the final document). After some hours I figured out that the only problem appears when I try to plot a ggplot including pattern=gradient.
In this link (https://somtom.github.io/post/using-dynamically-rendered-r-markdown-childs-for-reports/) you can find the original code.
Here you can find the same code including a small modification only in the subpage code: I replaced the figure in the original code with some random figure including gradient pattern.
Please note that I placed some . before the chunks ``` in order to be recognized as a single block code (you will have to remove them to run the code).
I explored the html code and I found the figure well ploted, but it does not appears in the corresponding chart. Any other figure without gradients appears ok.
---
title: "Example Analytics"
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: fill
---
# Overview

`r shiny::tags$h1("Overview", style="text-align:center")`

.```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)

# Create dummy data for example
set.seed(345)
date_start <- as.Date("2018-01-01")
product_groups <- c("PG1", "PG2", "PG3")
products <- list(
  PG1 = c("A", "B", "C"),
  PG2 = c("D", "E", "F"),
  PG3 = c("G", "H")
)
data <- data.frame(
  product_group = sample(product_groups, 100, replace = T),
  trade_volume = rnorm(100, mean = 3448, sd = 200),
  date = date_start + 1:100
) %>%
  group_by(id = row_number()) %>%
  mutate(product = sample(unlist(products[[product_group]]), 1, replace = TRUE)) %>%
  ungroup()
.```

Row
-----------------------------------------------------------------------

### Trade Volume Development

.```{r fig.width=15, fig.height=5}
data %>%
  group_by(date) %>%
  summarise(trade_volume = sum(trade_volume)) %>%
  ggplot() +
  geom_line(aes(x = date, y = trade_volume),
           color = "#2780e3",
           alpha = 0.8) +
  scale_y_continuous(labels = scales::dollar) +
  theme_minimal() +
  ylab("Trade Volume") +
  xlab("Date")
.```

Row
-----------------------------------------------------------------------

### Product Group Share on Trade Volume

.```{r}
data %>%
  group_by(product_group) %>%
  summarise(trade_volume = sum(trade_volume)) %>%
  mutate(trade_volume_share = trade_volume / sum(trade_volume)) %>%
  ggplot() +
  geom_col(aes(x = reorder(product_group, -trade_volume_share), y = trade_volume_share),
           fill = "#2780e3",
           alpha = 0.8) +
  scale_y_continuous(labels = scales::percent) +
  theme_minimal() +
  ylab("Share on Trade Volume") +
  xlab("Product Group")
.```

### Product Group Share on Order Count

.```{r}
data %>%
  group_by(product_group) %>%
  summarise(order_count = n()) %>%
  mutate(order_count_share = order_count / sum(order_count)) %>%
  ggplot() +
  geom_col(aes(x = reorder(product_group, -order_count_share), y = order_count_share),
           fill = "#2780e3",
           alpha = 0.8) +
  scale_y_continuous(labels = scales::percent) +
  theme_minimal() +
  ylab("Share on Order Count") +
  xlab("Product Group")
.```

.```{r render subpages, include=FALSE}
# Get all unique product groups for the subpages
product_groups <- unique(data$product_group)

# Create variable which stores all subpages outputs
out = NULL

# Set knitr options to allow duplicate labels (needed for the subpages)
options(knitr.duplicate.label = 'allow')

# Create temporary environment which we use for knitting subpages.RMD
subpage_env <- new.env()

for (pg in product_groups) {
  # Filter data for product group
  subpage_data <- data %>%
    filter(product_group == pg)

  # Assign filtered data and product group to subpage_env
  assign("subpage_data", subpage_data, subpage_env)
  assign("product_group", pg, subpage_env)

  # Knit subpage.RMD using the subpage_env and add result to out vector
  out = c(out, knitr::knit_child('subpage.RMD', envir = subpage_env))
}
.```

`r paste(knitr::knit_child(text = out), collapse = '')`

`r paste0('# ', product_group, '{data-navmenu="Product Groups"}')`

`r shiny::tags$h1(product_group, style="text-align:center")`

Row
-----------------------------------------------------------------------

### Product Share on Trade Volume

.```{r fig.width=10}
#------------------------------------------! MODIFICATION INCLUDING GRADIENT PLOT-------------------------------------
df <- data.frame(
  trt         = c("a", "b", "c"),
  outcome     = c(2.3, 1.9, 3.2)
)

ggplot(df, aes(trt, outcome)) +
  geom_col_pattern(
    aes(
      pattern_fill        = trt,
      pattern_orientation = trt
    ),
    pattern       = 'gradient',
    pattern_fill2 = 'white',
    colour        = 'black'
  ) +
  theme_bw(15) +
  labs(
    title    = "ggpattern::geom_col_pattern()",
    subtitle = "pattern = 'gradient'"
  ) +
  theme(
    legend.key.size = unit(1.5, 'cm')
  ) +
  coord_fixed(ratio = 1/2)
.```

### Products with Most Trade Volume

.```{r}
subpage_data %>%
  group_by(Product = product) %>%
  summarise(`Trade Volume [€]` = sum(trade_volume)) %>%
  arrange(-`Trade Volume [€]`) %>%
  knitr::kable()
.```

A: geom_col_pattern is part of the ggpattern package it's not in ggplot2(tidyverse), you will need to add the package to your file if you want that function to work. In your question you ask about geom_pattern, but looks like the function is actually geom_col_pattern() or ggpattern::geom_col_pattern()

A: Try explicitly disabling {ggpattern}'s R 4.1 gradient support with options(ggpattern_use_R4.1_gradients = FALSE).  This fixed a similar issue for another user.


text:
Q: New Row Created - How to Get The Datepickr Working On Duplicated Row I have a row in a table that gets duplicated when a button is pressed.  See below:

<input type="text" name="session[]" size="15">
<textarea name="descr[]" cols="40" rows="5" required></textarea>
<input id='datepick' name='sessDate[]' style='padding:5px;' size='15' required />

This all works fine.  You will see that in column 3 there is a datepicker.  This is controlled by:

The first row works fine and a calendar pops up.  However when I click on the button to add a new row then obviously the datepicker doesn't work as 'datepicker2' is already being used.  How to I get the datepicker to work on newly generated rows?  Is there anyway to do it so it picks up the array for example datepicker[] then some how in the js code it automatically add another new datepickr to the script?
I can show the code to add the new row if required, it basically just duplicates the table row.
Thanks in advance

A: Give class to your field.After append new row call datepicker using class.
//code for inserting newRow
$('.Yourclass').datepicker();

Insted of class you may use Id selector. Id must be unique in your form so be careful about ID.
$('input[id^=datepick]').datepicker();

A: So, using jQuery, one way to do it is to use a custom event that would trigger as and when a new input is added. The custom event would then, go thru all the inputs, filter out the ones that do not already have a datepickr instance, and bind the datepickr to only those inputs.
Use classes as opposed to IDs as IDs need to be unique!

$("button").on("click", function() {
    $("#demo").append('<input type="text" class="datepickr" />').trigger("inputAdded");
});

$("#demo").on("inputAdded", function() {

    $(this).find("input.datepickr").filter(function() {
        return $(this).closest(".datepickr-wrapper").length === 0;
    }).each(function() {
        new datepickr(this.tagName, {
            dateFormat: 'd-m-Y'
        });
    });
}).trigger("inputAdded");

<link href="http://joshsalverda.github.io/datepickr/src/datepickr.min.css" rel="stylesheet" type="text/css"/>

    <input type="text" class="datepickr" />
    <input type="text" class="datepickr" />

<button>Add more</button>


text:
Q: Can I solve by ADMM? I wonder if I can solve the following with ADMM:
$$ \min_{A,C}||C||_* +\lambda||X-A||_F^2 $$ with the constraint $$A=AC$$.
My doubts are because usually the general form for ADMM is
$$ \min_{x,z} f(x) + g(z) $$ with the constraint $$Ax+Bz=c$$
and in my problem, I have multiplication of A and C.
What should I do ?


text:
Q: Matplot R manually labelling x-axis I have a problem labelling my matplot x-axis row. So I have 1388 instances, but I want my X-axis to a custom labeling in the form of a sequence in dates.
My R code looks like this:
Dates <- seq(as.Date("2004/01/29"), as.Date("2009/07/31"), by = "quarter")

matplot(seq(1388), t(Alldata[1, ]), type = "l",
    lwd = 1, lty = 1, col = 1:10, xlab = "Dates", ylab = "Strike",
    main = paste("TEST"), xaxt='n')
axis(side = 1:23, at=1, labels = paste(Dates, 1:23))

Can anybody help me get the Dates into the x-axis?
I have tried using same method as this: Change axis labels with matplot in R
but it doesn't work.
AllData is from an excel file in which the first number of rows looks like this:

A: I think you have confused the way the function axis works.  In answering below I will generate a random matrix to replace your Alldata which I don't have access to
Alldata <- t(as.matrix(rnorm(23)))

We can generate the plot again:
matplot(seq(23),  Alldata[1, ], type = "l",
        lwd = 1, lty = 1, col = 1:10, xlab = "Dates",
        ylab = "Strike", main = paste("TEST"), xaxt='n')

Now, its import to know what the arguments to axis are. First
side this is literally the side of the the rectangle on which the plot is drawn. It is one of the numbers 1, 2, 3, 4 corresponding to bottom, left, top, right, respectively.
You want the axis to be on the bottom so we set this to 1.
Next, the at argument, is for where the tick marks should be drawn. So if you have 10 points on your line, and you set this value to 1:10 it will draw a tick mark at each point on the axis. If you set it to c(2,4,6,8,10) it will draw a mark at every second point on the axis. In your case you've set it to 1, which would draw only one tick. Although since the side was set to 1:23 none showed up.
labels This argument will label the ticks which are drawn. Ideally it should be a vector the same length as the at value.  You can make sure that they are the same length by creating an index variable and using this as the at variable and to index the labels.
This gets us to:
index <- c(1,7,14,21)
axis(side = 1, at = index, labels = paste(Dates, 1:23)[index])

I think having a full range of dates would look cluttered. But you can drop the index and choose the below if you prefer:
axis(side = 1, at = 1:23, labels = paste(Dates, 1:23))


text:
Q: Where to securely store API keys and passwords in WordPress? I'm looking to use a few APIs and many come with keys, secret keys and passwords required to work. Where in WordPress can you store that information? Assuming anyone can hack your DB is there anyway for WordPress to make saving that information more secure? Also, consider the ability to change these keys ever so often so I would need to update the keys on an options page.
UPDATE

*

*Mossack Fonseca Breach – WordPress Revolution Slider Plugin Possible Cause

*Panama Papers: Email Hackable via WordPress, Docs Hackable via Drupal

A: The answer is NO. If your DB can be spied on, your code probably can be as well so even if you encrypt data it can be decrypted.
If you are going to store sensitive data there are no low level solution to help you with it and you just need to make your whole application secure to make the question of storage irrelevant.
I actually ran into a requirement to encrypt data so if the app security is breached and you get access only to the DB you can not use that data, but in real life you are more likely to be hacked at the wordpress level than the DB level.

A: There is no absolutely safe way to store such information permanently.
You have two options to increase security a little bit:

*

*Use the options table and encrypt the data
Use a strong encryption method, and bind it to either:

*

*your password when you want to use the API call only when you are logged in, or

*a secret key stored in your wp-config.php – then an attacker needs both, the PHP code and the database

*Store the access information outside of WordPress
If you are using a system for automatic deployment, for example based on Composer and wpstarter, you have probably some kind of deployment server like Envoyer that creates a file with important configuration variables that is stored outside of the site server's document root.
Then you can use the deployment server's backend instead of the WordPress backend to change these data.
Both options are not completely safe. You still have to monitor the actual API usage to detect unintended activities. Make sure there is a log that cannot be compromised from someone with full access to your website.


text:
Q: How to rename a Child in Firebase Database? I am developing an Android chat application using Firebase as its back end. When a user updates his/her details after somedays, I want to update the name of the child in Message node according to the updated name.

I want to Update the children names when users update there user names from the app. For example, how can I change the Child name PBW from the code?

A: Firebase ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com");
Firebase userRef = ref.child(YOUR_NODE);
Map newUserData = new HashMap();
newUserData.put(YOUR_NEW_DATA);

userRef.updateChildren(newUserData);

A: I think the best way is create another child and move data
databaseReference.child(**oldChildName**).get().addOnSuccessListener(dataSnapshot -> {
                            databaseReference.child(**newChildName**).setValue(dataSnapshot.getValue());
                            databaseReference.child(**oldChildName**).removeValue();
                        });


text:
Q: list index out of range при поиске в списке подпоследовательности подряд идущих элементов Добрый день подскажите в чем проблема? есть задача определить в списке последовательность 1, 2, 3. Я додумался только до этого:
  def listCheck(nums):

    for i in nums:
            if (nums[i] == 1) and (nums[i + 1] == 2) and (nums[i + 2] == 3):
                    return True
    return False

  lists = [1, 2, 1, 1, 2, 5, 4]

  print(listCheck(lists))[1, 2, 1, 1, 2, 11, 4]

Если в списке list присутствуют числа больше 6, то вылетает ошибка
IndexError: list index out of range
Вопрос чем вызвана данная ошибка?

A: Цикл надо делать, не доходя двух шагов до длины списка, иначе i+2 вызовет ошибку.
Поэтому цикл должен выглядеть так:
def listCheck(nums):
  for i in range(len(nums))[0:-2]:

А вообще, a бы делал так:
def listCheck(nums):
  for i in range(len(nums))[0:-2]:
    if [1,2,3] == nums[i:i+3]:
      return True
  return False

Или так
listCheck = lambda s: (1,2,3) in zip(s,s[1:],s[2:])


text:
Q: Why does this circuit require such an high resistance?
So I'm new to this and this may be a dumb question, but why is there such high resistance in this circuit when the current/voltage of it isn't that high? A 1M Ohm resistor to the collector seems like too much.

A: My interpretation is that this circuit is an extremely sensitive current amplifier, with a gain of something like 10,000,000, designed for input currents starting in the hundreds of picoamps range (based on the assumption that a typical LED current is around 20mA.)
The purpose of the current-limiting collector resistors appears to be controlling / limiting the gain of the circuit, so that larger input currents do not cause excessive output currents that would burn out the LED. [I had a previous explanation here that was not correct. I'm happier about this one, but it doesn't fully explain why the first resistor has to be so large. The circuit appears relatively insensitive to its value.]
As designed, I believe the circuit has a low input impedance, which makes sense if the input signal is meant to be a current (changes of input current don't change input voltage much.) If (as a commenter suggests) the large resistor were moved to the emitter side of the first transistor, the circuit would instead have a high input impedance, and be suitable for a voltage input signal (changes of input voltage don't change input current much.)
I am hard pressed to find other examples of circuits quite like this one, so I'm not highly confident in my answer, but I have verified the properties described above by playing around in LTSpice.
(In light of the added comment that this is a finger detector: the exact parameters of the circuit matter much less, in that case, than the fact that a huge amount of gain is required. This "amplifier" is only linear in a fairly narrow region, and it's extremely slow by most standards; and the gain is anywhere between around 1 million and 500 million, depending on the temperature and the exact specs of the transistors you end up with. But if you just want to make an LED glow when you touch an electrode, none of that is a big deal. Although, I assume by 'static electricity' you mean you are just detecting the presence of a finger from small currents flowing through it -- perhaps what you're actually detecting is capacitively-coupled mains. Real "static electricity", i.e. a painful zap from a charged-up person, would probably kill this circuit, I imagine.)

A: Without current limiting, you will burn out the bottom transistor's base region.
Thus the first 2 transistors need to limit their collector current, to protect the base of the 3rd transistor.
Also I'd place 10Kohm in that first base, just for ESD protection.


text:
Q: How to export an object returned by async/await method As Async always returns promise, we have to resolve it to get the value. I need to export it's value (returned object) so that we can use it in another module.
export const getClient = async () => {

  return await HttpService.getValueFromSettings('durl').then((response) => {
    if(isValidResponse(response)) {
        endpoint = response.data;
        export const client = createClient(response.data);
        //This is where getting error that we can not export in side the function
      }
    }
  })
}

I need to use client in another module.
I tried to declare and initialize client object before calling, but didn't work:
export let client = null;
export const getClient = async () => {
 return await HttpService.getValueFromSettings('durl').then((response) => {
    if(isValidResponse(response)) {
        endpoint = response.data;
        client = createClient(response.data);
        return client;
      }
    }
  })
}

A: I'm fairly certain you can't do what you want, at least not directly.
Instead, you should just export the getClient() function itself and just call that when you need the client.
import { getClient } from './myfile';

getClient().then(client => { someOtherFunction(client); });

import and export are decided synchronous, so you won't be able to mix and match them with an asynchronous function.
The problem with your second example is you set client = null. When you then later set it to an object, you are setting that variable to an object, but you exported the value of client at export

A: This is now possible in modern browsers with Top level await. Be sure to check browser support at the table below the example.
A simple example using fetch from MDN:
const colors = fetch('../data/colors.json')
  .then(response => response.json());

export default await colors;

The original script can be written like below and work as OP intended:
const client = HttpService.getValueFromSettings('durl').then((response) => {
  if(isValidResponse(response)) {
    return createClient(response.data);
  }
  return null;
};

export default await client;


text:
Q: Openssl native client port gives error on building I am working on a simple chrome NaCl extension where I want to use the openssl library for encryption of data. I checked out the pepper_40 branch of naclports as described on the wiki page and tried to build the port for openssl but it is encountered with the following error.
kunal@Baweja:~/Downloads/naclports/src$ ./make_all.sh openssl
+ set -e
+ TARGETS=openssl
+ TARGETS=openssl
+ BUILD_FLAGS=--ignore-disabled
+ export TOOLCHAIN
+ export NACL_ARCH
+ export BUILD_FLAGS
+ NACL_ARCH=x86_64
+ TOOLCHAIN=glibc
+ make openssl
bin/naclports install openssl --ignore-disabled
Already installed 'openssl' [x86_64/glibc/release]
+ TOOLCHAIN=newlib
+ make openssl
bin/naclports install openssl --ignore-disabled
Building 'glibc-compat' [x86_64/newlib/release]
naclports: Building glibc-compat: failed.
make: *** [openssl] Error 1

What could be the possible error exactly and any ways around that ?

A: Thanks to @sbc for telling me about VERBOSE=1 option in the comment on the above question. I identified that the libstdc++.so.6 file was missing while accessing from $NACL_SDK_ROOT/tools/sel_ldr_x86_32. This is so because my machine is of x86_64 type i.e. 64 bit. Hence we need to install libstdc++ for 32 bit machines separatly by using the command sudo apt-get install lib32stdc++6
The original solution to missing libstdc++.so.6 file is given here


text:
Q: Can't push subtree using sourcetree I'm looking to use git subtree to use a framework repo that I own in my project repo. This should look like this:

*

*project

*

*Some stuff

*Some stuff

*framework

Using Sourcetree app for windows I made the following:

*

*Clone project

*Add Subtree framework in a folder named framework

*Add test.txt in framework

That leads me to something like this:

*

*project

*

*Some stuff

*Some stuff

*framework

*

*test.txt

Sourcetree then tells me that test.txt is not staged for commit so I add it and commit it.
I might be using it wrong but I couldn't find a way to make sure test.txt was actually added to the framework repo and not to project/framework as it seems to be.
If I push this I got the right files in project/framework/test.txt as expected but the framework repo remains empty (it didn't receive the change I made)
I thought I had to manually push the subtree to commit these changes to framework repo but it seems to loop endlessly without giving me any error
I let this run for more than 10 minutes but didn't get any result. Any help would be very appreciated.
Thanks for your time.

A: Yes, you'd have to push the subtree to the remote using precisely what you were using. This is how the whole submodule/subtree approach works in general - you commit changes to your main repo but you'd have to manually push those changes up to the remote for the subtree.
We designed subtree support so you could just right click and push to the selected subtree using metadata that we store. I haven't had any reports of bugs, but that definitely looks like one. Could you report it via jira.atlassian.com including as much detail as possible, it's better handled there and I'll take a look at it then.
Cheers


text:
Q: Robolectric filenotFound on asset files Hi i am using robolectric version 3.0 for unit testing my app and have the asssets folder with some files inside under src/test/assets but keep getting fileNotFound.
Here is my test code:
```
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, manifest = Config.NONE)
public class ShowsDatesTest {

@Test
public void testResponse(){
BufferedReader = getBufferedResponseFromFile("response.json");
}

private BufferedReader getBufferedResponseFromFile(String json) throws IOException {

         mContext = RuntimeEnvironment.application;
        InputStream jsonResponse = mContext.getAssets().open(json);

        BufferedReader br = new BufferedReader(new InputStreamReader(jsonResponse, "UTF-8"));

        return br;

    }

}

```
Here is my sourceset and dependencies from my gradle file:
```
 production {
            res.srcDir 'build-config/production/res'
            test.java.srcDirs += 'src/main/java'
            test.java.srcDirs += "build/generated/source/r/production"
            test.java.srcDirs += "build/generated/source/buildConfig/production"
            test.assets.srcDir file('src/test/assets')
        }

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:19.1.+'
    compile 'com.google.code.gson:gson:2.3'
    testCompile('org.robolectric:robolectric:3.0') {
        exclude group: 'commons-logging', module: 'commons-logging'
        exclude group: 'org.apache.httpcomponents', module: 'httpclient'
    }
    compile 'com.fasterxml.jackson:jackson-parent:2.5'
    compile 'com.squareup:otto:1.3.6'
    compile 'com.jakewharton:butterknife:6.1.0'
    compile 'com.sothree.slidinguppanel:library:3.0.0'
    compile 'com.crashlytics.android:crashlytics:1.+'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    compile 'joda-time:joda-time:2.8.2'
    testCompile('junit:junit:4.12') {
        exclude module: 'hamcrest'
        exclude module: 'hamcrest-core'
    }
    testCompile 'org.hamcrest:hamcrest-all:1.3'
    compile 'com.sothree.slidinguppanel:library:3.0.0'
    compile 'com.squareup:otto:1.3.6'
    compile 'com.squareup.okhttp:okhttp:2.3.0'
    testCompile 'org.apache.maven:maven-ant-tasks:2.1.3'

    compile 'com.google.android.gms:play-services:7.0.0'

    compile 'com.android.support:multidex:1.0.0'

    compile 'com.android.support:recyclerview-v7:21.0.+'
    compile 'com.squareup.picasso:picasso:2.5.2'

```
production is a build varient