Securing SSH on Linux Ubuntu

Question: How can I secure SSH access to a linux box running Ubuntu k for multiple users?
This server will be for a web app but I'm not sure how to evaluate the tools to perform this task. I have tried a few tools in the past but not sure how they stack up against each-other. How can I evaluate my SSH security and the tools and utilities that I would use to perform that securing?
Answer: What goals do you have in mind for your security? Who are you protecting this against?
Broad spectrum, use iptables to firewall port 22 against any unwanted IPs by specifically allowing the IPs you want, then blocking everything else.
You can also specify whether users can use passwords to log in, or whether they have to have certificates, which might be a good idea if you suspect people will try to break into others' accounts.
But for specifics, we've got to know what you're doing.
EDIT
OK, taking into account what you said below in the comments, you want to prevent unauthorized access to the machine. The second part, ensuring that your users don't do anything bad, is beyond the scope of this particular question, but is a worthy topic too. Broad, but worth asking.
The primary file that you need to edit is /etc/ssh/sshd_config and after each configuration change, you need to run /etc/init.d/sshd restart (or /etc/init.d/ssh if it's a debian/ubuntu system). When you're first learning how to configure ssh, it's a good idea to be logged in on the local console, since a misconfiguration will cut off your access.
Step 1: Make sure that root can't log in via ssh.
PermitRootLogin no

If you absolutely must have root logins, you can set it to "without-password", which requires the connecting user to present a certificate and be authenticated like that.
Step 2: Allow (or deny) any specific users that should (or shouldn't) have access
There are various configuration directives to do this, like DenyUsers, AllowUsers, DenyGroups, and AllowGroups. These take lists of users or groups separated by spaces.
One of the neat things is that you can specify user@host, so if you only want Bob to be able to connect form his home machine, you can say
AllowUsers email@example.com

Step 3: Explicitly permit public key authentication
PubkeyAuthentication yes

This is the default, but we want to ensure it takes effect, because we're going to disable the ability for users to type passwords in...
Step 4: Disable password authentication
Passwords can be stolen, overheard, or copied from the sticky note under your keyboard. Certificates are harder to do. Make sure that people can't use passwords thusly:
PasswordAuthentication no

Step 5: Make sure clients use modern protocols
Protocol 2

OpenSSH supports 2 protocols, called creatively, "1" and "2". "1" is old, allows things like DES encryption and other insecure things.
You're going to have to get your users putty certificates in order to connect now. The easiest way is to use PuttyGEN, which is available at the Putty site (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html).
Hope it helps!
Comment: I will be using putty and I have been using openSSH bust was wondering if there was a better way
Comment: If you're coming from a Windows machine, putty is perfectly fine, and openssh is the right server. Do you know what you're trying to protect against, or are you just looking for some good policies to put in place?
Comment: just want to keep hackers out of my system... I have changed my SSH port and what not to help but I want to make sure I have my bases covered.

Also, I don't want "other" users on my server to break anything.
Comment: Also, I'm trying to learn more about security for linux so if there is anything I can do to make this thing more secure the better.

Basically I want to protect against common problems that may arise.

I know this is not a precise as you would like, as there are thousands of ways to "hack" a system.

So for my scenario, as of right now, I want to keep my users accounts form being used by anyone other than who I gave permissions too and your generic hacker.
Comment: You should also install denyhosts IMHO it watches for login attempts and blocks traffic in /etc/hosts.deny
Comment: Thanks a ton this really help... I think I'm going to get a book on this stuff.

Excellent reply!
Comment: @MattSimmons Thank you for adding Step 4 for disabling password authentication! I wish that were the default everywhere!
Answer: you can try enforcing use of ssh keys or introduce a hardtoken (like yubikey)
moving ssh away from port 22 helps against script kiddies but will surely not defend you from someone, who targeted you as a victim.
Answer: For learning more about securing linux see the NSA guide at:
Guide to the Secure Configuration of Red Hat Enterprise Linux 5
It has some good sections on SSH, enforcing password lengths etc.
Comment: I would recommend turning off passwords altogether like MattSimmons suggests in Step 4 of [his answer](http://serverfault.com/a/93432/93109).
Answer: On top of everything the top poster said, there is a script called "Denyhosts" which will deny access to anything that authenticates badly three times, or, for a more IP Tables way to do the same thing:
http://dwm.me.uk/articles/2008/mitigating-ssh-attacks
Answer: In addition to everything @MattSimmons suggests in his excellent answer I would say that instead of managing iptables yourself, you may want to consider using:
fwknop - Single Packet Authorization and Port Knocking:

fwknop stands for the "FireWall KNock OPerator", and implements an
  authorization scheme called Single Packet Authorization (SPA). This
  method of authorization is based around a default-drop packet filter
  (fwknop supports both iptables on Linux systems and ipfw on FreeBSD
  and Mac OS X systems) and libpcap. SPA is essentially next generation
  port knocking.

That way you don't have to bother with things like fail2ban or other ssh blacklisting tools; instead you can avoid allowing anyone to even connect to your ssh port without first doing SPA.
Answer: You can take different actions like install deny hosts. That will block the ssh from one IP address after failed three tries. Blocked IP address will be listing in /ets/hosts.deny file and you can manually white-list using /etc/hosts.allow
Also let known useraccounts only to ssh into the host. You can do this by using pam.d module. You may add rule to /etc/pam.d/sshd file as following, and  /root/allow-users file contain the user list of those who authorize to ssh.
auth required pam_listfile.so item=user sense=allow file=/root/allow-users onerr=fail

Securing SSH on Linux Ubuntu


Strange HTTP response headers being sent to Internet Explorer 8 only

Question: So here's something I find puzzling.
I'm working on a Javascript that needs to parse XML data and I'm using jQuery's $.ajax to fetch and parse the data. It's working great everywhere except when I test with Internet Explorer 8 (it might be a problem on 7 and 9 too). On IE, I'm getting parse errors. I installed a console.log to check the HTTP headers. Here's what I get from Chrome on Windows XP and what I'm getting from IE --
Chrome:
Date: Sat, 09 Apr 2011 16:06:24 GMT
Connection: Keep-Alive
Content-Length: 2283
Last-Modified: Sat, 09 Apr 2011 15:59:12 GMT
Server: Apache/2.2.14 (Ubuntu)
ETag: "48048-8eb-4a07e6c693400"
Content-Type: application/xml
Accept-Ranges: bytes
Keep-Alive: timeout=15, max=97

IE8:
LOG: ETag: "48048-8eb-4a07d7a3cbe40"
Keep-Alive: timeout=15, max=97
Content-Type: text/html
Content-Length: 2283
Last-Modified: Sat, 09 Apr 2011 14:51:29 GMT

This is what the xml document looks like:
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <tweet>
        <name>name</name>
        <message>message</message>
        <avatar>avatar</avatar>
    </tweet>
    <tweet>
        <name>name</name>
        <message>message</message>
        <avatar>avatar</avatar>
    </tweet>
</root>

I checked the MIME configuring for my Apache server and it is set to send xml files as 'application/xml'. So it's strangely sending a content-type of 'application/xml' to Chrome, but IE gets content-type of 'text/html'.
So I built a simple PHP script:
<?php
header('Content-type: application/xml; charset=UTF-8');
echo '<?xml version="1.0" encoding="UTF-8" ?>';
?>
<root>
    <tweet>
        <name>name</name>
        <message>message</message>
        <avatar>avatar</avatar>
    </tweet>
    <tweet>
        <name>name</name>
        <message>message</message>
        <avatar>avatar</avatar>
    </tweet>
</root>

When I change the Javascript to retrieve the PHP instead of the XML file, I get these response headers --
Chrome with PHP:
Date: Sat, 09 Apr 2011 16:10:39 GMT
X-Powered-By: PHP/5.2.10-2ubuntu6.7
Connection: Keep-Alive
Content-Length: 2102
Server: Apache/2.2.14 (Ubuntu)
Content-Type: application/xml; charset=UTF-8
Keep-Alive: timeout=15, max=97

IE with PHP:
LOG: X-Powered-By: PHP/5.2.10-2ubuntu6.7
Content-Length: 2102
Keep-Alive: timeout=15, max=100
Content-Type: application/xml; charset=UTF-8

So from what I can tell, with my limited Apache knowledge, it seems like the raw XML file is getting sent without the right content-type only to IE, even though I have it configured to send 'application/xml'. Chrome is receiving the right content-type. When I use PHP, Apache seems to be following my wishes and sending 'application/xml' because that is what I stamped it as in the script. Is it also strange that IE doesn't have all the same headers as Chrome? "Server" is missing for instance.
So what could possibly be getting in the way and changing 'application/xml' to 'text/html' only for Internet Explorer? I'd hate to have to rely on a PHP script to output my XML data. I thought of mod-deflate, but I disabled it and the results are the same.
Any ideas?
(PS - the XML I'm including is just a sample, so the content-lengths don't match up)
Comment: So … this is a webserver administration question? Better fit for Server Fault?
Comment: For more fun and excitement, I changed my XML file to have the extension .tweets, and I put an "AddType application/xml tweets" into my Apache2 directives for that directory. Internet Explorer gets the correct content-type for the .tweets file! So somewhere, something seems to be interrupting Apache's headers for Internet Explorer, but only with a .xml file (and maybe other standard types).  Sorry, I did not know about serverfault.com. I guess I will try there.
Answer: So I think I figured it out.
It appears that IE caches the AJAX GET data in such a way that it is hard (impossible?) to clear it out. Maybe I had the xml configured as text/xml at some point, but I don't think so. Basically, IE continued to use the cached results for that XML file over the actual server results. That also explains why the HTTP headers looked so odd (no server information for instance). Or it's possible that the cache is always producing text/html (I gave up further tests).
My solution:
I added a '?avoidcache=' + a timestamp to the end of the URL in the GET request. Now IE gets the proper HTTP headers that I set on the server.
Wow do I hate Internet Explorer. How many development hours are wasted creating workarounds for it's horrible behavior?
Comment: Deep and complete hate for IE =( Lets see if Edge does something better
Answer: IE may send a different HTTP request, asking for text/html primarily or only and chrome on the other hand application/xml as well. Did you check the HTTP request headers?
Also, how did you inspect the HTTP packets? Maybe IE drops the server tag? (Which is pretty useless anyway, most of the time.)
As you tested with PHP, setting the content-type, and it worked, it's a webserver setting and/or HTTP-Request difference. Check those.
Comment: I was checking via jQuery's 'complete' event for the $.ajax() function. I will try and figure out a way to grab the request headers.


How do I count the number of products in cart programmatically?

Question: I have created the custom block, here I want to count the number of products which is presented in the cart and tried with commerce_cart_order_load function to get the user selected products.
Is there any other methods to count the number of product in cart ?
Please help me how to achieve this !
Answer: In Drupal 8, carts are special orders, related to a user (like regular orders). In a custom module, you can fetch the logged in user orders, filter them by a convenient boolean field called 'cart', sort them by creation date to get the last cart for this user. Then you can get the items count for this cart order :
in mymodule.module :

use Drupal\commerce_order\Entity\Order;

function mymodule_preprocess_[page|block|something_else](&$variables) {

  // get orders...
  $query = \Drupal::entityQuery('commerce_order')
    // ...for logged in user, could be anonymous (uid = 0)
    ->condition('uid',\Drupal::currentUser()->id())
    // ...which are carts
    ->condition('cart', 1)
    // ...last created first
    ->sort('created', 'DESC')
    // ...get only one
    ->range(0,1);

  // execute this : you get an array of a unique order ids (last cart)
  $cartsOrders = $query->execute();

  // I found one : this user has a cart
  if(count($cartsOrders) > 0) {

    // load the order which is the last cart for logged in user
    /* @var Order $lastCart */
    $lastCart = current(Order::loadMultiple($cartsOrders));
    // send this order items count to the template
    // ({{ cartItemsCount }} in your twig)
    $variables['cartItemsCount'] = count($lastCart->getItems());
  }
}

This may contains non optimal or ugly code, this is just a starting point (but quickly tested though, seems to work). Also this need to be tested in rare case scenarios or weird situations (involving anonymous users for example). My strategy (grab the last created cart order) may be wrong too...I would be happy to have a specialist feedback on this.
EDIT
I spent more time on this and had to debug a few things, here is some improvments (more Drupal Commerce 2 way) :
/* @var CurrentStoreInterface $cs */
$cs = \Drupal::service('commerce_store.current_store');
/* @var CartProviderInterface $cpi */
$cpi = \Drupal::service('commerce_cart.cart_provider');
$cart = $cpi->getCart('default', $cs->getStore());

$nbItemsInCart = $cart ? count($cart->getItems()) : 0;

Answer: If you know the store id and order type, then you can count the number of products in the current user's cart with the following code.
    $store_id = 1;
    $order_type = 'default';
    $cart_manager = \Drupal::service('commerce_cart.cart_manager');
    $cart_provider = \Drupal::service('commerce_cart.cart_provider');
    $entity_manager = \Drupal::entityManager();
    $store = $entity_manager->getStorage('commerce_store')->load($store_id);
    $cart = $cart_provider->getCart($order_type, $store);
    $total_items = count($cart-> getItems());

Comment: From the docs: entityManager() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal::entityTypeManager() instead.
Answer: Are you sure this is Drupal 8 and not Drupal 7? That function is from the Drupal 7 version of commerce_cart.module. If that's the case, you can do what the code does in the title callback for the "Shopping cart (# items)" code to count the number of items in the cart:
// Count the number of product line items on the order.
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

To make it more performant, we've added a cart_line_items_quantity_by_id() function in the dev version (to be included in Commerce 1.14) that avoids using the wrapper. However, you'd have to convert the $order->commerce_line_items field value into an array of line item IDs yourself first.
Comment: Yeah, am asking for drupal 8. Will your answer work in drupal 8 ?
Comment: I am trying to display the count of product in a block. I used the above code, its showing like PHP Fatal error:  Call to undefined function Drupal\\custom_hgsi_common\\Plugin\\Block\\commerce_cart_order_load() . I do not know what else to do. Please guide me
Comment: Yeah, that function doesn't exist; it appeared you were talking about Drupal 7 based on your mention of the Drupal 7 function. The same code will not work for Drupal 8.


Data retrieved from a NSMutableArray are different with the one I saved into it

Question: Why the value of  cells retrieved from a NSMutableArray is different with the ones I have originally stored in it?
I have a property of type NSMutableArray and I use it to hold an integer matrix with the following code
tiles = [[NSMutableArray alloc] initWithObjects:
         @1, @1, @1, @1, @1, @1,
         @1, @0, @0, @0, @0, @1,
         @1 ,@0, @0, @0, @0, @1,
         @1 ,@0, @0, @0, @0, @1,
         @1 ,@0, @0, @0, @0, @1,
         @1, @1, @1, @1, @1, @1,nil];

tileManager = [[TileManager alloc] init];
[tileManager CreateTilesMapRow:tilesMatrixWidth withColumns:tilesMatrixHeight byFlatDataArray:tiles];

and here is the retrieving part which always return @1 from NSMutableArray which is a "iso_wall"
-(void) placeAllTilesIso
{
    NSString *imageName;
    printf("Width , Height : %li , %li \n",(long)tilesMatrixWidth (long)tilesMatrixHeight);
    for (NSInteger i = 0;i<tilesMatrixWidth;i++)
   {
        for(NSInteger j = 0;j<tilesMatrixHeight;j++)
        {
            imageName = [tileManager getSpriteNameForRow:i andCol:j];
//HERE IS THE WRONG RESULT! Always says iso_wall! but It shouldn't if you take a look at tiles which includes both @0 and @1, where did the @0 went?
            NSLog(@"Sprite Got!  image name : %@ \n",imageName);
        }
    }
}

I have also defined a class and a header with names TileManager.m and TileManager.h that I plan to extend them in future, here is their codes :
This is TileManager.h
#import <UIKit/UIKit.h>
#import <math.h>
@interface TileManager : NSObject
@property (strong,nonatomic) NSMutableArray *tilesMatrix;
- (void) CreateTilesMapRow:(NSInteger) row withColumns:(NSInteger) col byFlatDataArray:(NSMutableArray*) flatArray;
- (NSString *) getSpriteNameForRow:(NSInteger) row andCol:(NSInteger) col;
@end

This is TileManager.m
#import "tileManager.h"
@implementation TileManager

//NSMutableArray *tilesMatrix;

- (void) CreateTilesMapRow:(NSInteger) row withColumns:(NSInteger) col byFlatDataArray:(NSMutableArray *) flatArray
    {

    _tilesMatrix = [[NSMutableArray alloc] initWithCapacity:row];
    NSMutableArray *innerTmp = [[NSMutableArray alloc] initWithCapacity:col];
    for (int i = 0;i < col;i++) [innerTmp addObject:@0];
    for (int i = 0;i < row;i++) [_tilesMatrix addObject:innerTmp];

   for (NSInteger rowIndex=0; rowIndex < row;rowIndex++)
     {
        for (NSInteger colIndex=0; colIndex < col; colIndex++)
        {
            _tilesMatrix[rowIndex][colIndex] =(NSString*) flatArray[rowIndex*col+colIndex];
        //READ ME
        // This show everything is ok and the _tileMatrix contains both 0 and 1
            NSLog(@"Create : row : %li    col : %li  val : %@",(long)rowIndex,(long)colIndex,_tilesMatrix[rowIndex][colIndex]);
            }
        }
    }
}
-(NSString *) getSpriteNameForRow:(NSInteger) row andCol:(NSInteger) col
{
    //README
    // This always writes 1 which is incorrect
    NSLog(@"GET : row : %li    col : %li  val : %@",(long)row,(long)col,_tilesMatrix[row][col]);
    if ([_tilesMatrix[row][col] isEqual:@1])
        return (NSString *) @"iso_wall";
    else
        return (NSString *) @"iso_ground";
}

Why working with arrays is so hard in Objective C !!!
Comment: "Why working with arrays is so hard in Objective C" Well, you _could_ switch to Swift... :)
Comment: Still don't understand why is it so hard to work with arrays in Objective C, I never make such a mistake in c/c++ but Objective C !!!!! God give enough patient.
Comment: :) But in this case it had merely to do with the fact that you don't understand that object references are _pointers_. It has nothing to do with arrays at all.
Comment: @matt since I am a newbie in Objective C, do you think I should switch to swift?
Comment: Personally, yes. I have used and taught Objective-C for many years but I think Swift is a much better newbie language, with far cleaner syntax, and protecting the programmer from many kinds of mistake. (However, you _could_ have made a similar mistake to _this_ one in Swift, because class instance references are pointers in Swift as well.) - You can read my online book about Swift and decide whether this might be a better road to go down: http://www.apeth.com/swiftBook/
Comment: I don't understand how you managed to program in C/C++ without knowing what a pointer is.
Comment: Thanks for the suggestion and Yes you are right it could happen in any pointer based language but why assigning a reference need a method! (add_object) come on! its only an address! I thought that will be passed by value, otherwise why a method!, by the way ......I will start swift tomorrow!
Comment: There's no reasonable way to add a value to a composite structure like an NSArray without doing a method call.  You couldn't do it in C or C++ either.  Of course, you're always welcome to use plain old C arrays in Objective-C, but most people avoid them since the benefits of using NSArray far outweigh any inconvenience 99% of the time.
Answer:
for (int i = 0;i < col;i++) [innerTmp addObject:@0];

Fill innerTmp with col zeroes...

for (int i = 0;i < row;i++) [_tilesMatrix addObject:innerTmp];

Add innerTmp row times to _tilesMatrix...
You've built a matrix where every row is a reference to the same object - innerTmp.
Maybe try:
[_tilesMatrix addObject:[innerTmp mutableCopy]];

so each row is distinct.
HTH
Comment: Thank you very much, Yes you were right, all rows were pointing at the first one which was a full row of  @1.
Answer: Is it possible that these 2 line is causing the problem:
for (int i = 0;i < col;i++) [innerTmp addObject:@0];
for (int i = 0;i < row;i++) [_tilesMatrix addObject:innerTmp];

I can not run the code now unfortunately but everything else looked solid except these. Same innerTmp is being added to all rows. Same memory. Instead maybe:
for (int i = 0;i < row;i++) {
    NSMutableArray * innerTmp = [[NSMutableArray alloc] initWithCapacity:col];
    for (int j = 0;j < col;j++) {
        [innerTmp addObject:@0];
    }
    [_tilesMatrix addObject:innerTmp];
}


Customizar/personalizar legenda do gráfico em Python

Question: Estou a tentar criar uma legenda personalizada no meu gráfico feito em Python num Jupyter Notebook, no Anaconda. Não quero nenhum retângulo à volta da legenda. Em vez da legenda aparecer como está na imagem, que é a predefinição, gostava de simplificar um pouco a legenda para depois poder aumentar o tamanho da letra. Queria que a legenda aparecesse da forma que aparece na seguinte imagem que fiz com lápis e papel para exemplificar. Poderiam dizer-me/ajudar-me a dar esta melhoria no meu gráfico? Já procurei, mas não encontrei mesmo como fazer.
Como eu gostaria de ter a legenda (rascunho):

import matplotlib.pyplot as plt
from numpy import *
import numpy as np
import pandas as pd

df = pd.read_excel('data39e40cm.xlsx', header=None, usecols=[0,1,2,3,4,5,6], names=['A', 'B', 'C', 'D','E','F','G'])
plt.style.use('classic')
plt.rcParams["figure.figsize"] = [10.5,10]
plt.rc('axes', titlesize=16)
plt.rc('xtick', labelsize=12)    # fontsize of the tick labels
plt.rc('ytick', labelsize=12)
plt.rc('legend', fontsize=14, frameon=False)
plt.rcParams["figure.facecolor"] = "w"
plt.plot(df['A'], df['B'], label='Temperatura da zona quente (40 cm)', linestyle='-', marker='o', color='DarkGreen', markersize=4)
plt.plot(df['A'], df['C'], label='Temperatura da zona fria (40 cm)', linestyle='-', marker='o', color='MediumAquamarine', markersize=4)
plt.plot(df['A'], df['D'], label='Temperatura do termopar (40 cm)', linestyle='-', marker='o', color='OliveDrab', markersize=4)
plt.plot(df['A'], df['E'], label='Temperatura da zona quente (39 cm)', linestyle='-', marker='o', color='OrangeRed', markersize=4)
plt.plot(df['A'], df['F'], label='Temperatura da zona fria (39 cm)', linestyle='-', marker='o', color='Orange', markersize=4)
plt.plot(df['A'], df['G'], label='Temperatura do termopar (39 cm)', linestyle='-', marker='o', color='Coral', markersize=4)
#plt.grid(b=True, color='black', alpha=0.3, linestyle='-.', linewidth=1) #caso quisesse a grid completa e nao apenas a horizontal
axes = plt.gca()
axes.yaxis.grid(b=True, color='black', alpha=0.3, linestyle='-.', linewidth=1)
plt.xlabel('Tempo (minuto)', fontsize=15)
plt.ylabel('Temperatura (ºC)', fontsize=15)
plt.title('Perfil de temperatura do forno')
plt.legend()
#plt.show()
plt.savefig('output.png', dpi=500, bbox_inches='tight')

Dados completos do ficheiro Excel:
0   26  26  27  25  25  26
2   36  34  28  37  35  29
4   85  52  37  85  52  42
6   153 65  48  156 66  56
8   183 79  60  187 80  71
10  217 93  72  217 93  84
12  259 107 84  259 106 98
14  300 121 96  300 120 112
16  339 135 108 340 134 126
18  379 149 120 382 148 140
20  419 163 131 420 162 151
22  459 177 143 461 177 165
24  498 190 154 498 189 176
26  538 204 166 537 204 188
28  584 218 178 583 220 203
30  606 233 190 606 232 214
32  604 246 200 604 245 226
34  601 260 210 601 259 236
36  627 274 220 625 273 248
38  670 288 231 669 287 260
40  713 300 243 711 300 273
42  756 302 254 751 302 283
44  793 303 260 791 303 288
46  806 305 265 806 305 292
48  803 307 267 803 307 294
50  801 310 269 801 310 295
52  800 313 271 800 313 296
54  800 317 273 800 316 297
56  800 320 274 800 319 298
58  800 323 275 800 322 299
60  800 326 276 800 324 300
62  800 329 277 800 325 300
64  800 331 278 800 328 302
66  767 334 278 800 330 302
68  735 337 277 800 332 303
70  708 339 275 766 334 303
72  686 340 273 733 337 302
74  664 340 272 710 338 300
76  645 340 270 681 339 298
78  629 339 268 662 340 295
80  613 338 266 645 339 293
82  598 336 263 629 339 291
84  585 334 261 612 337 289
86  572 332 259 598 336 287
88  560 330 257 584 334 284
90  550 327 255 573 332 282
92  538 325 252 560 329 279
94  529 322 250 549 327 277
96  520 319 248 539 325 274
98  511 317 245 529 322 271
100 502 314 243 520 319 269
102 494 311 240 511 316 266
104 487 308 238 502 313 263
106 479 305 236 494 311 261
108 471 302 233 486 307 258
110 465 299 231 479 305 255
112 458 296 229 472 302 253
114 451 293 226 465 299 250
116 445 291 224 458 296 247
118 439 288 222 451 293 245
120 433 285 219 444 290 242
122 427 282 217 438 287 239
124 421 279 215 432 284 237
126 416 277 213 426 282 234
128 410 274 210 421 279 232
130 405 271 208 416 276 230
132 400 269 206 409 274 227
134 394 266 203 405 271 224
136 390 263 202 400 268 222
138 385 261 200 395 266 220
140 380 258 198 387 262 218
142 376 256 196 383 260 215
144 371 253 194 378 257 212
146 367 251 192 371 253 209
148 363 248 190 367 251 206
150 358 246 188 364 248 204
152 354 244 186 358 245 202
154 350 241 184 354 243 200
156 346 239 182 350 241 198
158 343 237 181 346 239 196
160 341 236 180 342 236 194
162 338 234 179 338 234 192
164 335 232 177 334 232 190
166 330 230 175 331 229 188
168 327 228 174 327 227 186
170 323 225 172 323 225 185
172 320 223 170 320 223 183
174 317 221 169 317 221 181
176 313 219 167 313 219 179
178 310 217 166 310 217 178
180 307 215 164 307 215 176
182 303 213 162 303 212 174
184 300 211 160 299 210 172
186 297 209 159 297 209 170
188 294 207 158 294 207 169
190 291 205 156 290 205 167
192 286 202 154 288 203 166
194 282 200 152 285 201 165
196 279 198 151 282 199 163
198 274 194 148 279 198 162
200 272 193 147 277 196 160
202 268 191 145 274 194 159
204 266 189 144 271 192 157
206 263 187 143 268 190 155
208 260 185 141 265 189 154
210 258 184 140 263 187 153
212 255 182 139 260 185 151
214 253 181 138 257 183 149
216 250 179 136 255 182 148
218 248 177 135 253 180 147
220 246 176 134 250 179 146
222 243 174 133 248 177 145
224 241 173 132 245 175 144
226 238 171 131 243 174 142
228 236 170 129 241 173 141
230 234 168 128 238 171 140
232 232 167 127 236 170 139
234 230 165 126 234 168 137
236 227 163 125 233 167 136
238 225 162 124 231 166 136
240 223 161 123 229 165 135
242 221 159 122 227 163 133
244 219 158 121 225 162 132

Gráfico obtido:
Comment: Em vez da imagem das colunas, você pode colar o texto ou disponibilizar parte da base de dados em um arquivo. Ficaria mais fácil responder podendo replicar o que vc fez
Comment: @Lucas Obrigada pela dica. Acabei de colocar os dados todos no enunciado. Agradecia muito se me pudesse ajudar. Obrigada
Answer: O que você precisa é do método plt.annotate e adicionar alguns parâmetros no método plt.legend:
import matplotlib.pyplot as plt
import pandas as pd

names=['A', 'B', 'C', 'D','E','F','G']
df = pd.read_table('data.txt', sep='\t',header=None, usecols=[0,1,2,3,4,5,6], names=['A', 'B', 'C', 'D','E','F','G'])

fig, ax =plt.subplots()
ax.plot(df['A'], df['B'], label='40 cm', linestyle='-', marker='o', color='DarkGreen', markersize=4)
ax.plot(df['A'], df['C'], label='40 cm', linestyle='-', marker='o', color='MediumAquamarine', markersize=4)
ax.plot(df['A'], df['D'], label='40 cm', linestyle='-', marker='o', color='OliveDrab', markersize=4)
ax.plot(df['A'], df['E'], label='39 cm', linestyle='-', marker='o', color='OrangeRed', markersize=4)
ax.plot(df['A'], df['F'], label='39 cm', linestyle='-', marker='o', color='Orange', markersize=4)
ax.plot(df['A'], df['G'], label='39 cm', linestyle='-', marker='o', color='Coral', markersize=4)
axes.yaxis.grid(b=True, color='black', alpha=0.3, linestyle='-.', linewidth=1)
ax.set_xlabel('Tempo (minuto)', fontsize=15)
ax.set_ylabel('Temperatura (ºC)', fontsize=15)
ax.set_title('Perfil de temperatura do forno')
ax.legend(loc=9,
          bbox_to_anchor=(.75,.75),
          labelspacing=3,
          ncol=2, fontsize=14)

trans = ax.get_xaxis_transform() # x em unidades do dado, y em fração do eixo
ann = ax.annotate('Temperatura da zona quente', xy=(150, 0.75), xycoords=trans, fontsize=14)
ann = ax.annotate('Temperatura da zona fria', xy=(150, 0.65), xycoords=trans, fontsize=14)
ann = ax.annotate('Temperatura da zona termopar', xy=(150, 0.55), xycoords=trans, fontsize=14)

plt.show()

Eu mudei um pouco o seu código para deixar apenas o que é essencial à questão. Note que de diferente do seu código, o meu tem apenas a função plt.legend com argumentos e a função plt.annotate. Experimente mexer nos parâmetros xy do método annotate e no parâmetro loc do legend para ver como você pode colocar a legenda no lugar que desejar.
Outro ponto: é possível remover a repetição de informações no seu código e fazer ele ficar mais DRY:
fig, ax =plt.subplots()
for index, col in enumerate(names[1:]):
    ax.plot(df['A'], df[col], label='40 cm', linestyle='-', marker='o', color=colors[index], markersize=4)

axes.yaxis.grid(b=True, color='black', alpha=0.3, linestyle='-.', linewidth=1)
ax.set_xlabel('Tempo (minuto)', fontsize=15)
ax.set_ylabel('Temperatura (ºC)', fontsize=15)
ax.set_title('Perfil de temperatura do forno')
ax.legend(loc=9,
          bbox_to_anchor=(.75,.75),
          labelspacing=3,
          ncol=2, fontsize=14)
trans = ax.get_xaxis_transform() # x em unidades do dado, y em fração do eixo
for index, label in enumerate(temp_label):
    ann = ax.annotate(label, xy=(150, 0.75-index*0.1), xycoords=trans, fontsize=14)

plt.show()

Comment: Muito obrigada pela completa resposta, Lucas! Agradeço imenso e me ajudou muito!
Answer: Uma forma simples de fazer isso é
ax.legend(frameon=False)


Como fazer um bypass em um redirecionamento HTTP?

Question: Existe alguma forma de fazer um "bypass" e acessar a página? Por exemplo:
if(!isset($variavel)) {
  header ('Location: error.php');
} else {
  echo 'oi';
}

Answer: Não sei se você considera isto um bypass, mas a emissão do header não termina o script. Você deve fazer isso manualmente com exit após um redirect, ou o script segue em frente:
if(!isset($variavel)) {
  header ('Location: error.php');
  exit;
} else {
  echo 'oi';
}
// Chegaria aqui sem o exit

Se a sua dúvida é quanto à execução do else do seu código, isso não tem relação com o redirecionamento. Tudo depende de a variável $variavel estar definida ou não. Logicamente, se o código de redirecionamento do seu exemplo for executado, não tem como o else também ser executado.


Comma separated list

Question: How I can get comma separated name list like Abc, Xyz. Here is my code
<%= user.email %>
    <% user.user_policies.each{|user_policy| %>
          <%=user_policy.policy.name %>
    <%}%>

Thanks,
Answer: policy_names = user.user_policies.map {|up| up.policy.name }
policy_name_list = policy_names.join(',')

Comma separated list


Combine / Allow access between 2 Azure / Office 365 Domains / Tenants

Question: Apologies if this is not the correct place to ask this question.
After a recent acquisition, I am trying to understand if it is possible to provide a trust between 2 Office 365/Azure AD domains, both are currently syncing via separate Azure AD Connects in 2 different regions.
Is it possible to do this without setting up an AD trust on premise? We're looking away from this option for security reasons.
I've come across something called Azure AD B2B. Will that help in what I am trying to achieve?
Or is there a way for a single global admin account in Azure to allow and control access between the 2 online domains? Perhaps using the method as described here:
Consolidating Office 365, AAD and Azure Subscription
What are the limitations if any?
Is it possible for company A using 123.com email addresses to create accounts for company B's 789.com email address and vice versa?
Can the calendar free/busy lookups work between the domains?
I know I'm possibly asking the impossible, but any help/insight would be appreciated.
Thanks in advance.
Answer: There is always a 1:1 relationship between the on-prem domain and entra id domain when using Azure aad connect.
But there is an exception you can add multiple domains to azure ad connect.
So you could create a S2S-VPN to the other company and their domain controller and sync the users.
Another option would be a tenant-to-tenant migration.
https://learn.microsoft.com/en-us/microsoft-365/enterprise/microsoft-365-tenant-to-tenant-migrations?view=o365-worldwide


I tried with this code, but it won't work with Ionic 3

Question:
PS C:\Users\USER\PickMeUp> typings install google.maps --ambient --save
  typings ERR! deprecated The "ambient" flag is deprecated. Please use "global" instead
Answer: Try this:
<code>C:\Users\USER\PickMeUp> typings install google.maps --global --save typings
</code>
it just means you have to replace --ambient with --global flag
Comment: i ll try ..thnk u so much
Comment: @KalanaDilshan for this at least that's what the instruction says. ionic 3 have to check


How to calculate mean and standard deviation in R given confidence interval and a normal or gamma distribution?

Question: Suppose you are given a $95 \%$ CI $(1,6)$ based on the normal distribution. Is there any easy way to find $\mu$ and $\sigma$? What if it came from a gamma distribution? Can we do this in R?
Comment: Toby, be careful about how you interpret answers to this question, because "based on the normal distribution" can mean various things. For instance, some people might interpret a CI which uses the Student T distribution to be "based on the normal distribution" (because it is, indirectly). Moreover, there are many kinds of CIs: they are often "symmetric" in some sense, but not always (in particular, a CI related to a gamma distribution might not be). It all comes down to *what formula was used* to compute the CI. Do you have any information about that?
Answer: Please read the erratum at the end of the answer.
First note that there is not enough information to solve this problem. In both cases, $n$ the sample size is missing. In the case of the Gaussian distribution, assuming you know $n$, you can easily do it by following @Michael Chernick's instructions. In R that would give something like this (with $n=43$ for the sake of the example).
n <- 43
ci <- c(1,6)
# Take the middle of the CI to get x_bar (3.5).
x_bar <- mean(ci)
# Use 1 = x_bar - 1.96 * sd/sqrt(n)
S2 <- n^2 * (x_bar - ci[1])/1.96

For the case of the Gamma distribution, things are a bit more complicated because it is not symmetric. So the mean is not in the center of the CI.
For example, say you sample from a Gamma population $\Gamma(\alpha,1)$ where $\alpha$ is unknown. The sample mean is the sum of $n$ variables distributed as $\Gamma(\alpha,1)$ divided by $n$, so it is a variable distributed as  $\Gamma(n\alpha,1/n)$. Say that we observed a mean of $1.7$ for a sample size of $n=5$. There are several CI that contain this value as we can check.
> qgamma(.975, shape=1.7*5, scale=1/5)
[1] 3.019101
> qgamma(.975, shape=1.7*5, scale=1/5, lower.tail=F)
[1] 0.7564186

A 95% CI for $\alpha$ is $(.756, 3.019)$, the middle of which is $1.89$, not $1.70$. In short, finding the $\alpha$ and $\theta$ that produce a 95% CI is possible because the solution is unique, but it is a hack.
Fortunately, as $n$ increases, the distribution becomes more and more Gaussian and symmetric, so the CI will be symmetric around the mean. The mean and variance of a $\Gamma(n\alpha,\theta/n)$ are $\alpha\theta$ and $\alpha\theta/n$, so you can use the results of the Gaussian case and solve this very simple equation to get $\alpha$ and $\theta$.
Erratum: Following @whuber's comment I realized that the proposed way to get a confidence interval for $\alpha$ is not good.
The example given above was meant to demonstrate that getting CI with Gamma variables is much more tedious than with Gaussian variables. My mistake proves the point even better. At @whuber's prompt I will show that the CI I proposed is incorrect.
set.seed(123)
# Simulate 100,000 means of 5 Gaussian(0,1) variables (positive control).
means <- rnorm(100000, sd=1/sqrt(5))
upper <- means + qnorm(.975)/sqrt(5)
lower <- means - qnorm(.975)/sqrt(5)
mean((upper > 0) & (lower < 0))
[1] 0.95007 # OK.
# Simulate 100,000 means of 5 Gamma(1,1) variables.
means <- rgamma(100000, shape=5, scale=1/5)
upper <- qgamma(.975, shape=5*means, scale=1/5)
lower <- qgamma(.975, shape=5*means, scale=1/5, lower.tail=FALSE)
mean((upper > 1) & (lower < 1))
[1] 0.94666 # Almost, but not quite.

Comment: This reply starts off really well. The second part, though, does not give a correct CI for a gamma distribution. (Simulate it for small values of `shape` and small sample sizes.)
Comment: +1 For a convincing simulation, try a shape parameter of 0.5 and scale of 2 :-).
Answer: If you mean the true parameters, of course, the answer is no.  But if you mean that you want to recover the sample estimates from the confidence interval, the answer is yes, for the normal distribution if the sample size $n$ is also given.
If the confidence interval was $(1,6)$, then $1= \overline{X}-1.96 \cdot S/\sqrt{n}$ and $6=\overline{X}+1.96 \cdot S/\sqrt{n}$.  So $\overline{X}= (6+1)/2=3.5$
and then $6=3.5 +1.96 \cdot S/\sqrt{n}$ or $S=\sqrt{n} 2.5/(1.96)$.
For the gamma distribution this paper shows various ways to get the approximate and exact confidence intervals for rates.  Getting the parameter estimates from these confidence intervals may be complicated.
Comment: Some tricks, Michael: (1) http://www.math.harvard.edu/texman/ lets you quickly look up some common expressions. (2) Start $\TeX$ expressions with both the enclosing "$\$$" characters, so that as you type you can see the expression previewed below. (3) For using $\TeX$ in comments, open a separate window and start to *ask a new question* on this site. It will give you a preview. Cut and paste it into your comment, then abandon the new question. (4) You can right-click on any $\TeX$ on a page to see the original markup: learn from it (and use copy-and-paste judiciously).
Comment: Please consider using TeX in your answers. It makes it much easier to read equations!
Comment: @MånsT, or we can earn the 'Copy Editor' badge by editing his posts for him :)
Comment: @MichaelChernick - that's fine. When I first learned TeX, I found it to be very useful to look at examples. If you look at how I formatted the equations in your answer here, you can see, for example, that you enter "Equation" environment by typing `$` (or `$$` to make in a centered equation on a new line) and, once you're in equation environment that `\overline{X}` will type $\overline{X}$, and `\sqrt{n}` will type $\sqrt{n}$, and so on
Comment: That's a great start! Have a look at the edits to your answers and I'm sure that you'll be TeXing in no time.
Comment: @Macro I can do subscripts and superscripts in TeX and have started doing that but I am not knowledgeable enough to do full equations.
Comment: @MichaelChernick: How would you do it for a gamma distribution?
Comment: The approximate CIs involve normal approximations and others.  Just like for the normal the end points of the interval would have to be expressed as functions of the 2 gamma parameters and you would have to solve 2 equations in 2 unknowns again.  I pointed you to the paper because I think that is where you can find out how those endpoints are expressed.  But I expect that it is much more complicated than in the normal case.
Comment: Why was my answer downvoted?  I gave a complete answer for the normal case and pointed to a possible way to get a solution in the case of the gamma.
Comment: Michael, I checked for suspicious voting patterns but found nobody systematically downvoting your answers, so if you were concerned about that possibility, please do not be. I can only speculate that the downvote was placed before your answer attained its current well-formatted state or included that useful reference about gamma CIs.
Answer: You can construct a confidence interval around anything that can be estimated, whether it be a mean, standard deviation, even a maximum for any given probability distribution.
Assuming you have a CI around the mean estimated from an experiment in which a finite sample of size $n$ were taken from independent, identically distributed random normal variables, then you know the exact confidence interval is given by the sample mean plus or minus 1.96 times the standard error, which is the sample standard deviation scaled by the square root of the sample size. $\bar{x} \pm \mathcal{Z}_{\alpha/2} \left( s/\sqrt{n} \right)$. Your estimates of these parameters, conventionally labeled as $\bar{x}$ and $s$ are the "best guesses" for the "population mean" $\mu$ and "standard deviation" $\sigma$.
These estimators also estimate the same values regardless of the distribution of your independent samples or the corresponding sampling distribution of the mean. Note however, that the confidence interval is asymptotic and these estimates are not necessarily the best anymore.
Comment: The first paragraph is insightful. Concerning the second, your "exact" CI went out of vogue 104 years ago when "Student" showed that it is not exact and, in finding an exact CI, discovered the t distribution. The third paragraph is difficult to make sense of. Overall, though, what is your answer to the question?
Comment: That's correct, I haven't accounted for the degrees of freedom in what I called the exact CI. What I'm getting at is this: assuming the CI is an asymptotic, dist-n free estimate based on the CLT, then yes the sample mean and sample standard deviation can be arithmetically derived, given the sample size. Without knowledge of the construction of the CI, this may be perilous. CIs for the odds ratio in logistic regression models are non-symmetric and you couldn't estimate the "mean" and "standard deviation" of the sampling distribution of the sample odds ratio based on such a CI.
Answer: If what is given are the quantiles from a normal distribution (although not the same as confidence intervals) then a solution to the problem reduces to find the distribution parameters from quantiles.
For the normal distribution we want to find $\mu$ and $\sigma$ such that the random variable $X$ satisfies:
$$
P(X<x_1) = p_1
$$
$$
P(X<x_2) = p_2
$$
The random variable $X$ has the same distribution as $\mu Z + \sigma$ where $Z$ is a standard normal random variable $Z \sim N(0,1)$ and cdf $\phi$ .
This implies that :
$$
\phi^{-1}(p_i)\sigma+\mu=x_i
$$
In R an example given that 20 and 40 are the 0.05 and 0.95 quantiles then.
approx_sd <- function(x1, x2){
  (x2-x1) / (qnorm(0.95) - qnorm(0.05) )
}
approx_sd(20, 40)

approx_mean <- function(x1, x2){
  (x1*qnorm(0.95) - x2*qnorm(0.05)) / (qnorm(0.95) - qnorm(0.05) )
}
approx_mean(20, 40)

For the gamma, the solution is more involved because the inverse CDF has not a closed-form. However, there exist tools and software that automate this complex problem, for example, ParameterSolver downloadable from the following repository https://biostatistics.mdanderson.org/SoftwareDownload/
Although your question parts from a frequentist confidence interval which is of course, not a quantile, the text might indicate that readers can arrive at this question looking for a quantile parameterised distribution which is a topic of active research.


How to make click on ActionBar Logo in android

Question: I tried to do something on Click on icon in ActionBar but do nothing.I also like to do open drawer_layout on click on a icon in action bar. How to make it clickable and handle the event of it`s pressing?
public class MainActivity extends AppCompatActivity {
ViewPager viewPager,viewPager01;
CustomSwipAdapter swip_adapter;
CustomSwipAdapter01 swip_adapter01;

String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try{
        getSupportActionBar().setLogo(R.drawable.sample_01);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("");
    }
    catch (Exception e) {
    }
    viewPager = (ViewPager)findViewById(R.id.viewpager);
    swip_adapter =new CustomSwipAdapter(this);
    viewPager.setAdapter(swip_adapter);

/*    viewPager01 = (ViewPager)findViewById(R.id.viewpager01);
    swip_adapter01 =new CustomSwipAdapter01(this);
    viewPager01.setAdapter(swip_adapter01);*/

    menu = new String[]{"Home","E-Gift Voucher"};
    dLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    dList = (ListView)findViewById(R.id.left_drawer);
    adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menu);

    dList.setAdapter(adapter);
    dList.setSelector(android.R.color.holo_blue_dark);

    dList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            dLayout.closeDrawers();
            Bundle args = new Bundle();
            args.putString("Menu", menu[position]);
            Fragment detail = new DetailFragment();
            detail.setArguments(args);
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();
        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
 /*   getMenuInflater().inflate(R.menu.menu_main, menu);
    MenuInflater inf = getMenuInflater();
    inf.inflate(R.menu.main_activity_action,menu);
    return super.onCreateOptionsMenu(menu);*/

    MenuInflater inf = getMenuInflater();
    inf.inflate(R.menu.main_activity_action,menu);
    return true;//super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
   // int id = item.getItemId();

     switch (item.getItemId()){
         case android.R.id.home:
             Toast.makeText(MainActivity.this,"Click on Logo",Toast.LENGTH_SHORT).show();
             return  true;
         default:
             return super.onOptionsItemSelected(item);
     }
    }
}

Comment: action bar is deprecated, please use toolbar
Comment: will you provide some example of toolbar
Comment: http://www.androidhive.info/2015/04/android-getting-started-with-material-design/
Comment: http://www.android4devs.com/2014/12/how-to-make-material-design-navigation-drawer.html
Comment: thanks for your help
Comment: Possible duplicate of [Android how to make clickable logo icon in actionbar?](http://stackoverflow.com/questions/11030204/android-how-to-make-clickable-logo-icon-in-actionbar)
Answer:
layout xml

<RelativeLayout
    android:id="@+id/rl_main_search_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/transparent_semi"
    tools:context="com.worldofmoms.views.fragments.search_and_explore.SearchFragment">

    <android.support.v7.widget.Toolbar
          android:id="@+id/toolbar_search"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:background="?attr/colorPrimary"
          android:minHeight="?attr/actionBarSize"
          app:theme="@style/ActionBar_Light"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar_search"
        android:background="@android:color/white"
        android:visibility="gone"
        />

</RelativeLayout>

Add in your activity onCreate()
       mToolbar = (Toolbar) view.findViewById(R.id.toolbar_search);
       setSupportActionBar(mToolbar);
       getSupportActionBar().setDisplayShowHomeEnabled(true);
       getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and Add

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
      if(id==android.R.id.home){
        // home button from toolbar clicked
        }
    }

Answer: Add in your activity onCreate(): i am quite sure it may help you...
     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Custom code for image icon which redirects to homepage
    ActionBar actionBar=getSupportActionBar();
    actionBar.setDisplayOptions(actionBar.getDisplayOptions()
            | ActionBar.DISPLAY_SHOW_CUSTOM);
    ImageView imageView = new ImageView(actionBar.getThemedContext());
    imageView.setScaleType(ImageView.ScaleType.CENTER);
    imageView.setImageResource(R.mipmap.ic_launcher);
    imageView.setOnClickListener(new OnClickListener() {
        @Override public void onClick(View v) {
            webViewPlaceholder.loadUrl("http://www.salebhai.com");
        } });
    ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT, Gravity.LEFT
            | Gravity.CENTER_VERTICAL);
    layoutParams.leftMargin = 20;
    imageView.setLayoutParams(layoutParams);
    actionBar.setCustomView(imageView);

    actionBar.setDisplayHomeAsUpEnabled(true);

Thank you ,
happy Coding.....
Comment: Please do not post the same answer to multiple questions. If the same information really answers both questions, then one question (usually the newer one) should be closed as a duplicate of the other. You can indicate this by [voting to close it as a duplicate](http://stackoverflow.com/help/privileges/close-questions) or, if you don't have enough reputation for that, [raise a flag](http://stackoverflow.com/help/privileges/flag-posts) to indicate that it's a duplicate. Otherwise, be sure you tailor your answer to *this* question and don't just paste the same answer in multiple places.


asp.net/sql get everything in the string before the "-" and put it into a different string

Question: Basically I have got two things i am passing from a command argument
<asp:LinkButton ID="lbEditDetails" Text="Edit..." runat="server" CommandName="EditDetails" CssClass="EditAdults" CommandArgument=<%# DataBinder.Eval(Container.DataItem, "number_slept") & "-" & DataBinder.Eval(Container.DataItem, "booking_ref")  %>></asp:LinkButton>

I need to grab the number_slept which is everything before the - and put it into another string and then grab the booking_ref which is after the - and put that into a string
Here's what I've got
Dim strPassedString = e.CommandArgument

Dim NumberSlept = This will be the passed number slept

Dim BookingRef = This will be the passed booking ref

I'm not sure how to split the command argument
Is it possible?
Thanks
Jamie
Answer: String.Split
C#, but you get the idea...
string numberSlept = e.CommandArgument.Split('-')[0];
string bookingRef = e.CommandArgument.Split('-')[1];


Cache not clearing on expiry

Question: Using the steps explained here: http://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7 I'm storing an array with specified expiry time.
But what is happening is that even after expiry of time, the cache_get is returning the stale cache. Even Cron run is not deleting the cache entry(I've checked the cache_block table).
This is the code:
     $out = &drupal_static(__FUNCTION__);

        if ( !isset($out)) {
            if ( ( $cache = cache_get(__FUNCTION__,'cache_block'))) {
                $out = $cache->data;
                dsm("cache returned");
            } else {

//do something
//...........
  $out = '
' . $out . "
";
            cache_set(__FUNCTION__, $out, 'cache_block', strtotime("23:59:59")+2);
        }//else ends
    }//!isset ends

    return $out;
}//function ends

Only cache clear all in the Performance tab is clearing this cache entry in the cache table.
I'm confused how this expired cache will be deleted.
In that article I can read this statement:

Expired entries will be automatically discarded as they pass that
  date.

But does not seem to be happening. Also I've verified that "expire" value in the cache table is beyond current time.
I can clear the cache myself but then cache_get function does not return the "expire" time in the table.
Anything I'm missing here?
Comment: Please show us your code to **store** cache data. We can't tell what's wrong with it if we can't see it.
Comment: I've edited it.
Answer: As you can see in the documentation:

$expire: One of the following values:

CACHE_PERMANENT: Indicates that the item should never be removed unless explicitly told to using cache_clear_all() with a cache ID.
CACHE_TEMPORARY: Indicates that the item should be removed at the next general cache wipe.
A Unix timestamp: Indicates that the item should be kept at least until the given time, after which it behaves like CACHE_TEMPORARY.

Please note - it's not "at most". It's "at least". So your code works just the way it is to be expected. If you want to force-expire it, use cache_clear_all( __FUNCTION__ , 'cache_block'), for example in hook_cron() or at the beginning of your code.
Also note that it looks like you are re-saving cache at each use. That's not an usual thing, saving data is CPU and HDD expensive. It costs more than not caching at all. So consider only setting cache if it was not found in the first place, and needs to be regenerated. If cache is already set, let it expire and don't set it again.
Comment: The +2 seconds is for testing. I've placed the correct code now. How would I know when the cache has expired?
Comment: It's not about +2, really. It's about setting cache at *use*, no matter if it was there already or not.

Cache not clearing on expiry


Login to Openstack Horizon Failed

Question: I setup Openstack Horizon using the official Guide https://docs.openstack.org/horizon/ussuri/install/install-ubuntu.html
But now I can not login. I checked the credentials with the CLI client and they work without a problem.
In /var/log/apache2/error.log i see the following.
<code>[Sat Sep 19 16:10:39.087944 2020] [mpm_event:notice] [pid 32076:tid 140116107127744] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations
[Sat Sep 19 16:10:39.088076 2020] [core:notice] [pid 32076:tid 140116107127744] AH00094: Command line: '/usr/sbin/apache2'
[Sat Sep 19 14:11:47.362377 2020] [wsgi:error] [pid 32077:tid 140115930097408] /usr/lib/python3/dist-packages/scss/namespace.py:172: DeprecationWarning: inspect.getargspec() is deprecated since Python 3.0, use inspect.signature() or inspect.getfullargspec()
[Sat Sep 19 14:11:47.362467 2020] [wsgi:error] [pid 32077:tid 140115930097408]   argspec = inspect.getargspec(function)
[Sat Sep 19 14:11:47.494122 2020] [wsgi:error] [pid 32077:tid 140115930097408] [remote 172.17.2.20:48130] /usr/lib/python3/dist-packages/cinderclient/client.py:23: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
[Sat Sep 19 14:11:47.494163 2020] [wsgi:error] [pid 32077:tid 140115930097408] [remote 172.17.2.20:48130]   import imp
[Sat Sep 19 16:11:47.924935 2020] [authz_core:error] [pid 32092:tid 140115850520320] [client 172.17.5.2:47206] AH01630: client denied by server configuration: /usr/bin/keystone-wsgi-public
[Sat Sep 19 14:11:47.926407 2020] [wsgi:error] [pid 32077:tid 140115930097408] [remote 172.17.2.20:48130] INFO openstack_auth.forms Login failed for user "admin" using domain "Default", remote address 172.17.2.20.
[Sat Sep 19 14:11:49.704606 2020] [wsgi:error] [pid 32078:tid 140115988846336] /usr/lib/python3/dist-packages/scss/namespace.py:172: DeprecationWarning: inspect.getargspec() is deprecated since Python 3.0, use inspect.signature() or inspect.getfullargspec()
[Sat Sep 19 14:11:49.704674 2020] [wsgi:error] [pid 32078:tid 140115988846336]   argspec = inspect.getargspec(function)
[Sat Sep 19 14:11:49.824541 2020] [wsgi:error] [pid 32078:tid 140115988846336] [remote 172.17.2.20:48134] /usr/lib/python3/dist-packages/cinderclient/client.py:23: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
[Sat Sep 19 14:11:49.824582 2020] [wsgi:error] [pid 32078:tid 140115988846336] [remote 172.17.2.20:48134]   import imp
</code>
What can be the problem here and how to fix this? If you need additional information just ask and I will supply them.
Answer: Adjusting the apache2.conf according to https://ask.openstack.org/en/question/117138/failed-to-login-to-dashboard/ helped in my case
Comment: The configuration is already like that.

Login to Openstack Horizon Failed


What kind of snowboard would you recommend for a first board?

Question: I'm currently at an intermediate level of snowboarding. I can comfortably carve the snow and can make my way down easy/intermediate hills without falling.
I think it's time that I stop using rentals and buy my own board, as I want to go to the slopes more frequently.
What kind of snowboard would you recommend for a person looking for their first board?
Comment: To comment on close flags: I think this is a legit question as long as @Jonathan is not looking for a definite brand-model recommendation but rather a suggestion on the _type_ and _characteristics_ of the board which are general and there are certain _objective_ recommendations to be made for first time buyers.
Comment: I tried to keep the question generic for anybody else who may be trying to understand the different types of snowboards more.
Comment: Snowboarding already seems to be topic on Great Outdoors... Very simiar question here http://outdoors.stackexchange.com/questions/306/what-is-the-difference-between-the-different-types-of-snowboards-all-mountain
Comment: I'd also like to know the answer, especially in regards to the latest Rocker boards hype, when compared to Cambered ones. The OP indicated he want's to go to the slopes, so it leaves aside boards for freeride, parks and half-pipes. Still there's a lot left to answer, like: length, side-cut diameter, stiffness, directionality, ...
Comment: @JonathanSternberg I think some more specificity here would actually make a better question (I confess I know less than nothing about snowboarding). But if this type of recommendation is going to work its going to have to pretty specific. I'm skeptical at best (it reads like a shopping question), but I think there may actually be some value here in that (I assume) there are different types of boards (rather than specific brands and models) that would answer this question well.
Answer: This article lists several criteria to consider when choosing a first snowboard:

Price of the board - get a cheap board or a higher quality board? Buying new or used could also be a factor
Men or women's board - generally a criteria for women, since men/boys will usually get a board designed for men
The type of snowboarding the rider will be participating in - "Different snowboards are build for different terrains and different styles of riding."
Length of the board - varies greatly by individual preference

The article has one suggestion:

Also, factor in the stiffness of the board. As a beginner, you will
  probably want a soft-flexing board. One that is forgiving of mistakes.
Answer: I've been snowboarding for 5 years now but it was only this year I actually purchased my own board and binding. I chose the K2 Raygun and I would absolutely recommend it. It's not a beginner's board, and it's a great board for those who are intermediate and above. I consider myself an expert, and the guy at the shop said the Raygun is probably one of the best because you won't really have to upgrade as you get better.
However, here are some other practical tips when picking out a board:

Choose a board that matches your riding style. Do you like hitting the park, do you hate all those park rats, or are you a little bit of both?
Don't buy used. Buy last year's model. Equipment prices are can often seem very high, so you may think that buying used is the only way to go. Used equipment can be fine, but I wouldn't want to take the risk and have your board split or find that the binding screw-holes are stripped. Go to your local shop and find a board you like and see if you can find last year's model. The older the model, the cheaper, and as long as its in the past couple of years, you really won't lose much at in terms of features or quality. My Raygun is last years model, and from what I have seen, the only thing different I would have gotten by paying $150 more was some slightly altered graphics.
Choose a board that's offered at your local shop. Don't go on a ski trip 1500 miles away and decide to buy your new ride there. Get friendly with your local board shop and you'll find the owner/employees will usually offer great advice and possibly even discounts. If you have any problems with your board, they'll be able to help. Most shops will put your bindings on and set your stance for you right in the shop. That's something you can't get online.

And last of all, choose one that looks cool!
Answer: Since you've stated that you are at an intermediate level of riding, I would imagine that you have a style of riding that you prefer. Once you have decided what kind of riding you're going to do, remember that it's not just important to decide on what type of board you'll be riding, but the combination of boots and bindings as well.
Note: Different riders have different preferences and combinations and there are always exceptions to the rule, so bear this in mind when selecting a board.
Shapes
Before I list the different types of riding available, you should be aware of the different shapes that snowboards come in. The shape of the board will have pros and cons to it, so be sure to lay the board down and get a good look at its shape before deciding. Here are the three most common types of shapes (note: there are variations or these boards, so bear that in mind).
Camber
This is when the center of the board is at an upward curve, leaving the ends of the board to touch the ground. The center of the board will only touch the ground when a rider is on top.
Pros

Excellent stability
Increased edgehold
Great for carving
Greater "pop" (spring from jumping)

Cons

Requires more effort to turn
Easier to catch an edge

Rocker
Also known as reverse-camber, this board is the opposite of a camber, with the center of the board touching the ground and the ends up the board pointed upward and away from the ground.
Pros

Easier to turn
Easier to flex
Floats well in powder
Less likely to catch an edge

Cons

Less stability (can "wash out" easier)
Less "pop" (spring from jumping)

Flat
As the name implies, this board is completely flat from the center to the ends (with only the tip and tail curved).
Pros

Decent edgehold
Decent maneuverability
Good transitioning
Excellent for rails

Cons

The increased versatility sacrifices some stability and maneuverability
Some riders complain of a "dead" and/or "damp" feeling

Types of Riding
Now that you have an idea of the different shapes that snowboards can come in, here are the different types of riding available and the appropriate board and gear.
All-Mountain
This is probably the most common type of riding because most riders like to try a bit of everything. It is great for riding in both backcountry and groomed runs. This type of riding is less specialized than the others, which also makes it a great type of riding for beginners. Once you are past the beginner stage, you can specialize your riding or stay with all-mountain.
For this type of riding, your best bet is to purchase a stiffer (but not too stiff) board. Stand the board up vertically and push downwards from the top to determine the board's stiffness/flexibility. Different boots have different stiffness level. You can turn faster with softer boots, but you will have to use more strength from your legs and feet to stay stable. Most will advocate that beginners start off with a stiffer boot, but suggest that advanced riders take on a softer and more flexible boot.
Freestyle
If you're interested in performing tricks on the slopes and in the terrain park, then you will definitely want to purchase a shorter and more flexible board with twin tips. This will make it easier to absorb impacts from riding boxes, rails, etc. For increased control, I would recommend a lighter boot with a stiffer forward flex.
Note: This is for the terrain park. If you want to ride on the half-pipe, make sure that you invest in a stiffer board. On the contrary, stiffer boards will not absorb impact in the terrain park.
Freeride
If you like riding on steep slopes, deep snow, and backcountry, make sure that you purchase a stiffer board, so that you can pull off decent carving with excellent stability. I would suggest a stiffer boot that is soft on the upper part to make your transitions easier on your shins.
Racing
If you're interested in racing, there are specific narrower boards for racers with an emphasis on carving and speed. There are also plate bindings and hard plastic shells boots that differ from the typical gear you usually see in shops.
Conclusion
To end off, if you want to find the best deals, visit the shops during the spring and summer months and see what gear they have available. Like one user has already said, be sure to ask for stock from last year. I paid sixty dollars for a pair of boots that were two years old (but had never been used). You'd be surprised at the deals you can find.
Answer: For a first time buyer, I would actually advise you to spend more time worrying about your boots than the board.  Comfortable boots will improve your experience much more than the board will at your skill level.
Until you are more advanced and know what kind of terrain/style of board you really want, look for a simple All-Mountain board that is in your price range.  Make sure you are in the manufacturer's recommended weight range for the board's length.  Call it bias, but choose a brand that has been around for a while and has reviews online that don't report frequent problems.  Avoid particularly stiff boards or really soft park boards.  You're looking for the happy medium, which most low end boards cater to anyway.
Used Boards
I think you can have good success with a used board if you are careful. Used boards can save you  a lot of money and make it easier for you to get into the sport.  Alternately, the cash saved on a used board can help you spend more on boots (which I wouldn't buy used, unless the obviously had only been used once or twice) or more lift passes.  Cheaper boards may also let you try a new board more frequently as you are less invested.  Once you really know what you want, I would move on to new boards, ideally last years model.
When you buy a used board, if the owner appears trust worth ask how much it's been ridden.  If it has been pretty light, less than 10 or 15 trips, I wouldn't hesitate.  Do a little research into the board to find out what the original cost should have been and, if possible, how it was reviewed or if it showed any common problems.
You showed also do a solid visual inspection.  Warning flags:

Deep scratches: I would hesitate to buy a used board that had a deep scratches or core shots where you can see the material underneath the outer layer.
Base Repairs: If the base has been repaired, the owner probably rode the board pretty hard and/or in poor conditions. Ask about them, and you may also see spots where the repair color clearly doesn't match base of the board.
Lots of scratches: A lot of scratches, even if none are bad, also indicates the owner  mistreated the board.
Dull or blunted edges: The board should have a reasonably clean edge.  If the metal edge seems to have suffered a lot of damage or is blunted, don't buy it.  If the owner says the board was tuned for rails, It's not your board.
Rusty edges or edges peeling from the base: This board was not taken care of when it got home.
Any other notable damage
A combination of these that makes you uncomfortable.

If it looks sketchy, move on.  This is a market where buyers can be picky.
Answer: Short Answer: Something with a twin-tip and standard camber, but I'd spend the real money on your bindings.
Twin tip feels a little more natural than a directional, and the rentals you've been using are most likely conventional camber. The camber on things like Skate Bananas are AWESOME but might be an extra learning curve you don't need when you're just building confidence.
Get a couple ideas of what you like style/characteristic wise, then go cruise some rental places and see if they have any of them you can ride. I hated on Burton Customs HARD back in the day when they had the block stripe design and they were coming out with the rail binding system. Resisted buying one for a long time but once I rode it, it felt great and couldn't fight it anymore.
Definitely focus on your bindings though. Good one's make you feel like the board just grew out of your heels, bad one's will make it feel like you super-glued a 2x4 to your shoes.


Is it appropriate to use BPM to measure the tempo of a song?

Question: First, does tempo tell us how fast a song is? Second, is BPM the right way to measure the tempo of a song?
There are some songs like Illahi-Yeh jawaani hai deewani where the tempo is around 120 BPM but the song feels too fast because of so many notes per measure.
Would the notes per minute would be an appropriate measure of tempo?
Answer: Yes, the tempo describes the speed of a composition; it literally means "time" in Italian.
"BPM" stands for beats per minute; it's the musical equivalent of "miles per hour," and it is the standard way of measuring the tempo of a composition.
But the tempo is different from how many notes are played. A piece with a very fast tempo could use relatively few notes, whereas a very slow piece could use many many notes.
To go back to the "miles per hour" analogy, imagine driving 60 miles an hour but only passing two trees. Now imagine driving 1 mile an hour and passing 100 trees. Which is the best measurement of speed, miles per hour or trees per hour?
This is why it's more common to measure the BPM of a piece instead of the number of notes per minute.
Comment: In this particular case, I think it's incorrect to say "To kia hua" is 160 BPM; where did you get that number? It sounds like whoever determined that is actually measuring the tempo twice as fast; to me, "To kia hua" really has a tempo of 80 BPM, not 160. (And thus it does have a slower tempo than the first song.)
Comment: Shouldn't that be "beats per minute", not "beats per measure"?
Comment: I understood what you said. But, I think sometimes BPM doesn't give an insight into how fast a song is. For Example, a song like [To kia hua](https://www.youtube.com/watch?v=cOfPDZSqXMk) has tempo of around 160 bpm and the one which I have mentioned in my question has around 120 BPM. But, the latter one feels too slow. So, Am I correct in saying that It is defined in terms of BPM just for convention and may not be practical many times? @Richard
Answer: Yes, 'tempo' refers mainly to the speed of a song or piece.
BPM is the standard, objective way of measuring the tempo of a song or piece. It isn't the right way but rather a right way of measuring tempo. BPM stands for "beats per minute".
However, you can't measure the speed of a piece by number of notes in a minute. A note is a single pitch, and it can be held for as long (or as short) as denoted by the composer. Because not all notes are held for the same amount of time, you can't measure tempo with the number of notes in a minute (or the number of notes in any period of time).
In the song you linked, the notes sound very fast because their values are very short, and also at a pretty fast tempo.


How to combine data several studies with events?

Question: I have a compilation of following data on 10 studies, all of which had 2 groups: a control group which received usual treatment and an active group which received an intervention. The subjects were followed up for one year and any adverse events were counted. The data is as follows:
study   events_control  total_control   events_active       total_active
'First et al'       25              100         38                  200
'Second et al'      30              150         45                  400
etc

Hence, in the first study, 25 of 100 in control group had events while 38 of 200 had events in active group. And so on.
How can I combine all these data to determine if events in active group were more or less than those in control group? Thanks for your help.
Edit:
I was thinking of this option: since I have all the numbers, can I combine all 4 columns and get events in control and active groups and also total number of subjects with all studies taken together. Then I can compute overall odds ratio and its confidence interval.
Using this method 55/250 events occurred in the control group and 83/600 in active group, giving the overall OR is 0.57 with 95% CI of 0.39 and 0.83. These are not too different from the estimate of 0.536 (CI: 0.156, 0.916) using metafor package, as detailed in the excellent answer by @user33. Can this be a reasonable strategy? If not, what are the drawbacks?
Edit2: To take into account that data has come from different studies, can we use a mixed effects anova as follows:
aov(event_rate ~ treatment_type + Error(study_id/treatment_type), data=mydata)

Answer: In order to be able to conduct a meta-analysis based on your data (this seems to me what you want to do), you first have to select what kind of effect size you want to use. If all your data has this structure you could for instance select log odds ratios as effect size measure. For more information about effect sizes see Borenstein, Hedges, Higgins, and Rothstein (2009). Introduction to meta-analysis, Chapter 5.
Once you selected your effect size you have to compute for each study this effect size and its sampling variance. You could do this easily with for instance the metafor package in R.
To give an example:
ai = events_control
bi = no_events_control
ci = events_active
di = no_events_active
Assuming that your effect sizes of interest are log odds ratios you can compute these and its sampling variances by
library(metafor)

ai <- c(25, 30)
bi <- c(75, 120)
ci <- c(38,45)
di <- c(162, 355)

es <- escalc(ai = ai, bi = bi, ci = ci, di = di, measure = "OR")
> es
      yi     vi
1 0.3514 0.0858
2 0.6792 0.0667
You could use then these log odds ratios (yi) and the sampling variances (vi) for conducting different types of meta-analyses. The code below gives a standard random-effects meta-analysis:
> rma(yi = es$yi, vi = es$vi)

Random-Effects Model (k = 2; tau^2 estimator: REML)

tau^2 (estimated amount of total heterogeneity): 0 (SE = 0.1079)
tau (square root of estimated tau^2 value):      0
I^2 (total heterogeneity / total variability):   0.00%
H^2 (total variability / sampling variability):  1.00

Test for Heterogeneity:
Q(df = 1) = 0.7043, p-val = 0.4013

Model Results:

estimate       se     zval     pval    ci.lb    ci.ub
  0.5358   0.1937   2.7657   0.0057   0.1561   0.9155       **

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Another option to get the same output as presented above is not first computing the log odds ratios and its sampling variances via the escalc() function, but directly running the meta-analysis by
rma(ai = ai, bi = bi, ci = ci, di = di, measure = "OR")

For more information about meta-analysis please see the help functions of the metafor package or use the earlier mentioned book.
Comment: Good answer, but one point is misleading: The analysis is done with log-transformed odds ratios, not the odds ratios themselves. So, the aggregated value you get is also a log-OR (which of course can be easily back-transformed via exponentiation).
Comment: Yes, 0.5358 and the confidence interval are of course log odds ratios. Sorry for the confusion from my side ;-)
Comment: Thanks for a great answer. I will certainly look at metafor package. Please see the edit in my question above regarding a simpler option. Is it valid?
Comment: Also why did you choose a random effects rather than fixed effects here?
Comment: I would not apply the analysis strategy as you proposed in your edit because then you ignore the fact that the data come from different studies. To answer you question about random-effects or fixed-effect meta-analysis... I did not really choose for a random-effects meta-analysis, but this is the default option. Based on theoretical reasons you have to select either a fixed-effect meta-analysis or a random-effects meta-analysis
Comment: Can we use mixed effects anova to correct for data coming from different studies, as I have mentioned in my edit2 above.
Comment: Just to confirm: estimate of 0.5358  and confidence intervals of  0.1561 & 0.9155 in output of metafor function above are log(OR) values?


Is it possible to get a negative F-statistic (e.g. in ANOVA)?

Question: If so, why? If not, why not?
I'm thinking of an ANOVA context, but if the answer changes depending on context I would also be interested to know why that is.
Comment: @Zhang You are correct about the $F$ *distribution*, but a statistic is computed from data: it is not a distribution. For instance, to help clarify the distinction, we all know that a (squared) correlation coefficient is described by a non-negative distribution *when certain assumptions hold*, but nevertheless the $R^2$ statistic [*can* be negative.](http://stats.stackexchange.com/a/12929)  I wonder whether the present question might be of a similar nature.
Comment: F-statistics is always positive, since $F(m,n)\sim\frac{X_1^2(m)/m}{X_2^2(n)/n}$, which is always positive.
Comment: There *are* negative F-statistics: http://www.dorak.info/genetics/popgen.html (look about a third of the way down the page). They are, however, not the same as the F-statistics of ANOVA; about all they share is the name.
Comment: Assuming we're talking F in ANOVA - it depends on how the numerator and denominator are calculated; not every calculation is 100% guaranteed to yield a non-negative value for a notionally non-negative quantity.
Answer: Updated to account for the "F statistic" in population genetics that @whuber links to above.
It depends on what you mean by "F-statistic" and "context".  In statistics, the $F$-statistic is a ratio of variances.  As long as the "context" refers to this F-statistic, whether it comes from an ANOVA or a simple linear regression model will not matter.  Evidently however, there is something unrelated called an "F statistic" in population genetics.  Here is a quote from the linked page:

F statistics: The F statistics in population genetics has [sic] nothing to do the F statistics evaluating differences in variances. Here F stands for fixation index, fixation being increased homozygosity resulting from inbreeding.  ...
...The value of FIS ranges between -1 and +1. Negative FIS values indicate heterozygote excess (outbreeding) and positive values indicate heterozygote deficiency (inbreeding) compared with HWE expectations.

On the other hand, it is not possible to get a negative $F$-statistic of the type that occurs in statistics.  Think about what an $F$-statistic is.  All $F$-statistics are of the form:
$$
F = \frac{MS_{\rm effect}}{MS_{\rm residual}}
$$
So it could only be negative if (only) one of those values were negative.  But all mean squares are of the form:
$$
MS = \frac{SS}{df}
$$
So it, in turn, could only be negative if (only) one of those values were negative.  Now consider the form these must take:
$$
SS = \Sigma_i(x_i - \bar x)^2  \\
\text{and}  \\
df = N - \text{number of parameters estimated}
$$
Squaring any value yields a positive value.  I suppose you could say that if you were estimating more parameters than you had data, then you would get a negative df, and thus ultimately a negative $F$, but such a model would be unidentifiable, so this could not be done.  Thus, any $F$-statistic will always be non-negative.  For a given sample, it is possible to get $0$ if all conditional means are identical, or undefined if all data exactly equal the conditional means, but these are extremely unlikely to happen in practice even if the null hypothesis is completely true.
Comment: +1 However, all this seems to assume that the computer is able to compute with perfect accuracy, and that we always choose formulas that allow it to calculate with the best possible accuracy. The first is never true and the second only occasionally true at best. If we very carefully set up our code it should be possible to always avoid negative numerator and denominator in the F ratio ... but in practice it's quite clear that some programs have not been so carefully set up. This is less a problem now than it was 25 or 30 years ago, but it's still sometimes an issue... ctd
Comment: ctd ...  It's not very many years ago that Excel still used the unstable form of the one-pass formula for variance!


Country and Continent Dummies - Is there a point? What does the continent dummy pick up?

Question: I stumbled upon this question about including both country dummies and continent dummies.
AlexK comments: "Well, to be precise: let's say North America (continent) includes Canada, U.S. and Mexico. If you included all three countries as dummies, then the "North America" dummy would be perfectly collinear with those 3 country dummies and its coefficient could not be estimated. This is because for all observations in North America, the value of "North America" would just be the sum of values in three country dummies. If you have a continent dummy that is not exhaustive of the country dummies for that continent, then you would not have this issue for that continent."
As far as perfectly collinearity goes, that is clear and makes sense.  He then suggests to "remove one country on each continent, in addition to removing one continent." I am wondering if this would be a logical idea (apart from solving the a dummy variable trap) because of the following:
If you were to run the regression
$$y_i = B_0 + B_1countryDummies  + B_2continentDummies  + u$$
The software package is going to throw out two coefficients due to perfect collinearity.
In Stata, you can choose which it throws out by altering the order. So by doing:
$$y_i = B_0 + B_1countryDummies  + B_2continentDummies  + u$$
Two of the continents are thrown out. If you do:
$$y_i = B_0 + B_1countryDummies + B_2continentDummies  + u$$
Two countries are thrown out. Now the interesting things (which I should have maybe already realised) is that, when you look at the coefficients, the coefficients of $continent$ for the levels which are not thrown out will be exactly the same as the coefficients on the $countries$ when they are not thrown out.
Now I know that AlexK suggests to throw more variables out. Actually, one continent and a country for each continent.
What is achieved by AlexK's suggestion?
And what is now picked up by the variable $continent$ if we assume that $y_i$ is income for example?
In other words, if you are already controlling for country effects, what would there be left to be controlled for at the continental level?
Comment: Are you familiar with [dummy variables](https://en.wikipedia.org/wiki/Dummy_variable_(statistics))? Also see https://stats.stackexchange.com/questions/7948/when-is-it-ok-to-remove-the-intercept-in-a-linear-regression-model
Comment: @Tim Thank you for your comment. I am familiar with dummy variables. Am I missing something obvious? I am going trough your CrossValidated right now, but I have not yet stumbled on anything that really relates to my question (Are you assuming that there is no intercept in my model? Because that was not intended.. I will change it).
Comment: @Tim I have made some tweaks in the hope my question is a bit clearer now.
Comment: If you dummy encode categorical variable with $k$ categories, you always end up with $k-1$ binary columns that encode it. The remaining category is the baseline, relative to which are parameters for the other categories. So if you have two categories, you drop one of the categories from each of them i.e. intercept + 0 + 0. This is what the comment says.
Comment: @Tim I think we are having some miscommunication (or as I said, I am missing something very very obvious). In any case, as I explained, I am familiar with dummy variables. My question is about what possible variation there is left. It is nice that they are no longer perfectly collinear, but I am wondering what has been achieved by doing so.
Answer: Let's suppose your dummy variables follow the suggestion are
<code>            Ct1 Cy1 Cy2 Cy3
    USA      0   0   0   0
    Canada   0   1   0   0
    Mexico   0   0   1   0
    Germany  1   0   0   0
    France   1   0   0   1
</code>
Then

the base data will be as if for the USA (no dummies),
the coefficient of $Ct_1$ will be for Germany (representing base Europe) relative to the USA,
the coefficient of $Cy_1$ will be for Canada relative to the USA,
the coefficient of $Cy_2$ will be for Mexico relative to the USA,
the coefficient of $Cy_3$ will be for France relative to Germany, and if you want France relative to the USA then you need to add the coefficient of $Ct_1$ and the the coefficient of $Cy_3$

This allows every country to have distinct dummy variables and so coefficients.  Having the continental dummies does not affect the number of dummy variables: overall counting continents and countries you still need $1$ less than the total number of countries, as each extra continent dummy allows you to reduce the number of country dummies by one, following the suggestion
Comment: Thank you for your answer. I see that I was looking at this all wrong, although I guess it confirms my suspicion that the coefficient on "continent" is not what you (read I) think it is (as in has little to do with continental variation), if I understand your explanation correctly.


identify each iphone device in iOS SDK

Question: I need to determine each iOS device.
In the past SDKS, there's a way to identify UUID by the command
 [[UIDevice currentDevice] uniqueIdentifier];

But in iOS 5.0, this function is deprecated. Is there any way to do this similar task?
Thank you!
Comment: What are you trying to do with the UUID?
Comment: Possibile duplicate of: http://stackoverflow.com/questions/7273014/ios-unique-user-identifier
Comment: Check Apple documentation about CFUUIDRef:
https://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFUUIDRef/Reference/reference.html
Comment: Check This [Tutorial](http://oleb.net/blog/2011/09/how-to-replace-the-udid/) about how to create UDID in ios5.
Answer:
uniqueIdentifier
An alphanumeric string unique to each device based on various hardware
  details. (read-only) (Deprecated in iOS 5.0. Instead, create a unique
  identifier specific to your app.) @property (nonatomic, readonly,
  retain) NSString *uniqueIdentifier Special Considerations
Do not use the uniqueIdentifier property. To create a unique
  identifier specific to your app, you can call the CFUUIDCreate
  function to create a UUID, and write it to the defaults database using
  the NSUserDefaults class. Availability
Available in iOS 2.0 and later.
Deprecated in iOS 5.0.

Related Sample Code
GKTank

Declared In UIDevice.h

So use CFUUIDCreate and you will get and uniqID and save it to the NSUDefaults.
Note that the CFUUIDCreate will give you a new id on each call. That is why you have to save it.
If you really need to know if the app was installed on that device you can read the mac address of the wifi card.
Answer: For iOS 6 and latter you can use.

NSString *U_ID = [[NSUUID UUID] UUIDString];
Answer: Please check the answer of @suchi here How to create a GUID/UUID using the iPhone SDK.
use [[UIDevice currentDevice] uniqueDeviceIdentifier] to retrieve the unique identifier (it's a hash of your Bundle ID + MAC address)
use [[UIDevice currentDevice] uniqueGlobalDeviceIdentifier] to retrieve a global unique identifier (it's a hash of the MAC address, used for tracking between different apps).

identify each iphone device in iOS SDK


Como não aplicar opacidade em um elemento filho?

Question: Eu tenho uma div com opacidade aplicada, porém essa div possui elemento filho. Eu não quero que seja aplicada opacidade a esses elementos filhos, teria alguma maneira de resolver isso?
Exemplo:
http://jsfiddle.net/qSsC3/1/
Código do link:

.div-pai{
  width: 400px;
  height: 400px;
  background-color: black;
  position: fixed;
  opacity: 0.7;
}
 .div-filho{
  width: 150px;
  height: 150px;
  position:absolute;
  top: 50%;
  left: 50%;
  background: blue;
  margin-top: -75px;
  margin-left: -75px;
  opacity: 1;
}

Answer: Acredito não ser possível, porém há workarounds.
Se precisar de opacidade apenas no background, é possível aplicar uma cor rgba:
background-color: rgba(0,0,0,.7);

Fiddle. Note que não há suporte para IE<=8.
Caso precise aplicar a opacidade em todo elemento e não somente no background, terás que quebrar a hierarquia e transformá-los em irmãos.
Há uma terceira forma, que funciona caso você esteja buscando um efeito overlay. Seria criar um pseudo-elemento ::before que cobre todo elemento .div-pai e fica em baixo do .div-filho:
.div-pai:before {
    content: '';
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
    background: white;
    opacity: 0.3;
}

Fiddle.
Desta forma o :before é um irmão da .div-filho e fica em baixo desta sem a necessidade de z-index devido à ordem dos elementos. Note que a .div-pai necessita de um position diferente de static, não adicionei isto ao código pois a sua .div-pai já é fixed.
A .div-filho também precisa de um position diferente de static para aparecer sobre o :before. Caso contrário, elementos posicionados sempre aparecem sobre elementos estáticos (vide Empilhamento sem z-indexem inglês).

Quanto a suporte para IE8, é possível utilizar um .gif/.png com transparência como background, ou aplicar a propriedade filter proprietária do IE5-8. Não tive sucesso aplicando o filter à um pseudo-elemento, mas funciona se poluirmos a marcação um pouco (adicionando uma div).
Para testar no IE8: http://jsfiddle.net/qSsC3/12/show/

.overlay {
    content: '';
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
    background: white;

    filter: alpha(opacity=30); /* IE5-8 */
    opacity: 0.3; /* IE9+ e todos browsers modernos */
}

Ou, sem criar nenhum outro elemento, outra forma que funciona cross-browser (IE8+), utilizando uma imagem como background: http://jsfiddle.net/qSsC3/17/show
.div-pai:before {
    content: '';
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;

    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNXG14zYAAAAWdEVYdENyZWF0aW9uIFRpbWUAMDIvMDMvMTSFgaz/AAAADUlEQVQImWP4//+/LwAJSQNLpIypVwAAAABJRU5ErkJggg==);
}

Codifiquei a imagem como Data-URI para ficar mais fácil de colocar na resposta, mas não fará diferença linkar para um arquivo .png/.gif (exceto que geraria uma request extra). Também vou notar que IE<8 não suporta Data-URIs, embora acredito que poucas pessoas ainda se importam com suporte para IE<=7.
Comment: Excelente solução, funcionou perfeitamente. Obrigado pela ajuda, já não vou precisar usar imagens... !
Comment: funcionou muito bem as suas sugestões, porém no ie8 eu não obtive sucesso... Seria a unica solução para ie8 uma imagem de background?
Comment: @DenisBernardo sim, um `.gif`/`.png` com transparência funcionaria bem. Dê-me um segundo, é possível utilizar o `filter` do IE também.
Answer: Não é possível, a opacidade dos filhos sempre vai ser relativa à dos pais. Se você está precisando mudar apenas a cor do background, poderia em vez de opacity. modificar o atributo background:
.div-pai {width: 400px;height: 400px; position: fixed; background-color: rgba(0, 0, 0, 0.7); }

Answer: Nesse caso, aconselharia a usar uma imagem em .png com opacidade como background no elemento pai, uma imagem de 1px por 1px repetindo, fica bem leve, alguns browser mais antigos não dão suporte a essa propriedade.
Answer: Bom, não é possivel fazer da forma que estás querendo, porém uma sugestão é remover o div.pai e apenas utilizar o div.filho e colocar uma borda nele, que resultaria na mesma coisa, porém seu elemento filho "central" não ficaria com opacidade, veja o exemplo que fiz no JSFiddle
Utilizei do seguinte código CSS:
.div-filho{
    width: 150px;
    height: 150px;
    position:absolute;
    background: blue;
    border: 150px solid rgba(0,0,0,0.75);
}

E removei o div.pai do HTML.
Answer: Já passei por caso semelhante, mas a Opacidade no Javascript é sempre herdada pelos elementos, não tem como você remover ela, então o que eu costumo fazer é criar um elemento que fique exatamente na mesma posição e dimensão do elemento que seria o pai com transparência, porém esse elemento não é filho, está após o elemento transparente e contém o que seriam os filhos dele.
O resultado pode ser visto nesse jsfiddle.
Será compatível com todos os browsers e pode ser aplicado a qualquer elemento.
Exemplo:

Existem várias soluções para contornar o problema quando é background, mas se sua div, está por cima de uma imagem, vídeo, ou algo do gênero, eu pessoalmente prefiro esta solução, pois é genérica a todos os casos.


AcquireTokenByUsernamePassword throws System.AggregateException and MsalServiceException

Question: AcquireTokenByUsernamePassword throws System.AggregateException and MsalServiceException:
1st Exception:

System.AggregateException: 'One or more errors occurred. (Federated
service at
https://autologon.microsoftazuread-sso.com/domain.com/winauth/trust/2005/usernamemixed?client-request-id=[ID]
returned error: Authentication Failure )'

2nd Exception:

MsalServiceException: Federated service at
https://autologon.microsoftazuread-sso.com/domain.com/winauth/trust/2005/usernamemixed?client-request-id=[ID]
returned error: Authentication Failure

string clientId = "client-id";
string tenant = "tenant-id";

// Open connection
string authority = "https://login.microsoftonline.com/" + tenant;
string[] scopes = new string[] { "user.read" };
IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
                          .WithAuthority(authority)
                          .Build();
var securePassword = new SecureString();
foreach (char c in user.Password.ToCharArray())  // you should fetch the password
securePassword.AppendChar(c);  // keystroke by keystroke
var results = app.AcquireTokenByUsernamePassword(scopes, user.UserName, securePassword).ExecuteAsync().Result.IdToken;

Comment: Have you checked your password? Is it correct?
Comment: Could you please check if you have enabled `Allow public client flows``?
Comment: @JimXu Allow public client flows is enabled
Comment: @Tassisto Have you enabled mfa for your user account?
Comment: @JimXu where can I enable this?
Comment: please refer to https://learn.microsoft.com/en-us/azure/active-directory/authentication/tutorial-enable-azure-mfa
Comment: I get this Message --> AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application: 'api://guid'.
Comment: Could you please tell me how you configure redirect URL?
Comment: Under Azure Active Directory > App Registrations > My App > Authentication  > https:// myapi.azurewebsites.net/signin-oidc
Comment: Could you please tell me which type of application you use?
Comment: I thought I had the solution but I was accessing the API with an ID token, which isn't a best practice. I have to access API's with the Access Token. I check the validity of the Access token on jwt.io, it is valid when decoding with algorithm RS256.
Answer: Your scope is set incorrectly. I think you want to call your custom api instead of ms graph api, so you should get a token for your expose api. The scope you set in the code is the permissions of ms graph api instead of your custom api scope.
Therefore, you need to set the scope to: api://{api app client id}/.default.
Comment: what is .default for ?
Comment: @Tassisto The `/.default` scope is a way to silently request. see the explanation of the official doc:  https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope
Comment: It says: "Then the code returns an id_token, rather than an access token."
Isn't it required to access an API with an access token instead of an id token?
Comment: @Tassisto  Of course, you must use an access token.