text:
Q: R apply function across rows, unexpected answer I don't understand what is going on here:
Set up:
> df = data.frame(x1= rnorm(10), x2= rnorm(10))
> df[3,1] <- "the"
> df[6,2] <- "NA"
## I want to create values that will be challenging to coerce to numeric
> df$x1.fixed <- as.numeric(df$x1)
> df$x2.fixed <- as.numeric(df$x2)
## Here is the DF
> df
                   x1                 x2   x1.fixed   x2.fixed
1   0.955965351551298 -0.320454533088042  0.9559654 -0.3204545
2   -1.87960909714257   1.61618672247496 -1.8796091  1.6161867
3                 the -0.855930398468875         NA -0.8559304
4  -0.400879592905882 -0.698655375066432 -0.4008796 -0.6986554
5   0.901252404134257  -1.08020133150191  0.9012524 -1.0802013
6    0.97786920899034                 NA  0.9778692         NA
.
.
.
> table(is.na(df[,c(3,4)]))

FALSE  TRUE
   18     2

I wanted to find the rows that got converted to NAs, so I put in a complex apply that did not work as expected.  I then simplified and tried again...
Question:
Simpler call:
> apply(df, 1, function(x) (any(is.na(df[x,3]), is.na(df[x,4]))))

which unexpectedly yielded:
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

Instead, I'd expected:
[1] FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE

to highlight the rows (3 & 6) where an NA existed.  To verify that non-apply'ed functions would work, I tried:
> any(is.na(df[3,1]), is.na(df[3,2]))
[1] FALSE
> any(is.na(df[3,3]), is.na(df[3,4]))
[1] TRUE

as expected.  To further my confusion on what apply is doing, I tried:
> apply(df, 1, function(x) is.na(df[x,1]))
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE  TRUE
[2,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE  TRUE
[3,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE  TRUE
[4,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE  TRUE

Why is this traversing the entire DF, when I have clearly indicated both (a) that I want it in the row direction (I passed "1" into the second parameter), and (b) the value "x" is only placed in the row id, not the column id?
I understand there are other, and perhaps better, ways to do what I am trying to do (find the rows that have been changed to NA's in the new columns.  But please don't supply that in the answer.  Instead, please explain why apply did not work as I'd expected, and what I could do to fix it.

A: To find the columns that have NA's you can do:
sapply(df, function(x) any(is.na(x)))
#      x1       x2 x1.fixed x2.fixed
#   FALSE    FALSE     TRUE     TRUE

A data.frame is a list of vectors, so the above function inside sapply will evaluate any(is.na( for each element of that list, i.e. each column.
As per OP edit - to get the rows that have NA's, use apply(df, 1, ... instead:
apply(df, 1, function(x) any(is.na(x)))
# [1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE

A: apply is working exactly as it is supposed to. It is your expectations that are wrong.
apply(df, 1, function(x) is.na(df[x,1]))

The first thing that apply does (per the documentation) is coerce your data frame to a matrix. In the process, all numeric columns are coerced to character.
Next, each individual row of df is passed as the argument x to your function. In what sense is it meaningful to index df by the character values in the first row in df? So you just get a bunch of NAs. You can test this via:
> df[as.character(df[1,]),]
       x1   x2 x1.fixed x2.fixed
NA   <NA> <NA>       NA       NA
NA.1 <NA> <NA>       NA       NA
NA.2 <NA> <NA>       NA       NA
NA.3 <NA> <NA>       NA       NA

You say you want to know which columns introduced NAs, and yet you are applying over rows. If you really wanted to use apply (I recommend @eddi's method) you could do:
apply(df,2,function(x) any(is.na(x)))

A: You could use
rowSums(is.na(df))>0
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE

to find the rows containing NAs.
I'm not sure, but I think this is a vectorized operation which might be faster than using apply in case you are working with large data.


text:
Q: Javascript this keyword - inside function I am trying to understand the this keyword on Javascript.
I was doing some tests on chrome console and I came across two different results that I was expecting to be the same:
var myTest = {};
myTest.test1 = function() {
        return this; // this = Object
}

This first function returns myTest object which I understand.
var myTest = {};
myTest.test1 = function() {
    return function test2() {
        return this; // this = Window
    }
}

Why is the second function returning the window instead of the myTest object?
Thank you

A: this refers to the current object on which the function is called. When you called test1, you would have done like this
myTest.test1()

Now, test1 is called on myTest object. That is why this refers to myTest in the first case.
In the second case, you would have executed like this
myTest.test1()()

myTest.test1() returns a function and you are invoking without any current object. In that case, JavaScript will make sure that this will refer the global object (window in this case).
Note: But, in strict mode, this will be undefined, in the second case. You can confirm that like this
var myTest = {};
myTest.test1 = function() {
    return function test2() {
        console.log("this is global", this === window);
        console.log("this is undefined", this === undefined);
        return this;
    }
}

myTest.test1()();

Output will be
this is global true
this is undefined false

But if you include use strict like this
"use strict";

var myTest = {};
myTest.test1 = function() {
    return function test2() {
        console.log("this is global", this === window);
        console.log("this is undefined", this === undefined);
        return this;
    }
}

myTest.test1()();

Output will be
this is global false
this is undefined true

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trouble with function return type I am having trouble with creating a function that returns the following Gradient type (https://docs.rs/nannou/latest/nannou/color/gradient/struct.Gradient.html) from the nannou. I now realize this is going to be a problem for me in general with complex generics types.
I tried to use a trick I've seen, which is to call a non-existent function on a given type to have the compiler complain.
8 |     gradient.asdfasdf();
  |              ^^^^^^^^ method not found in `nannou::color::Gradient<nannou::prelude::rgb::Rgb<nannou::color::encoding::Linear<Srgb>>>`

So great! My type must be nannou::color::Gradient<nannou::prelude::rgb::Rgb<nannou::color::encoding::Linear<Srgb>>>
So then I created the function with that as the return type:
pub fn get_gradient(color_1: Rgb, color_2: Rgb) -> nannou::color::Gradient<nannou::prelude::rgb::Rgb<nannou::color::encoding::Linear<Srgb>>> {
    let (r1, g1, b1) = color_1.into_components();
    let (r2, g2, b2) = color_2.into_components();

    Gradient::new(vec![lin_srgb(r1 as f32, g1 as f32, b1 as f32), lin_srgb(r2 as f32, g2 as f32, b2 as f32)]);
}

But then the compiler gives a new error:
error[E0277]: the trait bound `nannou::prelude::rgb::Rgb: RgbSpace` is not satisfied
  --> examples/utils/color.rs:3:52
   |
3  | ...color_2: Rgb) -> nannou::color::Gradient<nannou::prelude::rgb::Rgb<nannou::color::encoding::Linear<Srgb>>> {
   |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `RgbSpace` is not implemented for `nannou::prelude::rgb::Rgb`
   |
   = help: the following other types implement trait `RgbSpace`:
             (P, W)
             nannou::color::encoding::Srgb
   = note: required because of the requirements on the impl of `RgbStandard` for `nannou::color::encoding::Linear<nannou::prelude::rgb::Rgb>`
note: required by a bound in `nannou::prelude::rgb::Rgb`
  --> /Users/brittcagnina/.cargo/registry/src/github.com-1ecc6299db9ec823/palette-0.5.0/src/rgb/rgb.rs:46:19
   |
46 | pub struct Rgb<S: RgbStandard = Srgb, T: Component = f32> {
   |                   ^^^^^^^^^^^ required by this bound in `nannou::prelude::rgb::Rgb`

I'm unsure how to proceed or even interpret this error. Not just with this particular type but in general. I'm having trouble with several other types in this library that use generics. What is the general strategy or principles needed to figure this out?
Thanks!

A: Turns out the naming in the nannou crate is quite a mess.
There are multiple Rgb types:

*

*nannou_core::color::Rgb, re-exported as:

*

*nannou::color::Rgb

*nannou::prelude::Rgb

*palette::rgb::Rgb, re-exported as:

*

*nannou::color::rgb::Rgb

*nannou::prelude::rgb::Rgb
Further, there are multiple Srgb types:

*

*palette::rgb::Srgb, re-exported as:

*

*nannou::color::rgb::Srgb

*nannou::prelude::rgb::Srgb

*palette::encoding::srgb::Srgb, re-exported as:

*

*nannou::color::encoding::Srgb
Note that especially in the Rgb case, even the docs are confused and tend to link to the wrong Rgb type.
Either way, the actual mistake you made is that you chose the wrong Srgb type:
use nannou::{color::Gradient, prelude::*};

pub fn get_gradient(
    color_1: Rgb,
    color_2: Rgb,
) -> nannou::color::Gradient<
    nannou::prelude::rgb::Rgb<nannou::color::encoding::Linear<nannou::color::encoding::Srgb>>,
> {
    let (r1, g1, b1) = color_1.into_components();
    let (r2, g2, b2) = color_2.into_components();

    Gradient::new(vec![
        lin_srgb(r1 as f32, g1 as f32, b1 as f32),
        lin_srgb(r2 as f32, g2 as f32, b2 as f32),
    ])
}

Alternatively, you don't even need the full form, because Rgb<Linear<Srgb>, f32> is just the long form of the actual return type of your lin_srgb, which is LinSrgb<f32>:
use nannou::{color::Gradient, prelude::*};

pub fn get_gradient(color_1: Rgb, color_2: Rgb) -> Gradient<LinSrgb<f32>> {
    let (r1, g1, b1) = color_1.into_components();
    let (r2, g2, b2) = color_2.into_components();

    Gradient::new(vec![
        lin_srgb(r1 as f32, g1 as f32, b1 as f32),
        lin_srgb(r2 as f32, g2 as f32, b2 as f32),
    ])
}


text:
Q: Parse local json to UILabels I'm trying to parse a JSON file so I can use it's contents as NSStrings and display in UILabels throughout my application.
My JSON:
{
    "CustomText": [
        {
            "bodyText": "This is the body text",
            "loginText": "This is the loginText",
            "extraText": "This is the extra text"
        }
    ]
}

My code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"json"];

NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:content options:kNilOptions error:nil];

NSArray *customStrings = json[@"CustomText"];
NSString *body = [customStrings valueForKey:@"bodyText"];
NSString *login = [customStrings valueForKey:@"loginText"];
self.labelText.text = body;

I'm not sure why it breaks, I have looks and surprisingly didn't find much on how to best use a local JSON file.  Any help would be great.
Error message:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: '-[__NSArrayI length]:
  unrecognized selector sent to instance 0x7f8080781740'

A: NSString *filePath = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"json"];

NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
   NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:content options:kNilOptions error:nil];

NSArray *customStrings = json[@"CustomText"];
NSString *body = [[customStrings objectAtIndex:0] valueForKey:@"bodyText"];
NSString *login = [[customStrings objectAtIndex:0] valueForKey:@"loginText"];
self.labelText.text = body;

A: Use keypath
    NSString * body = [json valueForKeyPath:@"CustomText.bodyText"];
    self.labelText.text = body;


text:
Q: PhpMyAdmin Trigger is not creating with error: 1064 I am trying to create a trigger on PHPMYADMIN and this query below is not working, it is showing the error:

*

*"#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE Contas SET Saldo = Saldo - NEW.Valor_Transferido WHERE Apos' at line 11"
delimiter //
CREATE TRIGGER TRG_UPDATE_SALDO BEFORE INSERT ON Transferencias
FOR EACH
ROW
BEGIN
    IF (NEW.Valor_Transferido > 0) THEN

UPDATE Contas
   SET Saldo = Saldo + NEW.Valor_Transferido
WHERE Apostador_ID = NEW.Destino_Apostador_ID

UPDATE Contas
   SET Saldo = Saldo - NEW.Valor_Transferido
WHERE Apostador_ID = NEW.Origem_Apostador_ID

   END IF
END;
//
delimiter ;

Any idea where on this query is wrong??
Thanks in advance.


text: Q: Xamarin Forms Ask User to Enable Location The user gave location permission but the location is off. I wanna make a dialog box and ask the user to enable the location. I found a lot of similar questions but could not make it work. Can u help me? (Do I need to make 2 platform-specific implementations? or can I use xamarin forms?)


text:
Q: Can't change my screen resolution on Esprimo Mobile v5535 I just installed Ubuntu 12.04.5 in my old Fujitsu Siemens Esprimo Mobile v5535, but i think the graphics card driver is not installed with, because whenever i open a window, I can't see the whole thing. For example, when I google something, I can't see the research results properly, as everything is just huge. I tried to change the resolution but the only option is 640x480. Can somenone help me fixing this?

A: You can install a driver, but you will need to downgrade the graphical stack to support the driver.
Run in terminal
sudo apt-get install xserver-xorg xserver-xorg-input-all

You will be asked to agree to remove lots of packages and install lots too. You will need to agree with that.
Reboot.
If the procedure was OK, then proceed. You will need to install some packages and build the driver.
Run in terminal (one-by-one).
sudo apt-get install git xorg-dev mesa-common-dev libdrm-dev libtool build-essential
sudo apt-get install x11proto-xf86dga-dev x11proto-xf86dri-dev x11proto-gl-dev libxext-dev
git clone git://github.com/hellnest/xf86-video-sismedia-0.9.1.git
cd xf86-video-sismedia-0.9.1
./configure --prefix=/usr --disable-static
sudo make install

Reboot again. You will be able to set 1280x800 resolution.
There may be issues with running videos. If you meet any, let me know. I will try to remember how they are fixed.
Don't be worried with funny things happening with the splash screen with Ubuntu logo at boot and shutdown. It is OK.
Do not upgrade the system to 14.04. There is no way to get the graphics adapter work properly on new Ubuntu versions.
You may also meet a problem with video playback. In this case run
gstreamer-properties

and switch output to X11.
If you are using VLC, you will need to switch output in VLC settings.

A: this solved me:
 sudo nano /etc/default/grub
;uncomment the line;
 #GRUB_GFXMODE=640x480 to p.ex.
 GRUB_GFXMODE=1024x768
;save and;
 sudo update-grub
;on next boot you'll have the desired screen resolution


text:
Q: Bounds on propogation speed of solutions to variable-speed wave equations Suppose $u(x,t)$ where $x \in \mathbb{R}^3$ and $t \in \mathbb{R}$ satisfies the speed varying wave equation:
$$ \sum_{i=1}^3\frac{\partial^2}{\partial x_i ^2}u - \frac{1}{c(x)^2} \frac{\partial^2}{\partial t ^2} u =0 $$
where $0 < c(x) < c$ for some $c > 0$. Then if the initial wave $u(x,0)$ vanishes outside a ball $B(x_0, R)$ of radius $R$ centred at $x_0$ then does $u(x,t)$ necessarily vanish outside the ball $B(x_0, R+ct)$ for $t>0$ ?
It sounds physically intuitive but is there a formal proof? Is there a formulation for weak solutions to the wave equation (e.g., in Sobolev space) ? I know that if $c(x)$ is constant then it follows from Kirchoff integral theorem and this answer states that it can be generalized but seems quite complex, so I was wondering if we can avoid that machinery in this more mild question.

A: See https://users.math.msu.edu/users/yanb/847-full-note.pdf Theorem 4.19 where you can use inequality 4.29 instead of 4.30 in the hypothesis. I suspect it gives this exact bound.


text:
Q: How to sort varchar values in oracle I want to know how to sort ascending or descending varchar values.
This is my field and values
Filling_s_no            varchar2;
Table:
Id  Filling_s_no    name
1   1.1.1            X
1   1.1.10           X
1   1.1.5            X
1   1.1.2            X
1   1.2.1            X
1   1.2.0            X

Now I want to sort my table like this format
Id  Filling_s_no    name
1   1.1.1            X
1   1.1.2            X
1   1.1.5            X
1   1.1.10           X
1   1.2.0            X
1   1.2.1            X

I tried with this query but am unable get the solution.
select *
  from TCD_EX_Tab
 where id=1
 order by Filling_s_no ASC;

A: The following query will do what you need:
SELECT ID, FILLING_S_NO, NAME
  FROM TCD_EX_TAB
  where id=1
  order BY TO_NUMBER(REGEXP_SUBSTR(filling_s_no, '[0-9]+', 1, 1)),
           TO_NUMBER(REGEXP_SUBSTR(filling_s_no, '[0-9]+', 1, 2)),
           TO_NUMBER(REGEXP_SUBSTR(filling_s_no, '[0-9]+', 1, 3));

The problem to be solved is that the components of the text string need to be converted to numbers in order to sort as you want them to. We use a regular expression to pick out each of the sub-elements of the string, then convert those sub-elements to type NUMBER for sorting purposes.
Best of luck.


text:
Q: UIBarButton Title Only Shows Periodically I'm adding a UIToolbar to my UIViewController programmatically.
The problem I have is that when my view is created the buttons in the toolbar "DO" show but they do not show their title text.
If I wait for 10 - 20 seconds or sometimes even longer the titles will eventually show.
I tried calling setNeedsDisplay and setNeedsLayout to force the UI yo update but it straight up doesnt work.
Am I doing something ridiculous? I can't for the life of me figure out why the title don't show immediately.
-(id)initWithFrame:(CGRect)frame
{
    self= [super init];

    if (self) {
        UIView  *view=[[UIView alloc]initWithFrame:frame];
        self.view=view;
        cellLoader = [UINib nibWithNibName:CellClassName bundle:[NSBundle mainBundle]] ;

        self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.origin.x,
                                                                    self.view.frame.origin.y+44,
                                                                    self.view.frame.size.width,
                                                                    self.view.frame.size.height-44)
                                                   style:UITableViewStylePlain];

        [self.tableView registerClass:[MyCell class] forCellReuseIdentifier:@"mycell"];
        [self.view addSubview:self.tableView];

        self.tableView.dataSource=self;
        self.tableView.delegate=self;
        //[self.tableView setContentInset:UIEdgeInsetsMake(44, 0, 0, 0)];

        navItem = [[UINavigationItem alloc] init];

        UILabel* lbNavTitle = [[UILabel alloc] initWithFrame:CGRectMake(-200,50,100,40)];
        [lbNavTitle setBackgroundColor:[UIColor clearColor]];
        lbNavTitle.textAlignment = NSTextAlignmentLeft;
        [lbNavTitle setTextColor:[UIColor whiteColor]];
        lbNavTitle.text = NSLocalizedString(@"",@"");
        navItem.titleView = lbNavTitle;

        naviBar = [[UINavigationBar alloc] init];
        naviBar.barStyle=UIBarStyleBlack;
        naviBar.items = [NSArray arrayWithObject:navItem];
        naviBar.frame = CGRectMake(0.0, 0, self.view.frame.size.width, 44.0);

        toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 350, 44)];

        toolbar.barStyle=UIBarStyleBlack;
        NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:7];

         button1=[[UIBarButtonItem alloc]
                                               initWithTitle:@"Button 1 text"
                                               style:UIBarButtonItemStyleBordered target:self
                                               action:@selector(buttononepressed:)];
        [buttons addObject: button1];

        UIBarButtonItem *spacer1 = [[UIBarButtonItem alloc]
                                    initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                    target:nil
                                    action:nil];

        [buttons addObject:spacer1];

        button2=[[UIBarButtonItem alloc]
                                            initWithTitle:@"Button 2 text"
                                            style:UIBarButtonItemStyleBordered target:self
                                            action:@selector(button2pressed:)];
        [buttons addObject:button2];

        [toolbar setItems:buttons animated:NO];

            [self.view addSubview:toolBar];

            [naviBar setNeedsDisplay];
            [toolbar setNeedsDisplay];
            [self.view setNeedsDisplay];

    }

    return self;

}

A: Ok, if this is your viewController, you don't want to create all the view hierarchy in the init method, instead, use the viewDidLoad method. (and you don't have to set self.view yourself, default implementation in UIViewController does that for you)
Also, you're creating a UINavigationBar AND a UIToolBar, setting same frames for both when you just add the toolbar as subview... (I'll consider this UINavigationBar junk code too)
- (void)viewDidLoad
{

    cellLoader = [UINib nibWithNibName:CellClassName bundle:[NSBundle mainBundle]] ;

    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.origin.x,
                                                                      self.view.frame.origin.y+44,
                                                                    self.view.frame.size.width,
                                                                    self.view.frame.size.height-44)
                                                   style:UITableViewStylePlain];

    [self.tableView registerClass:[MyCell class] forCellReuseIdentifier:@"mycell"];
    [self.view addSubview:self.tableView];

    self.tableView.dataSource=self;
    self.tableView.delegate=self;

    toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 350, 44)];
    toolbar.barStyle=UIBarStyleBlack;

    UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:@"Button 1 text"
                                                  style:UIBarButtonItemStyleBordered target:self
                                                 action:@selector(buttononepressed:)];
    UIBarButtonItem *spacer1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                    target:nil
                                    action:nil];

    UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithTitle:@"Button 2 text"
                                                 style:UIBarButtonItemStyleBordered target:self
                                                action:@selector(button2pressed:)];

    // using Objective-C litterals you shorter code than using NSMutableArray !
    [toolbar setItems:@[button1, spacer1, button2] animated:NO];

    [self.view addSubview:toolBar];

  }

}

Normally, that's all you need (no call to setNeedsDisplay, these are done automatically when adding subviews)


text:
Q: Query XML with variable using PHP I've started parsing XML with PHP and got stuck with this problem. I've managed to query the XML with the following method:
echo $xml->textbox->item->id;

What's the syntax to use a variable instead of textbox?
I've tried (but didn't work):
echo $xml[$type]->item->id;
echo $xml->[$type]->item->id;

Any ideas?

A: $xml->{$variable}->item->id

will work. You may want to check first whether  that path exists, e.g. using empty().


text:
Q: Hibernate criteria.list() sets the session dirty I have the following queries with the criteria API:
1.
ICriteria criteria = _session.CreateCriteria<Country>();
criteria.Add(Restrictions.Like("Code", "%C%"));
IList<Country> countryList = criteria.List<Country>();

2.
ICriteria criteria = _session.CreateCriteria<Facility>();
criteria.Add(Restrictions.Like("Visible", true));
IList<Facility> facilityList = criteria.List<Facility>();

After the 2nd query, my session gets dirty, while after the 1st query it doesn't. My Country entity has only simple properties, the Facility has many-to-one and one-to-many as well.
Could you tell me why the session gets dirty?

A: Suppose your 2nd query returns one Facility object f1, and its EntityKey is k1. The reason it gets dirty is: Before 2nd query, the same Session already held a Facility object f2, and its EntityKey is same with k1! While there is some attributes different between f1 and f2. During 2nd query, executing query make Session do a dirty check, thus Session is considered as "dirty".
How to debug this? You can output all objects current Session holds before 2nd query (something like Set<EntityKey> set = session.getStatistics().getEntityKeys();, refer Hibernate session.contains( Class clazz, Serializable id ), @TheReincarnator's answer), I think you should find at least one Facility. Then you can debug whether the Facility is same with that one 2nd query get (it should be different!).


text:
Q: Pass tags (with spaces) to an ARM template using Azure Devops Pipeline I am using Azure DevOps Pipelines to deploy an ARM template. My template has a tags parameter that I pass into the pipeline using AzureResourceManagerTemplateDeployment@3.
My ARM template has a value in parameters section as an object. tags is an object, which is what many of the sample templates show:
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "resourceName": {
      "type": "string",
      "metadata": {
        "description": "Specifies the name of the resource, including its prefix."
      }
    },
    "tags": {
      "type": "object",
      "defaultValue": {
        "Cost Center": "Admin"
      }
    }
  },
  "resources": [
    {
      "apiVersion": "2019-06-01",
      "kind": "StorageV2",
      "location": "[resourceGroup().location]",
      "name": "[parameters('resourceName')]",
      "properties": {
        "supportsHttpsTrafficOnly": true
      },
      "sku": {
        "name": "Standard_LRS"
      },
      "type": "Microsoft.Storage/storageAccounts",
      "tags": "[parameters('tags')]"
    }
  ]
}

[Edited to match the thread that follows]
I am using ubuntu-latest for my pool. Tags may have spaces.
In my pipeline for simplicity, I set the tags to a variable.
pool:
  vmImage: 'ubuntu-latest'
variables:
  - name: tags
    value: ("Location Region=West US 2" "Environment=${{ parameters.environment }}")

When I call the template deployment, I am passing in the tags as an overrideParameters
  - task: AzureResourceManagerTemplateDeployment@3
    displayName: "Deploy my templateaccount"
    inputs:
      deploymentScope: 'Resource Group'
      azureResourceManagerConnection: 'ResourceManager-connection'
      subscriptionId: ${{ parameters.subscriptionid }}
      action: 'Create Or Update Resource Group'
      resourceGroupName: '$(resourceGroupName)'
      location: '${{ parameters.location }}'
      templateLocation: 'Linked artifact'
      csmFile: 'mytemplatelocation/azuredeploy.json'
      overrideParameters: -resourceName abcdefg76534 -tags "$(tags)"
      deploymentMode: 'Incremental'
      deploymentOutputs: resourceOutput
  - pwsh: Write-Output '$(resourceOutput)'

So far I have not understood how AzureResourceManagerTemplateDeployment@3 on Ubuntu is expecting the tags to be sent.
In each case, the template fails to deploy.
Is this scenario supported in Azure DevOps Pipeline?
Anyone with a suggestion?

A: The format for the tags that worked in Azure DevOps pipeline AzureResourceManagerTemplateDeployment@3 is to use JSON for your ARM Template objects, such as tags.

*

*Left curly bracket, colon separating the key value pairs, and comma separating the tags.

*Each key and the value in my case worked with quotes.

*A right curly bracket.

But following templates works by passing in a JSON object: {"Cost Center":"DevTest","Location":"West US"} as your template parameter. In context this looks like:
- task: AzureResourceManagerTemplateDeployment@3
  inputs:
    deploymentScope: 'Resource Group'
    azureResourceManagerConnection: 'ResourceManager-connection'
    subscriptionId: 'XXXXX'
    action: 'Create Or Update Resource Group'
    resourceGroupName: 'rg-wus2-exampletest'
    location: 'West US 2'
    templateLocation: 'Linked artifact'
    csmFile: 'storageaccount/example.azuredeploy.json'
    csmParametersFile: 'storageaccount/azuredeploy.parameters.json'
    overrideParameters: '-resourceName oweruhsow -resourceTags {"Cost Center":"DevTest","Location":"West US"}'
    deploymentMode: 'Complete'

This Pipeline module is expecting JSON objects, not the same format used elsewhere with PowerShell (https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/tag-resource) to deploy from the command line.
Also as a side note, other posts suggested that you name use something other than tags for your tags parameter. The one that worked for me is resourceTags. Here is my ARM template:
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "resourceName": {
      "type": "string",
      "metadata": {
        "description": "Specifies the name of the resource"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for the resources."
      }
    },
    "resourceTags": {
      "type": "object",
      "defaultValue": {
        "Cost Center": "Admin"
      }
    }
  },
  "resources": [
    {
      "apiVersion": "2019-06-01",
      "kind": "StorageV2",
      "location": "[parameters('location')]",
      "name": "[parameters('resourceName')]",
      "properties": {
        "supportsHttpsTrafficOnly": true
      },
      "sku": {
        "name": "Standard_LRS"
      },
      "type": "Microsoft.Storage/storageAccounts",
      "tags": "[parameters('resourceTags')]"
    }
  ]
}

If you want to set your template object as a the variable, you then can pass it in using the DevOps variable such as $(tags):
variables:
  tags: '{"Cost Center":"DevTest","Location":"West US"}'
steps:
- task: AzureResourceManagerTemplateDeployment@3
  inputs:
    deploymentScope: 'Resource Group'
    azureResourceManagerConnection: 'ResourceManager-connection'
    subscriptionId: '9f241d6e-16e2-4b2b-a485-cc546f04799b'
    action: 'Create Or Update Resource Group'
    resourceGroupName: 'rg-wus2-exampletest'
    location: 'West US 2'
    templateLocation: 'Linked artifact'
    csmFile: 'storageaccount/example.azuredeploy.json'
    csmParametersFile: 'storageaccount/azuredeploy.parameters.json'
    overrideParameters: '-resourceName oweruhso11w -resourceTags $(tags)'
    deploymentMode: 'Complete'

Also (as a side note), for some reason, the module needed to have a csmParametersFile or it would just fail with something about failing with RESOURCEGROUP in all caps. The param file is not needed to deploy from the command line, but Pipelines modules does seem to require it.
A csmParamters file that can have just about nothing in it, but it seems to be needed.
{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
    "contentVersion": "1.0.0.0",
    "parameters": { }
  }

This also works using the pool image: windows-latest
Many thanks to ToMakesSense in the post at https://github.com/MicrosoftDocs/azure-devops-docs/issues/9051

A: If the parameter value you're using has multiple words, enclose them in quotes, even if you're passing them using variables.
For example, -name "parameter value" -name2 "$(var)".
Try to use below format:
overrideParameters: -location "${{ parameters.location }}" -tags "$(tags)"

More details please refer our official doc here-- Azure Resource Group Deployment task


text:
Q: Looping Through an Array with jQuery I have a question about creating Custom Lists with User Friendly touch.
I have the following example:
var unitA = [];
unitA[0] = "Unit A One";
unitA[1] = "Unit A Two";
unitA[2] = "Unit A Three";

var unitB = [];
unitB[0] = "Unit B One";
unitB[1] = "Unit B Two";
unitB[2] = "Unit B Three";

var level = [];
level[0] = "Level 1";
level[1] = "Level 2";
level[2] = "Level 3";

var skill = [];
skill[0] = "This has Skill 1";
skill[1] = "This has Skill 2";
skill[2] = "This has Skill 3";
skill[3] = "This has Skill 4";

$('

').appendTo('body');

var unit = [];
$.each(unitA, function(index, value) {unit.push('
'+value+'
');});
$.each(unitB, function(index, value) {unit.push('
'+value+'
');});
$(".units").html(unit.join(""));

The code above would loop through unitA and unitB and output data to HTML body in the DIV.
Unit A One
Unit A Two
Unit A Three
Unit B One
Unit B Two
Unit B Three

After I do this:
$(".unitA-0").append(
                '
'+level[0]+'
'+skill[0]+'

'+skill[1]+'

'+skill[2]+'

'+skill[3]+'

',
                '
'+level[1]+'
'+skill[0]+'

'+skill[1]+'

'+skill[2]+'

'+skill[3]+'

'
                );

$(".unitA-1").append(
                '
'+level[0]+'
'+skill[0]+'

'+skill[1]+'

',
                '
'+level[1]+'
'+skill[1]+'

',
                '
'+level[2]+'
'+skill[0]+'

'+skill[1]+'

'+skill[2]+'

'+skill[3]+'

'
                );

This would output data as:
Unit A One
> Level 1 > Skill 1 / Skill 2 / Skill 3 / Skill 4
> Level 2 > Skill 1 / Skill 2 / Skill 3 / Skill 4
Unit A Two
> Level 1 > Skill 1 / Skill 2
> Level 2 > Skill 2
> Level 3 > Skill 1 / Skill 2 / Skill 3 / Skill 4
Unit A Three
Unit B One
Unit B Two
Unit B Three

My goal is to create user friendly and maintainable code similar to List / Menu / Navigation style as I might have many of the Units, Levels and Skills.
If anyone can suggest how to create more efficient logic to handle this.
More like:
unitA-1+level-1+skill-1+skill-2
unitA-1+level-2+skill-1+skill-4+skill-5

Would output:

Unit Name 1

Level Name 1

Skill Name 1

Skill Name 2

Level Name 2

Skill Name 1

Skill Name 4

Skill Name 5

Thank you all for your time!

A: If I understand your problem correctly, you may want to first look at how you're storing the data.
With this kind of relational model (Units have Levels which have Skills), you may want to use a JSON-like way of storage. For Example:
var units = [
    {
        name   : 'Unit Name 1',
        levels : [
            {
                name   : 'Level Name 1',
                skills : [
                    'Skill Name 1',
                    'Skill Name 2'
                ]
            },
            {
                name   : 'Level Name 2',
                skills : [
                    'Skill Name 1',
                    ...
                ]
            },
            ...
        ]
    },
    {
        name   : 'Unit Name 2',
        levels : [
            ...
        ]
    },
    ...
];

You can loop through these with jQuery like:
$(units).each(function (unitIndex, unitValue) {
    // Print
unitValue.name

    $(unitValue.levels).each(function (levelIndex, levelValue) {
        // Print header for list (levelValue.name) and

        $(levelValue.skills).each(function (skillIndex, skillValue) {
            // Print
skillValue

        });
    });
});


text:
Q: How can I create a TableLayoutPanel in VB Dynamically? I'm trying to make a tableLayoutPanel by code in Windows Form VB which can later be coded to add on extra rows and columns also by coding

A: When the form starts:
Private Sub form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _MyBase.Load
          Dim TLP As New TableLayoutPanel
         'Edit all your properties: name, size, location, etc.
End Sub
Say when you click a button1:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Controls.Add(TLP)
End Sub
Hope that helps.


text:
Q: Adding console output to NUnit test results I have been trying to figure out a way to add some string output to NUnit test results. I did some research and came across this, but this is not what I want. I want to write the output to the result xml generated by NUnit, but I cannot find a way to do it. Please suggest!
I aware that NUnit 3 will have a mechanism called TextContex to accomplish something similar, but I am using 2.6.3.

A: You could take advantage of PropertyAttributes to attach properties per test to the XML output. The example below assumes you really want to use Console.WriteLine to produce string output, but you could always make your own TestConsole.WriteLine or something if you don't want to mess with the console output.
E.g. this attribute says to attach an "Output" property to each test it's declared on:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class TestWriterAttribute : PropertyAttribute
{
    public TestWriterAttribute() : base()
    {
        // Create a container for test output
        Properties["Output"] = new StringBuilder();
    }
}

And this attribute says to redirect Console.Out to your "Output" property (again, you can use your own TestConsole kind of class instead of using this attribute if you don't want to mess with Console.Out).
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ConsoleOutToTestWriterAttribute : TestActionAttribute
{
    public override void BeforeTest(TestDetails testDetails)
    {
        // If the test has a [TestWriter], redirect Console.Out to its "Output" property
        var output = TestContext.CurrentContext.Test.Properties["Output"] as StringBuilder;
        if (output != null)
            Console.SetOut(new System.IO.StringWriter(output));
        _consoleOutRedirected = output != null;
    }

    public override void AfterTest(TestDetails testDetails)
    {
        // Reset Console.Out, if appropriate
        if(_consoleOutRedirected)
            Console.SetOut(new System.IO.StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
    }

    public override ActionTargets Targets
    {
        // needs to apply to each test, since [TestWriter]s are applied per test
        get { return ActionTargets.Test; }
    }

    private bool _consoleOutRedirected;
}

And your tests can just use Console.WriteLine which will be captured per test:
[ConsoleOutToTestWriter] // redirect Console.Out into "Output" property per test
public class ClassTest
{
    [Test]
    [TestWriter] // adds "Output" property
    public void MyTest()
    {
        Console.WriteLine("test 123");
        Console.WriteLine("321 test");
    }

    [Test]
    [TestWriter]
    public void MyTest2()
    {
        // this console output will be written to this test's own "Output"
        Console.WriteLine("test2 123");
        Console.WriteLine("321 test2");
    }
}

Which produces the following under <results> in the NUnit XML output:
<test-case name="SO_31092459.ClassTest.MyTest" executed="True" result="Success" success="True" time="0.023" asserts="0">
    <properties>
        <property name="Output" value="test 123
321 test
" />
    </properties>
</test-case>
<test-case name="SO_31092459.ClassTest.MyTest2" executed="True" result="Success" success="True" time="0.000" asserts="0">
    <properties>
        <property name="Output" value="test2 123
321 test2
" />
    </properties>
</test-case>


text:
Q: Regex match optional set of characters not working I'm trying to capture the username from these lines:
title="user1 is online now">user1
title="user2 is online now">user2

With this as the pattern:
title=".{1,16} is \w{5,8}? now">(?:)(?<text>.+?)(?:)?

But it's only capturing user1.
The "font color" tag needs to be ignored, sometimes it's there sometimes it's not.
I'm struggling with this for hours now, what am I missing?

A: The following might work.

*

*Assume that username follows title=" and is followed by is on(or off)line

*capture that instance into capturing group 1

*use a back reference to find the last instance of username in the line

*capture that into named capturing group UserName

title="(\S+)(?= is (?:on|off)line).*(?<UserName>\k<1>)

If you wanted to, you could also capture the on or off line status.

A: For those examples this should work:
title="\S+\sis\s(?:on|off)line\snow">(?:]+>)?(.*?)

A: You can use the following regex:
<[^>]*>(user\d+)<[^>]*>


text:
Q: Syntax for DISTINCT query on one column in MS Query I have an Excel spreadsheet which I use as a relational database for my milk round. I query this database using MS Query in Excel (Mac 2011 Version) to generate my delivery routes. One of the columns is the customer address and I'd like to have this shown once per order i.e. have a distinct query for just this column while displaying multiple other rows. It's purely for cosmetic purposes to make the spreadsheet less cluttered.
The main spreadsheet I use as my database has column headings which I have screenshotted, complete with some sample data:

From this main spreadsheet I use MS Query to generate my delivery route which looks like this:

As you can see there is a lot of repeated data in the route generated from the query. What I'd like to do is have just one instance of the address per customer's order, it would help with the legibility of the route when opened in an iPad. I hide other columns that aren't really necessary to help in that regard.
*EDIT
From isolated's comments below, here's a screenshot of ideally how the data returned from the query should look:

I've manually deleted the repeated info in the name & address column to achieve the desired result. I've also hidden some columns that aren't really necessary and I use some conditional formatting rules to help distinguish each customer's order.
EDIT*
I have tried using a group by clause and the following window function but can't get it to work:
SELECT *
FROM (
    SELECT "All Orders"."Route ID",
          "All Orders".Name,
          "All Orders".Address
          ROW_NUMBER() OVER(PARTITION BY "All Orders".Address
                                ORDER BY "All Orders".Address DESC) AS row_number
    FROM "All Orders"
    ) AS rows
WHERE row_number = 1;

Whenever I try to run the query I get an error message regarding syntax. Hopefully someone can tell me where I'm going wrong!

A: I don't know MS Sql at all, but you could do something with a formula in excel. If you don't like this solution, simply put a comment below that you would still like a sql route and I can get you a query to try to adapt to ms sql.
Create another column and call it address2 (or several more columns if your address field is multiple columns).
Then use this/these formula and adjust as needed:
    Column F (address2): =IF(A2=A1,"",C2)
    Column G (town2): =IF(A2=A1,"",D2)

You can then hide columns C and D.
=============
U P D A T E
Here's a method that works in many dbms such as postgres, but I don't know how to adapt [rank() over (partition by...] to excel sql.
    select account,
    cust_name,
    item,
    case
        when prod_rank = 1 then address
        else ''
    end address
    from (
        select
        account,
        cust_name,
        item,
        address,
        rank() over (partition by account order by item) as prod_rank
        from table1
        )z
    order by account, item

I tried a few variations in excel sql and finally got this one to work.
    select a.Account,
    a.Name,
    a.Product,
    Iif(a.product = b.min_item,a.address,'') as [address]
    FROM table1 as a
    ,(
    select
    z.Account,
    min(z.Product) as min_item
    FROM table1 as z
    group by z.Account ) as b
    where b.account = a.Account
    order by a.account, a.product


text:
Q: "What goes in" vs "What do you put in"? My intiial question was - What would be best way to ask what the ingredients or components or resources that a particular item is made of?
But having spent some time on this today, Now I'm broadly curious on where either of these phrases are used/can be used.
PS: I'm not an native English speaker. Any help or information would be really helpful!


text:
Q: MIDI revisited 19.10 Rhythmbox I'd like to be able to play MIDI files through one of the default Ubuntu media players, preferably Rhythmbox. For some reason, clicking on a MIDI file in file manager launches "Videos". MIDI files are not video. Nevertheless, the MIDI file does not play and I am told to download a MIDI decoder. So I click on the button that says "Find in Ubuntu Software". This then opens the Ubuntu Software application which immediately greets me with a grey SAD FACE icon and no decoder is found. Well done.
How can I get Rhythmbox to play MIDI files? It is a multimedia audio player, no?


text:
Q: Manage Inventory Dataset Good Morning,
I have the following dataset:
print(df)

Date        Type of Operation     Quantity
01/01/17      Order                  5
01/01/17      Sale                   3
02/01/17      Sale                   1
02/01/17      Order                  5

I would like to create the following column:
print(df_1)

Date        Type of Operation     Quantity     Actual_Inventory
01/01/17      Order                  5                5
01/01/17      Sale                   3                2
02/01/17      Sale                   1                1
02/01/17      Order                  5                6

Any suggestion about how to code it using Python and pandas?
Thank you

A: You can multiple column Quantity by -1 if Sale and then use cumsum:
m = df['Type of Operation'] == 'Sale'
df['Actual_Inventory'] = df['Quantity'].mask(m, df['Quantity'] * -1).cumsum()

Another solution:
a = (df['Type of Operation'] == 'Sale').map({True:-1, False:1})
df['Actual_Inventory'] = df['Quantity'].mul(a).cumsum()

print (df)
       Date Type of Operation  Quantity  Actual_Inventory
0  01/01/17             Order         5                 5
1  01/01/17              Sale         3                 2
2  02/01/17              Sale         1                 1
3  02/01/17             Order         5                 6


text:
Q: How to get session value in code file while session is created in httphandler How to get session value in code file while session is created in httphandler .it gives error like Object reference not set to an instance of an object.

A: The session is connected with a page request, to work is require to read the cookie of the user from the browser, or the url in case that is with out cookies.
So in the asp.net session if you do not have the httphandler, you can not have the session, because you can not know who is calling and see the page at that time.
Maybe in a custom solution session, you can send the session id to some other code with out the httphandler and use that id to read the session data, but the asp.net did not give this option.


text:
Q: Plugin Shortcode value in post Theme was output with function get_post_meta(get_the_ID(), 'some_value', true); when I try with die(print_r()); function there have some array containing values such as
[item_ticket_tailor] => Array
        (
            [0] => [custom_event id="3106" ][custom_ticket id="3220" show_price="true"]
        )

Question is How can I get custom_ticket value with get_post_meta() function

A: shortcode_parse_atts

Accepts a string of shortcode attributes and returns an associative array of key/value pairs.

// UNABLE TO TEST THIS
// $value = get_post_meta(get_the_ID(), 'some_value', true);
// $sc = $value [ 'item_ticket_tailor' ][ 0 ];

// TEST DATA - assuming the data is a string
$sc = '[custom_event id="3106" ][custom_ticket id="3220" show_price="true"]';

// pad some elements for a better parse
$sc = str_replace("[", " [ ", $sc);
$sc = str_replace("]", " ] ", $sc);

// convert the string shortcode to an array
$array = shortcode_parse_atts($sc);

// the last id is the winner, so custom_event id won't show here
// only custom_ticket id
echo $array[ 'id' ]; // 3220

ALTERNATE
$sc = '[custom_event id="3106" ][custom_ticket id="3220" show_price="true"]';

// split up the shortcodes
$sc = str_replace("]", " ", $sc);
$sc = str_replace("[", "[", $sc);
$shorts = array_filter(explode('[', $sc));

$custom_event_id = false;

// loop through each one
foreach($shorts as $short) {

    // get the individual attributes of the shortcode
    $atts = shortcode_parse_atts($short);

    // if the first item in the parsed array is `custom_ticket` then get the id
    if($atts[ 0 ] === 'custom_ticket') {
        $custom_event_id = $atts [ 'id' ];
        break;
    }
}

echo $custom_event_id; // 3220


text:
Q: alasset showing wrong time [asset valueForProperty:ALAssetPropertyDate]);

is showing wrong time, its showing minutes correctly but hour is 5 less from current.
But my device is showing correct time in status bar.

A: The call [asset valueForProperty:ALAssetPropertyDate] returns in NSDate. An NSDate object has the timeZone encoded in it.
To display an NSDate as NSString you should make use of an NSDateFormatter.
NSDate *date = [asset valueForProperty:ALAssetPropertyDate];

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *dateString = [dateFormatter stringFromDate:date];

[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *timeString = [dateFormatter stringFromDate:date];


text:
Q: How can I use a widescreen resolution in KMQuake2? I recently tried KMQuake2 (Knightmare Quake II) and it works very well for playing Quake 2.
However, it doesn't support widescreen resolutions (16:9), like 1920 x 1080 - it only supports 4:3 resolutions, like 1280x1024, 1400x1050, 1600x1200, etc.
Is there any any way to run KMQuake2 in a widescreen resolution?
Additionally, the KMQuake2 homepage doesn't have any support page or contact, any idea how I can contact the author so I can send a feature request?

A: To set a widescreen resolution, you will need to manually define a custom resolution for the game to run at. This will require editing the games configuration files.
First of all, you need to make sure the configuration files exist - this is done by starting each game (and each expansion if you have any) at least once, and then exiting.
Inside your Quake 2 folder in the "baseq2" folder, edit the file kmq2config.cfg and find the following lines:
set r_customheight "xxxx"
set r_customwidth "xxxx"
Change these two lines (the xxxx) to define the resolution you wish to run at. For example, if you want to use 1920x1080, set r_customheight to "1080" and r_customwidth to "1920". Be careful not to get these the wrong way around.
Then, find this line:
set r_mode "x"
This is the line that defines which built in resolution option is active. Set this to "-1" to enable your custom resolution.
If you find after making these changes that your field of view is weird or not how you'd like it, find the following lines to adjust your FOV:
set cl_widescreen_fov "x"
Set this to "0" to disable the FOV auto-adjust. Then, find this line:
set fov "x"
Change this to the FOV (in degrees) that you want, save your configuration file, and run the game. If you need assistance working out what field of view you should be using at your resolution, you can use the Field Of View Calculator on the Widescreen Gaming Forums to work it out for you.


text:
Q: how to show pyspark df with large columns I have big pyspark df, with many columns and I need show it correctly. I don't need vertical.
Is there way to show with scrolling?

A: Just add:
from IPython.core.display import HTML
display(HTML("<style>pre { white-space: pre !important; }</style>"))

And execute df.show(),  you will get the scrollbar.

A: Try with display(sparkDF) else the best workaround is
sparkDF.limit(5).toPandas().head()


text:
Q: How can I tell my Linux installation to handle the brightness ketys with ACPID? I want to manually control my brightness keys making a event on /etc/acpi/events.
Only that there is a problem, when I press the brightness up/down keys, the brighness changes (I think that the BIOS is changing it) before my script is called. I tried to change LINUX_CMDLINE but I don't know how to tell the system to handle the brightness.


text: Q: CCavenue payment gateway integration in ASP.NET MVC4 Has any one have integrated ccavenue payment gateway in asp.net mvc4, actually they are providing a package whose .NET version is 3.5 and i have developed an ecommerce website using .NET version 4.5? please help me out with this problem.


text:
Q: Prove the connected components are uncountably many
Let $G$ a graph with vertices all the points in $\mathbb{R}^2$. An edge exists if and only if the distance between two points is a rational number. Prove that the connected components are uncountably many.

A: I think there is only one connected component of this graph.  Take any two points $P$, $Q$ in $\mathbb{R{^2}}$.  If the distance between them is rational, then there is an edge directly connecting them.  If the distance between them is irrational, say $d$, then choose a rational number, $r$, between $\frac{d}{2}$ and $d$.  Draw circles of radius $r$ around each of $P$ and $Q$.  These two circles will intersect at (at least one) point $S$.  There is an edge from $P$ to $S$ and from $Q$ to $S$, so $P$ and $Q$ are in the same component of the graph.


text:
Q: How to reuse the result from spark stream? How can we use the value inside the map, it seems the values not being filled.
  val goalScore = rawScore.transform(rdd=>{
        val minMax = rdd.flatMap(x=>{
          x.behaviorProfileType match {
            case Some("mapper") => Some((x.sourceType, x.targetType, "mapper"), x)
            case Some("non-mappe") => Some((x.sourceType, x.targetType, "non-mapper"), x)
            case _ => None
          }
        })
        .reduceByKey(reduceMinMax(_, _))
        .collectAsMap()

        rdd.map(x => (populateMinMaxWindowGoalScore(x, minMax)))
      })

Why minMax is always empty inside populateMinMaxWindowGoalScore function? rawScore is a DStream.


text:
Q: React infinite loop in useEffect() I have a useEffect() which should be called once but continuously it is calling the getStories method.
const [pageNo, setPageNo] = useState(1);
const [recordsPerPage, setrecordsPerPage] = useState(5);
const { jwt } = useSelector((state: StateParams) => state.account);

useEffect(() => {
  if (jwt) {
    dispatch(
      getStories({ token: jwt, pageNo: pageNo, recordsPerPage: recordsPerPage })
    );
  }
}, []);

UPDATED: I feel flatlist is causing
<FlatList
                    style={{
                        marginTop: 14,
                        alignSelf: "stretch"
                    }}
                    data={Items}
                    renderItem={renderItem}
                    keyExtractor={item => item.id}
                />
const renderItem = useCallback(({ item } : {id: string}) => {
        console.log({item})
        const Section = Components[item.id]
        return (<Section {...props}/>)
    }, [Items])


text:
Q: Doctrine2: What is wrong with the association between these entities? I am trying to work through simple examples to see all the changes in Doctrine2.
Please take a look at the following entity snippets:
VCat.php
namespace Application\Models;

/**
 * @Entity
 * @Table(name="v_cat")
 */
class VCat
{
    /**
     * @Id @Column(type="bigint")
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @OneToMany(targetEntity="VScat", mappedBy="vCat")     )
     */
    private $vScats;

namespace Application\Models;

VScat.php
namespace Application\Models;
/**
 * @Entity
 * @Table(name="v_scat",indexes={@index(name="FK_v_scat",columns={"vcatid"})})
 */
class VScat
{
    /**
     * @Id @Column(type="bigint")
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ManyToOne(targetEntity="VCat", inversedBy="vScats")
     * @JoinColumn(name="vcatid", referencedColumnName="id")
     */
    private $vCat;

vcatid is the Foreign Key column in table v_scat
This is the query I am trying to run:
$categories = Zend_Registry::get('em')
        -> createQuery('select c.name, sub.name as sub_name from \Application\Models\VCat c JOIN c.VScat sub WHERE sub.active = 1 and c.active = 1 and c.id = sub.vcatid')
        -> getResult();

And this is the error:
(string:130) [Semantical Error] line 0, col 69 near 'sub WHERE sub.active': Error: Class Application\Models\VCat has no association named VScat

It seems right, but I am obviously missing something.
UPDATE Now I get this error, which refers to the table column name in mysql. Is that incorrect? I thought I needed to tell Doctrine somehow that this property belongs to this field in the DB.
 Error: Class Application\Models\VScat has no field or association named vcatid

A: It's the property on VCat you need to reference not the entity type.
JOIN c.VScat sub

should be:
JOIN c.vScats sub


text:
Q: Pandas - filter rows with same value in one column and multiple values in another column based on the existence of a value in the latter column I have the following base table that I would like to separate out into a has guava table and a does not have guava table. I'm thinking of using a flag to get the intermediate table below but not sure where to go from there.
base table
user_id fruit
user1   passionfruit
user1   guava
user1   banana
user2   orange
user2   coconut
user3   guava
user4   melon

has guava
user_id fruit
user1   passionfruit
user1   guava
user1   banana
user3   guava

does not have guava
user_id fruit
user2   orange
user2   coconut
user4   melon

intermediate table
user_id fruit        has_guava
user1   passionfruit 0
user1   guava        1
user1   banana       0
user2   orange       0
user2   coconut      0
user3   guava        1
user4   melon        0

A: Without groupby check isin
out = df[df.user_id.isin(df.loc[df.fruit.isin(['guava']),'user_id'])]
Out[322]:
  user_id         fruit
0   user1  passionfruit
1   user1         guava
2   user1        banana
5   user3         guava

A: Try groupby then filter.
df_ = (df.
       groupby('user_id').
       filter(lambda group: group['fruit'].eq('guava').any())
)

print(df_)

  user_id         fruit
0   user1  passionfruit
1   user1         guava
2   user1        banana
5   user3         guava


text:
Q: NSOperation and NSURLConnection mystified I am trying to download multiple images from some server using NSOperation and NSOperationQueue.  My main question is what is the difference between the code snippet below, and this link http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/, performance wise?  I prefer the second solution, because we have a lot more control over the operations, it is a lot cleaner, and if a connection fails you can handle it properly.
If I try to download about 300 images from a server with the code below, my app will have a pretty big delay, and if I launch the app, and go to the home screen immediately, then go back into the app, I will crash, because there wasn't wasn't enough time for the app to become active again.  If I uncomment [queue setMaxConcurrentOperationCount:1], the user interface is responsive and it won't crash if it enters the background and returns to the foreground.
But if I implement something similar to the link above, I don't need to worry about setting maxConcurrentOperationCount, the default value is fine.  Everything is responsive, no crashing, and it seems like all the queue gets completed faster.
So this brings me to my second question, why does [queue setMaxConcurrentOperationCount:1] have such a big affect in my code below?  From the documentation, I thought that leaving the maxConcurrentOperationCount at its default value was fine, and that just tells the queue to decide what the best value should be based on certain factors.
This is my first post on Stack Overflow so hopefully this makes sense, thanks for any help!
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//[queue setMaxConcurrentOperationCount:1];

for(NSURL *URL in URLArray) {
    [queue addOperationWithBlock:^{
        NSHTTPURLResponse *response = nil;
        NSError *error = nil;
        NSData * data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:&response error:&error];

        if(!error && data) {
            [data writeToFile:path atomically:YES];
        }
    }];
}

A: I'm going to tackle these in reverse order. You ask:

So this brings me to my second question, why does [queue setMaxConcurrentOperationCount:1] have such a big affect in my code below? From the documentation, I thought that leaving the maxConcurrentOperationCount at its default value was fine, and that just tells the queue to decide what the best value should be based on certain factors.

With NSURLConnection, you cannot have more than four or five connections downloading concurrently. Thus, if you don't set maxConcurrentOperationCount, the operation queue doesn't know you're dealing with NSURLConnection and therefore when you add 300 NSOperation objects to your queue, the queue will try to start a very large number of them (64-ish, I think) concurrently. But since only 4 or 5 NSURLConnection requests can run concurrently, the rest of them that were started by the queue will wait until one of the four or five possible connections are available, and with so many download requests, it's quite likely that many of them will time out and fail.
By using maxConcurrentOperationCount of 1, that applies a rather heavy-handed solution to this problem, only running one at a time. I'd suggest a compromise, namely a maxConcurrentOperationCount of 4, which enjoys a degree of concurrency (and huge performance gain), but not so many that we risk having connections time out and fail.
Going back to Dave Drubin's NSOperation, his is great improvement over your synchronousRequest wrapped in an operation. Having said that, he's neglected to address a fairly basic feature of concurrent requests, namely cancelation. You should include a check to see if the operation has been canceled, and if so, cancel the connection:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if ([self isCancelled]) {
        [connection cancel];
        [self finish];
        return;
    }

    [_data appendData:data];
}

Likewise, when he should be doing that in the start method, too.
- (void)start
{
    // The Apple docs say "Always check for cancellation before launching the task."

    if ([self isCancelled]) {
        [self willChangeValueForKey:@"isFinished"];
        _isFinished = YES;
        [self didChangeValueForKey:@"isFinished"];
        return;
    }

    if (![NSThread isMainThread])
    {
        [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
        return;
    }

    NSLog(@"opeartion for <%@> started.", _url);

    [self willChangeValueForKey:@"isExecuting"];
    _isExecuting = YES;
    [self didChangeValueForKey:@"isExecuting"];

    NSURLRequest * request = [NSURLRequest requestWithURL:_url];
    _connection = [[NSURLConnection alloc] initWithRequest:request
                                                  delegate:self];
    if (_connection == nil)
        [self finish];
}

I might suggest other stylistic improvements to Dave's example, but it's all minor stuff, and I think he got most of the big picture stuff spot on. The failure to check for cancelation was the only obvious big issue that leapt out at me.
Anyway, for discussion of concurrent operations, see the Configuring Operations for Concurrent Execution section of the Concurrency Programming Guide.
Also, when testing huge downloads like these, I'd encourage you to stress test your app with the Network Link Conditioner (available for the Mac/simulator as a download available under "Hardware IO tools" on the "Xcode" - "Open Developer Tool" - "More Developer Tools"; if you enable your iOS device for development, there is also a network link conditioner setting under "General" - "Developer" in the Settings app). A lot of these timeout-related problems don't manifest themselves when we test our apps in our highly optimized scenario of our development environment. It's important to use the network link conditioner to simulate less than ideal, real-world scenarios.

A:
I prefer the second solution, because we have a lot more control over the operations

If you refer to your own solution, then actually the opposite is the case:
Due to the synchronous convenience method sendSynchronousRequest: you have basically no way to accomplish more practical requirements, like authentication, better error handling, and customized data handling, and many other features usually required in any app which is not a demo or toy app.
The bummer however is the lack of the ability to cancel operations. You cannot cancel a block operation once it has started. And it's also not clear how you want to cancel the "for loop". So, once the loop is started you cannot stop it.
You may want to search for more sophisticated (and more modern) approaches in the web and on SO.

A: When the queue's MaxConcurrentOperationCount is > 1 there is a good chance that the queue is getting locked and unlocked by the operations completing while you are still adding more jobs to the queue however when you set it to 1, the queue gets more completely full before the jobs start to work off, meaning the looping of the URLArray finishes faster (avoiding being 'deadlocked' constantly).
If I recall the NSOperationQueue api correctly you can "suspend" and "resume" it... I recommend you set it to "suspended" until you are done adding all the jobs, then set it resumed


text:
Q: Two past tenses in the same phrase? I have a quick question for you. I've seen many people get their answers on this site so I hope you can help me. Is the following sentence correct?

"I lost my wallet when I visited Mexico."

Basically I don't know if I'm allowed to use 2 verbs conjugated like this in the same sentence. To avoid this I'd use "I lost my wallet when VISITING Mexico" but the question I mentioned earlier is still bugging me. What do you think?

A: I'm not certain why you think it's wrong to have two (or more) past-tense verbs in the same sentence.  How else you could construct simple compound sentences about things that happened in the past?
Examples:

I left my home when I was fifteen.
She spilled her drink, then she dropped her phone.
I thought it was the butler who killed Lord Graves, but it was really the cook who did the deed.

"I lost my wallet when visiting Mexico" is fine, but it might be better to use while instead of when.  "When visiting X" is more often used to refer to the general experience of going to a place, and not any specific instance when you were there:

When visiting San Diego, don't plan your trip in June as the weather is often cool and cloudy.
When visiting California, be sure not to bring any fresh fruit or vegetables as these may be confiscated at the border.


text:
Q: How to configure Spring data SolrCloud connection with Basic Authentication I have configure Solr 6.2.1 as SolrCloud. Later I have Configured Basic Authentication.
I am going to configure Spring data solr 2.0.4.RELEASE with Solrj 6.2 and this is my code:
@Configuration
@EnableSolrRepositories(basePackages = { "ir.saeed.server.solr" }, multicoreSupport = true)

public class SearchContext {

    @Value("${solr.host}")

    private String host;

    @Value("${solr.port}")

    private Integer port;

    @Value("${solr.username}")

    private String username;

    @Value("${solr.password}")

    private String password;

    @Value("${zkHost}")

    private String zkHost;

    @Value("${solr.coreName}")

    private String collectionName;

    @Bean

    public SolrTemplate solrTemplate() {

        return new SolrTemplate(solrClientFactory());

    }

    @Bean

    public BasicCredentialsProvider credentialsProvider() {

        BasicCredentialsProvider provider = new BasicCredentialsProvider();

        provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        return provider;

    }

    @Bean

    public SolrClientFactory solrClientFactory() {

        return new HttpSolrClientFactory(solrClient(), "", credentialsProvider().getCredentials(AuthScope.ANY), "BASIC");

    }

    @Bean

    public SolrClient solrClient() {

        return new CloudSolrClient.Builder().withZkHost(zkHost).build();

    }

}

But when i run my web application this Exception occures:
 10:51:48,110 org.springframework.data.solr.UncategorizedSolrException: nested exception is java.lang.NullPointerException

 10:51:48,111   at org.springframework.data.solr.core.SolrTemplate.execute(SolrTemplate.java:172)

 10:51:48,111   at org.springframework.data.solr.core.SolrTemplate.executeSolrQuery(SolrTemplate.java:509)

 10:51:48,111   at org.springframework.data.solr.core.SolrTemplate.query(SolrTemplate.java:504)

 10:51:48,111   at org.springframework.data.solr.core.SolrTemplate.doQueryForPage(SolrTemplate.java:338)

 10:51:48,111   at org.springframework.data.solr.core.SolrTemplate.queryForPage(SolrTemplate.java:350)

How can I resolve the issue?
I think my Configuration is incorrect

A: I found a workaround for those who has same issue
Extends your own HttpSolrClientFactory. the problem caused by LBHttpSolrClient httpClient not being setup properly. correct setup should be like the following block  if (solrClient instanceof LBHttpSolrClient) {...}
AuthHttpSolrClientFactory.java
@SuppressWarnings("deprecation")
public class AuthHttpSolrClientFactory extends HttpSolrClientFactory {
public AuthHttpSolrClientFactory(SolrClient solrClient, String core, Credentials credentials, String authPolicy) {
    super(solrClient, core, credentials, authPolicy);
    Assert.notNull(solrClient, "solrClient must not be null");
    if (authPolicy != null) {
        Assert.hasText(authPolicy);
    }
    appendBasicAuthentication(credentials, authPolicy, this.getSolrClient());
}

private void appendBasicAuthentication(Credentials credentials, String authPolicy,  SolrClient solrClient) {
    if( credentials != null) {
        if (solrClient instanceof HttpSolrClient) {
            HttpSolrClient httpSolrClient = (HttpSolrClient) solrClient;
            if (assertHttpClientInstance(httpSolrClient.getHttpClient())) {
                AbstractHttpClient httpClient = (AbstractHttpClient) httpSolrClient.getHttpClient();
                httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
                httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Arrays.asList(authPolicy));
            }
        }
        else if (solrClient instanceof LBHttpSolrClient) {
            LBHttpSolrClient lbhttpSolrClient = (LBHttpSolrClient) solrClient;
            if (assertHttpClientInstance(lbhttpSolrClient.getHttpClient())) {
                AbstractHttpClient httpClient = (AbstractHttpClient) lbhttpSolrClient.getHttpClient();
                httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
                httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Arrays.asList(authPolicy));
            }
        }
    }
}

private boolean assertHttpClientInstance(HttpClient httpClient) {
    Assert.isInstanceOf(AbstractHttpClient.class, httpClient,
            "HttpClient has to be derivate of AbstractHttpClient in order to allow authentication.");
    return true;
}

}
beans-solr.xml
<solr:solr-client id="solrClient" url="${solr.host}" />
<bean id="credentials" class="org.apache.http.auth.UsernamePasswordCredentials">
    <constructor-arg type="java.lang.String" value="${solr.credentials}"/>
</bean>
<bean id="solrClientFactory" class="com.example.solr.AuthHttpSolrClientFactory" scope="singleton">
    <constructor-arg ref="solrClient" />
    <constructor-arg name="core">
        <null />
    </constructor-arg>
    <constructor-arg ref="credentials" />
    <constructor-arg type="java.lang.String" value="BASIC"/>
</bean>
<bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate" scope="singleton">
    <constructor-arg ref="solrClientFactory" />
    <constructor-arg name="requestMethod">
        <value type="org.springframework.data.solr.core.RequestMethod">POST</value>
    </constructor-arg>
</bean>

A: There are several reasons why your code is not working, but they are lied mainly to spring-data-solr missing features.
First of all spring-data-solr version 2.0.4 does not have support for Solr 5 (cloud) features.
So this is the reason why you are getting the NullPointerException in the method org.springframework.data.solr.server.support.SolrClientUtils#cloneLBHttpSolrClient
I've tried to see whether it the scenario exposed by you works with the latest SNAPSHOT (2.1.0-SNAPSHOT) of spring-data-solr and after a few modifications on the SolrContext spring configuration class :
@Configuration
@EnableSolrRepositories(basePackages = {"com.acme.solr"})
// notice that the multicoresupport is left false
// see org.springframework.data.solr.repository.config.SolrRepositoryConfigExtension#postProcess(org.springframework.beans.factory.support.BeanDefinitionBuilder, org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource) for details
public class SolrContext {

    @Bean
    public Credentials credentials(@Value("${solr.username}") String username, @Value("${solr.password}") String
            password) {
        return new UsernamePasswordCredentials(username, password);
    }

    @Bean
    public BasicCredentialsProvider credentialsProvider(Credentials credentials) {
        BasicCredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, credentials);

        return provider;
    }

    @Bean
    public SolrClientFactory solrClientFactory(SolrClient solrClient, Credentials credentials) {
        return new HttpSolrClientFactory(solrClient, "", credentials, "BASIC");

    }

    // create a solrtemplate bean, so that it is used in
    // org.springframework.data.solr.repository.support.SolrRepositoryFactoryBean#doCreateRepositoryFactory method
    // for using org.springframework.data.solr.repository.support.SolrRepositoryFactory#SolrRepositoryFactory(org.springframework.data.solr.core.SolrOperations) constructor
    @Bean
    public SolrTemplate solrTemplate(SolrClientFactory solrClientFactory){
        return new SolrTemplate(solrClientFactory);
    }

    @Bean
    public CloudSolrClient solrClient(@Value("${zkHost}") String zkHost) {
        CloudSolrClient solrClient = new CloudSolrClient.Builder().withZkHost(zkHost).build();
        solrClient.setDefaultCollection("gettingstarted");
        return solrClient;
    }
}

I still received a 401 authentication issue when performing a solr request (when the basic authentication was enabled on solr).
In a vanilla solrj application, this is how you'd make an authenticated request:
    CloudSolrClient solr = new CloudSolrClient.Builder()
            .withZkHost("localhost:9983")
            .build();

    SolrQuery query = new SolrQuery();
    query.setQuery("*:*");
    SolrRequest<QueryResponse> req = new QueryRequest(query);
    req.setBasicAuthCredentials("solr", "SolrRocks");
    QueryResponse rsp = req.process(solr, "gettingstarted");

    System.out.println("numFound: " + rsp.getResults().getNumFound());

When looking whether the method SolrRequest#setBasicAuthCredentials(String, String) is used in the code of spring-data-solr I didn't notice anywhere this method being used. So, it is very likely, that this feature is not implemented yet not even on the SNAPSHOT build of the spring-data-solr.
I've created a feature request on spring-data-solr project to add support for this functionality.

A: Yes, your configuration seems incorrect. I had same issue like yours
I would like to use apache solr version 6.6.0 and spring data solr version 2.0.8 (bought by spring boot starter). It turned out that the version from spring data solr doesn't have support for apache solr version > 5, because when you traced
at org.springframework.data.solr.core.SolrTemplate.execute(SolrTemplate.java:172), it's very clear that when the solrTemplate is going to createClientForCore, it will clone from the cloudSolrClient that we have been configured

the problem is in String zkHost = (String)readField(solrClient, "zkHost");
* it will return null since in apache solr version > 5, the zkHost is stored in "clusterStateProvider" not in the same level as "cloudSolrClient"
Solved:
If you want keep using spring data solr version 2, you need to downgrade the apache solr version

A: Had the same issue usind Solr 7.7 and spring-boot-starter-data-solr 2.1.14 (uses spring-data-solr-4.0.17.RELEASE)
Tried a few ways, including creating custom HttpSolrClientFactory. It works but actually makes 2 calls to Solr and the first one returns
401 Unauthorized.
I fix the problem extending the CloudSolrClient (trying to do correct auth as it described in Basic Auth with SolrJ)
It makes only one call to Solr and uses Basic auth
public class BasicAuthCloudSolrClient extends CloudSolrClient {

private final Credentials credentials;

/**
 * Create a new client object that connects to Zookeeper using BASIC Authentication and is always aware
 * of the SolrCloud state. If there is a fully redundant Zookeeper quorum and
 * SolrCloud has enough replicas for every shard in a collection, there is no
 * single point of failure. Updates will be sent to shard leaders by default.
 *
 * @param builder a {@link BasicAuthCloudSolrClient.Builder} with the options used to create the client.
 */
protected BasicAuthCloudSolrClient(Builder builder) {
    super(builder);
    this.credentials = builder.credentials;
}

@Override
public QueryResponse query(String collection, SolrParams params, SolrRequest.METHOD method)
        throws
        SolrServerException, IOException {
    QueryRequest request = new QueryRequest(params, method);
    request.setBasicAuthCredentials(credentials.getUserPrincipal().getName(),
            credentials.getPassword());

    return request.process(this, collection);
}

/**
 * Constructs {@link BasicAuthCloudSolrClient} instances from provided configuration.
 */
public static class Builder extends CloudSolrClient.Builder {
    protected Credentials credentials;

    /**
     * @deprecated use other constructors instead.  This constructor will be changing visibility in an upcoming release.
     */
    @Deprecated
    public Builder() {
    }

    /**
     * Provide a series of ZK hosts which will be used when configuring {@link CloudSolrClient} instances.
     *
     * @param zkHosts     a List of at least one ZooKeeper host and port (e.g. "zookeeper1:2181")
     * @param credentials a credentials to connect to Solr.
     */
    public Builder(List<String> zkHosts, Credentials credentials) {
        super(zkHosts, empty());
        this.credentials = credentials;
    }

    /**
     * Create a {@link CloudSolrClient} based on the provided configuration.
     */
    public BasicAuthCloudSolrClient build() {

        if (Objects.isNull(credentials)) {
            throw new IllegalArgumentException(
                    "Credentials must be provided to initialize BasicAuthCloudSolrClient");
        }
        if (stateProvider == null) {
            if (!zkHosts.isEmpty()) {
                stateProvider = new ZkClientClusterStateProvider(zkHosts, zkChroot);
            } else if (!this.solrUrls.isEmpty()) {
                try {
                    stateProvider = new HttpClusterStateProvider(solrUrls, httpClient);
                } catch (Exception e) {
                    throw new RuntimeException(
                            "Couldn't initialize a HttpClusterStateProvider (is/are the "
                                    + "Solr server(s), " + solrUrls + ", down?)", e);
                }
            } else {
                throw new IllegalArgumentException("Both zkHosts and solrUrl cannot be null.");
            }
        }
        return new BasicAuthCloudSolrClient(this);
    }

    @Override
    public BasicAuthCloudSolrClient.Builder getThis() {
        return this;
    }
}

Configuration looks like this:
@Bean
public Credentials solrCredentials(@Value("${solr.username}") String username, @Value("${solr.password}") String
        password) {
    return new UsernamePasswordCredentials(username, password);
}

@Bean
public SolrClientFactory solrClientFactory(SolrClient solrClient,
        Credentials solrCredentials) {
    return new HttpSolrClientFactory(solrClient, solrCredentials, AuthSchemes.BASIC);
}

@Bean
public SolrTemplate solrTemplate(SolrClientFactory solrClientFactory){
    return new SolrTemplate(solrClientFactory);
}

@Bean
public SolrClient solrClient(Credentials solrCredentials) {
    if (isNotEmpty(properties.getZkHosts())) {

        BasicAuthCloudSolrClient solrClient =
                new BasicAuthCloudSolrClient.Builder(properties.getZkHosts(), solrCredentials).build();
        solrClient.setDefaultCollection(properties.getCollection());
        return solrClient;
    } else {
        throw new IllegalStateException("ZkHosts is required for application startup.");
    }
}


text:
Q: How to style subclassed components in WPF I have a subclass of TextBox in WPF/XAML and I wish to apply the same styles to it as I do with all my other TextBox instances. I have the following styles defined
<Style TargetType="TextBox" x:Key="basicTextBox" >
    <Setter Property="Controls:TextBoxBehaviours.UpdateWhenEnterPressed" Value="True"/>
    <Setter Property="Controls:TextBoxBehaviours.SelectAllWhenEnterPressed" Value="True"/>
    <Setter Property="Controls:TextBoxBehaviours.SelectAllOnFocus" Value="True"/>
</Style>

and a class TextBoxBehaviours to implement these
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Reactive.Linq;

namespace Weingartner.Controls
{
    public static class TextBoxBehaviours
    {

        static TextBoxBehaviours()
        {}

        #region Binding Support
        private static Dictionary<Tuple<TextBox,string>, IDisposable> Bindings
            = new Dictionary<Tuple<TextBox,string>, IDisposable>();

        private static void Bind(TextBox tb, string key, IDisposable d)
        {
            Bindings[Tuple.Create(tb, key)] = d;
        }

        private static void UnBind(TextBox tb, string key)
        {
            var t = Tuple.Create(tb, key);
            if (Bindings.ContainsKey(t))
            {
                var d = Bindings[t];
                Bindings.Remove(t);
                d.Dispose();
            }
        }
        #endregion

        static UIPropertyMetadata CreateMeta<T>(bool defaultValue, Action<T,DependencyPropertyChangedEventArgs> fn)
        where T : DependencyObject
        {
            return new UIPropertyMetadata(defaultValue, (o, e) =>{
                var t = o as T;
                if (t == null)
                {
                    return;
                }
                fn(t, e);
            });
        }

        #region Update When Enter Pressed
        public static readonly DependencyProperty
            UpdateWhenEnterPressedProperty =
            DependencyProperty.RegisterAttached
            ( "UpdateWhenEnterPressed"
            , typeof(bool)
            , typeof(TextBoxBehaviours)
            , CreateMeta<TextBox>(false, SetupUpdateOnEnterPressed));

        public static void
            SetUpdateWhenEnterPressed
            ( TextBox dp
            , bool value)
        {
            dp.SetValue(UpdateWhenEnterPressedProperty, value);
        }

        public static bool
            GetUpdateWhenEnterPressed
            ( TextBox dp)
        {
            return (bool)dp.GetValue(UpdateWhenEnterPressedProperty);
        }

        private static void
            SetupUpdateOnEnterPressed
            ( TextBox element
            , DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                var sub = element
                    .PreviewKeyDownObserver()
                    .Where(x=>x.EventArgs.Key==Key.Enter)
                    .Subscribe(x=>DoUpdateSource(element));

                Bind(element, "KeyEnter", sub);
            }else{
                UnBind(element, "KeyEnter");
            }

        }

        static void DoUpdateSource(TextBox source)
        {
            BindingExpression binding = BindingOperations.GetBindingExpression(source, TextBox.TextProperty);

            if (binding != null)
            {
                binding.UpdateSource();
            }
        }
        #endregion
        #region SelectAll When Enter Pressed
        public static readonly DependencyProperty
            SelectAllWhenEnterPressedProperty =
            DependencyProperty.RegisterAttached
            ( "SelectAllWhenEnterPressed"
            , typeof(bool)
            , typeof(TextBoxBehaviours)
            , CreateMeta<TextBox>(false, SetupSelectAllOnEnterPressed));

        public static void
            SetSelectAllWhenEnterPressed
            ( TextBox dp
            , bool value)
        {
            dp.SetValue(SelectAllWhenEnterPressedProperty, value);
        }

        public static bool
            GetSelectAllWhenEnterPressed
            ( TextBox dp)
        {
            return (bool)dp.GetValue(SelectAllWhenEnterPressedProperty);
        }

        private static void
            SetupSelectAllOnEnterPressed
            ( TextBox element
            , DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                var sub = element
                    .PreviewKeyDownObserver()
                    .Where(x=>x.EventArgs.Key==Key.Enter)
                    .Subscribe(x=>element.SelectAll());

                Bind(element, "KeyEnterSelectAll", sub);
            }else{
                UnBind(element, "KeyEnterSelectAll");
            }

        }

        #endregion
        #region Select All On Focus
        public static readonly DependencyProperty
            SelectAllOnFocusProperty =
            DependencyProperty.RegisterAttached
            ( "SelectAllOnFocus"
            , typeof(bool)
            , typeof(TextBoxBehaviours)
            , CreateMeta<TextBox>(false, SetupSelectAllOnFocus));

        public static void
            SetSelectAllOnFocus
            ( TextBox dp
            , bool value)
        {
            dp.SetValue(SelectAllOnFocusProperty, value);
        }

        public static bool
            GetSelectAllOnFocus
            ( TextBox dp)
        {
            return (bool)dp.GetValue(SelectAllOnFocusProperty);
        }

        private static void
            SetupSelectAllOnFocus
            ( TextBox element
            , DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                Bind(element, "Focus", element.GotFocusObserver().Subscribe(x => element.SelectAll()));
            }else{
                UnBind(element, "Focus");
            }
        }
        #endregion

    }
}

in my XAML files I have been doing
<Style TargetType="TextBox" BasedOn="{StaticResource basicTextBox}"/>

and all following TextBoxes get the behviour I wish. Given my subclass is also a TextBox class I assumed that these would also get the behaviour but they don't. I tried being explicit by extending the styles so
<Style TargetType="TextBox" BasedOn="{StaticResource basicTextBox}"/>

<Style TargetType="Controls:EditForLength">
    <Setter Property="Controls:TextBoxBehaviours.UpdateWhenEnterPressed" Value="True"/>
    <Setter Property="Controls:TextBoxBehaviours.SelectAllWhenEnterPressed" Value="True"/>
    <Setter Property="Controls:TextBoxBehaviours.SelectAllOnFocus" Value="True"/>

</Style>

but I get an error that tells me the key for EditForLength
System.ArgumentException occurred
  HResult=-2147024809
  Message=Item has already been added. Key in dictionary: 'Weingartner.Controls.EditForLength'  Key being added: 'Weingartner.Controls.EditForLength'
  Source=mscorlib
  StackTrace:
       at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)
  InnerException:

So in summary behaviours installed via styles on a parent class do not propogate to the child class instances but when it is attempted to add another style targeting the child class there is some dictionary error.
Note I have tried the behaviours explicity on the instances of the EditForLength control they work fine. I just can't install the behaviours via styling.
UPDATE
Have discovered that I get the error even when all important bits
except the style declaration are commented out
        <!--<Style TargetType="TextBox" BasedOn="{StaticResource basicTextBox}"/>-->

        <Style TargetType="Controls:EditForLength">
            <!--
            <Setter Property="Controls:TextBoxBehaviours.UpdateWhenEnterPressed" Value="True"/>
            <Setter Property="Controls:TextBoxBehaviours.SelectAllWhenEnterPressed" Value="True"/>
            <Setter Property="Controls:TextBoxBehaviours.SelectAllOnFocus" Value="True"/>
             -->

        </Style>

A: About exception: it seems that you already added this style in dictionary (or its merged dictionaries) - try to search for it, I'm sure you will find a style with the same key.
About implicit styles: they are not applied to subclasses of target type (try to imagine if they are applied - if you have created implicit style for FrameworkElement - layout of a huge part of your controls will be broken)


text:
Q: tornado and postgresql I'm using demo from facebook's tornado
But I don't want to use MySQL and trying to replace it with PG
So I went ahead and modified like this :
define("port", default=8888, help="run on the given port", type=int)
define("pgsql_host", default="127.0.0.1:5432", help="blog database host")
define("pgsql_database", default="pgdb", help="blog database name")
define("pgsql_user", default="admin", help="blog database user")
define("pgsql_password", default="pgpass", help="blog database password")

and
        # Have one global connection to the blog DB across all handlers
    self.db = tornado.database.Connection(
        host=options.pgsql_host, database=options.pgsql_database,
        user=options.pgsql_user, password=options.pgsql_password)

But app just hangs when I run it, how to properly migrate it to PG?
Actually I get error after some time:
    Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/database.py", line 84, in __init__
    self.reconnect()
  File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/database.py", line 101, in reconnect
    self._db = MySQLdb.connect(**self._db_args)
  File "/usr/lib/pymodules/python2.7/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/MySQLdb/connections.py", line 187, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0")

Why is it connecting to MySQL?

A: Are you sure you can use it with different RDBMS including PostgreSQL?
It uses torndb package which is written to work with MySQL.
So i think that if you want to use it with PostgreSQL you should write your own torndb package for postgresql.
EDIT:
As you can see at Tornado Wiki you have to have postgresql wrapper (momoko or psycopg) there are some links for further study.
EDIT2: Momoko description:
 "An asynchronous Psycopg2 wrapper for Tornado."

A: tornado.database (which will be broken out of Tornado in 3.0) is a lightweight MySQL wrapper. It doesn't support anything other than MySQL.
The good news is, as @sufleR noted, you have some options. You can use pyscopg directly, or you can use momoko, an async wrapper for pyscopg.


text:
Q: Meteor JS Router.go redirect to the same page I have a problem, in my meteor app when I'm on a page say "test/two", I have a button called "All", now when I click this button I want my meteor app to reload whole "test/two" page with initial data from server (there are some filters and things you can change on "test/two").
The problem is that whether I use anchor or click event to redirect with Router.go meteor recognizes that I'm already on this page and does nothing.
Can I force meteor app to reload from the server the same page that I'm already on?

A: It's not easy as seems.
The problem is that if you do a full refresh of the page, you will get the page with the initial data, but you will lose the session.
Example:
.js
if (Meteor.isClient) {
    Session.setDefault('something', "other");
    console.log(Session.get('something'));
    Template.reload.events({
        'click #reload': function() {
            document.location.reload(true);
        },
        'click #change': function() {
            Session.set('something', 'else');
            console.log(Session.get('something'));
        }
    });
}

Router.route('/', function() {
    this.layout('layout');
    this.render('reload');
});

.html

    <title>Reload</title>

Reload test!

<template name="layout">
    {{> yield}}
</template>

<template name="reload">
    <button id ="change" type="button">Change Session</button>

    <input type="text">
    <input type="checkbox">
    <input type="checkbox" checked>
    <button id="reload" type="button">Reload</button>
</template>

I made some experiments with iron:router but I did not get any results.
A brute force idea can be save in a object the initial data, and if the user presses the "All" button you will restore the original data with a listener.
In addition I've found this, How do I reload the current iron:router route?, take a look, maybe it's useful.

A: Iron:Router is not necessary if you just want to reload the entire page, you can use pure JavaScript:
document.location.reload(true);


text:
Q: Python split a string using regex I would like to split a string by ':' and ' ' characters. However, i would like to ignore two spaces '  ' and  two colons '::'. for e.g.
text = "s:11011 i:11010 ::110011  :110010 d:11000"

should split into
[s,11011,i,11010,:,110011, ,110010,d,11000]

after following the Regular Expressions HOWTO on the python website, i managed to comeup with the following
regx= re.compile('([\s:]|[^\s\s]|[^::])')
regx.split(text)

However this does not work as intended as it splits on the : and spaces, but it still includes the ':' and ' ' in the split.
[s,:,11011, ,i,:,11010, ,:,:,110011, , :,110010, ,d,:,11000]

How can I fix this?
EDIT: In case of a double space, i only want one space to appear

A: Note this assumes that your data has format like X:101010:
>>> re.findall(r'(.+?):(.+?)\b ?',text)
[('s', '11011'), ('i', '11010'), (':', '110011'), (' ', '110010'), ('d', '11000')]

Then chain them up:
>>> list(itertools.chain(*_))
['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000']

A: >>> text = "s:11011 i:11010 ::110011  :110010 d:11000"
>>> [x for x in re.split(r":(:)?|\s(\s)?", text) if x]
['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000']

A: Use the regex (?<=\d) |:(?=\d) to split:
>>> text = "s:11011 i:11010 ::110011  :110010 d:11000"
>>> result = re.split(r"(?<=\d) |:(?=\d)", text)
>>> result
['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000']

This will split on:
(?<=\d) a space, when there is a digit on the left. To check this I use a lookbehind assertion.
:(?=\d) a colon, when there is a digit on the right. To check this I use a lookahead assertion.

A: Have a look at this pattern:
([a-z\:\s])\:(\d+)

It will give you the same array you are expecting. No need to use split, just access the matches you have returned by the regex engine.
Hope it helps!