Change the formatting of a label in Drupal 7

Question: When viewing the teaser for a node, all labels are output as uppercase.  I want them titleized (meaning the first letter of every word is capitalized).  What's the best way to go about doing this?  Currently there is no CSS effecting the label field, so I know Drupal is just outputting all capitals.
I don't know why Drupal is rendering the label text in all capitals, so I was looking for a theme preprocessor function in the Drupal 7 API that could maybe dig into the label data and then change it to all lowercase from there, but I couldn't find anything concrete.  I could then apply CSS to format the label how I want.  However, until I know HOW Drupal renders the labels I can't apply any CSS that will have the desired effect.
EDIT: I changed the title from "Change label in teaser output to lowercase" to "Change the formatting of a label in Drupal 7" as I think that the question can be answered in a less specific sense, and I may have found the reason my labels are turning up in all caps.
Comment: If you're going to downvote the question, at least explain why you're downvoting so the reasoning can be considered and addressed.
Comment: Ive upvoted the answer to neutralize the downvote. I think the question is more than fair. Theming fields, or finding where someone else might have hooked into the field rendering process is pretty common.
Answer: Something is odd about this as you say your labels are in lower case but they are being rendered in all caps.  I would view it with Firebug / Chrome Web Inspector to make sure there is not a higher level selector in your CSS that's transforming it to all caps in which case you would have a tough time going back to title case if your selector does not override the one thats making it all caps.
At any rate you can't transform all caps back to titlecase but you could with jQuery:
https://stackoverflow.com/questions/3471157/css-text-transform-capitalize-on-all-caps
Also see this for reference, http://www.w3.org/TR/CSS21/text.html#propdef-text-transform
"capitalize
Puts the first character of each word in uppercase; other characters are unaffected."

But before you go an add some JQuery, I would take a serious look at your CSS with Firebug to make absolute sure that something is not transforming it to all caps in the first place.
Comment: I've been through the element hierarchy and there is definitely no text-transform affecting things.  I agree, there is definitely something amiss.  This code is inherited so the previous developer might have done something a bit odd somewhere, I'm trying to find what he changed :)
Comment: ah, that could be key "`This code is inherited so the previous developer might have done something a bit odd somewhere`." That's happened to me a few times. I am guessing the previous dev might have hacked something up somewhere in the theme. Perhaps try doing some searches in your IDE to try to  find out where this might have been done.
Answer: Okay, since this code was inherited I began to suspect that the previous dev had done some fishy things, which he in fact did.  Here is the code I found in the ridiculously huge template.php file.
function ccom_field($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '
' . strtoupper($variables['label']) . '
'; //<-- HERE the colon
  }

  // Render the items.
  $output .= '
';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}

Notice the line that has the strtoupper call... That was the issue.  I removed that and everything is now how it should be.
There's been a couple of other methods mentioned here for altering the data stored in the label variable during the rendering process.  They all would be effective, including the method I just posted.  The method I posted has the added effect of allowing you to change the structure of the field as it is rendered in your theme.  For the sake of rewarding other's efforts in answering this ridiculous question, I'll find the next closest answer and set it as the accepted answer.
Comment: Glad you found the problem, I think the previous dev created a lot of code and overhead for no good reason and in a ridiculous manner. In the end, to simply add odd / even, one line of JQuery targeting the element would have worked.
Comment: After looking up the default field implementation on the Drupal site, this actually was the default, just copy pasted, but just capitalizing all of the labels and stripping the colon.  The odd even classes are good for CSS.  He wasn't entirely crazy, just, weird...
Answer: This is likely controlled by CSS, you can change it by adding a rule to your CSS file similar to this:
.node-teaser label{text-transform:capitalize}

You might need to target the particular element a bit more precisely so have a look with Firebug to see what rule is setting the text-transform on the labels currently.
Comment: Well just go and change the labels to the case you want them in, as pointed out by dymonkeyninja they shouldn't be in all caps anyway it doesn't make sense
Comment: @Lester, see my answer. You'd be better to not store the labels as uppercase.
Comment: Tried this already.  This doesn't have the desired effect if all of the letters are already uppercase, it simply changes the first letter of every word to be capitalized, which obviously is already the case if everything is already uppercase.  Here's the fiddle http://jsfiddle.net/h5q4x/
Comment: @Clive You can't just say "go and change the labels" because the question I asked was "How do I change the labels to do this..." implying that I don't know how to change the way the labels are rendered by Drupal.  I know it doesn't make sense to output them this way, and I don't know why they're being output as uppercase, that's why I want to change it.
Comment: @LesterPeabody: So are you saying you've been into the field settings for each field and checked that the label is being set in normal case, and that somewhere in the process Drupal is converting them in PHP to uppercase? Your question is not clear.
Comment: I clarified my question a few times, you can look through the edit history.  However, yes I've checked the field settings with the inspector in Chrome and there is no text-transform property being set on the label field currently.  So, somewhere in the Drupal engine the text is being converted to uppercase via PHP, that's why I was looking for a preprocess function to fix the issue.
Comment: @LesterPeabody: Gotcha. If you're still interested [`theme_form_element()`](http://api.drupal.org/api/drupal/includes--form.inc/function/theme_form_element/7) is the theme function you'd want to override
Comment: @LesterPeabody: Have you gone to the field display page in drupal for your content type to check the actual case of the labels there?  (e.g. www.yourdomain.com/admin/structure/types/manage/yourcontenttype/fields)
Comment: I have, and they're in titleized format.
Comment: I noticed you've marked this as the answer, what was the bottom line, how did you fix this?
Answer: First of all you need to establish what html is wrapping your labels, you can use firebug or just look for them in the source html.
For instance I find the labels on a site I happen to be working on are wrapped in
, so some css like .field-label { text-transform: lowercase; text-transform: capitalize;} in your theme's stylesheet should do the trick.
Comment: Unfortunately this is not the way CSS works.  CSS simply specifies rules, it doesn't take any action.  A browser looks through these rules and then cascades them.  So, the only property the browser would apply would be the last text-transform you mentioned, and would apply `text-transform: capitalize;` to the field, which is already rendered in full uppercase, resulting in no visual change.  Make sense?
Comment: You are absolutely right, I just ran a test and it will only apply the last rule, so not so much "last-rule wins" as last-rule-applied". Interesting ;-)
Answer: Seeing as this is a style issue you could do this using the text-transform property in CSS:-
text-transform: capitalize;

Really, your labels you've defined in Drupal shouldn't all be in uppercase. It would be better to use text-transform: uppercase; for your form labels if that is what you are aiming for. Style should be kept separate from content.
Comment: See my comment to Clive.


How to use Amazon SES in a PHP Class

Question: I installed the AWS PHP SDK using composer but am unsure how to use AWS SES within my existing class.
I used the sample code in the SES PHP Docs website. I was able to create a test.php file to test out that code and it works. However when trying to use SES within my class I get error 500 within my page.
Ive tried including the autoload file in the Class file.
<?php

namespace Main\messaging;
use vendor\Aws\Ses\SesClient;
use vendor\Aws\Exception\AwsException;
class Email
{
   public function sendEmail(){
       // Create an SesClient. Change the value of the region parameter if you're
// using an AWS Region other than US West (Oregon). Change the value of the
// profile parameter if you want to use a profile in your credentials file
// other than the default.
       $SesClient = new SesClient([
           'profile' => 'default',
           'version' => '2010-12-01',
           'region'  => 'us-west-2'
       ]);

// Replace firstname.lastname@example.com with your "From" address.
// This address must be verified with Amazon SES.
       $sender_email = 'firstname.lastname@example.com';

// Replace these sample addresses with the addresses of your recipients. If
// your account is still in the sandbox, these addresses must be verified.
       $recipient_emails = ['firstname.lastname@example.com'];

// Specify a configuration set. If you do not want to use a configuration
// set, comment the following variable, and the
// 'ConfigurationSetName' => $configuration_set argument below.
//$configuration_set = 'ConfigSet';

       $subject = 'Amazon SES test (AWS SDK for PHP)';
       $plaintext_body = 'This email was sent with Amazon SES using the AWS SDK for PHP.' ;
       $html_body =  '
AWS Amazon Simple Email Service Test Email
'.
           '
This email was sent with '.
           'Amazon SES using the '.
           'AWS SDK for PHP.
';
       $char_set = 'UTF-8';

       try {
           $result = $SesClient->sendEmail([
               'Destination' => [
                   'ToAddresses' => $recipient_emails,
               ],
               'ReplyToAddresses' => [$sender_email],
               'Source' => $sender_email,
               'Message' => [
                   'Body' => [
                       'Html' => [
                           'Charset' => $char_set,
                           'Data' => $html_body,
                       ],
                       'Text' => [
                           'Charset' => $char_set,
                           'Data' => $plaintext_body,
                       ],
                   ],
                   'Subject' => [
                       'Charset' => $char_set,
                       'Data' => $subject,
                   ],
               ],
               // If you aren't using a configuration set, comment or delete the
               // following line
               //'ConfigurationSetName' => $configuration_set,
           ]);
           $messageId = $result['MessageId'];
           echo("Email sent! Message ID: $messageId"."\n");
       } catch (AwsException $e) {
           // output error message if fails
           echo $e->getMessage();
           echo("The email was not sent. Error message: ".$e->getAwsErrorMessage()."\n");
           echo "\n";
       }
   }
}

What I expected was to see the the confirmation message echo out and receive the email. However this is not what I get. I dont think I am properly including the AWS library into my class.
Comment: What *do* you get?
Comment: If "nothing" means a blank page, you should check the error logs or adjust your error reporting settings. 500 + a blank page means you've got a useful error message sitting around somewhere.
Comment: I get nothing when using it within my class. When I call the function I get an error 500 in browser. However if I dont use it within a class and just call the php file through the terminal I get a successful email send.
Comment: (If you're using Composer, I'd bet that error is that you're using `use vendor\...`. The `vendor` part should usually be left off.
Comment: I am using composer. Ill give that a try
Comment: Checked logs and found this message PHP Fatal error:  Uncaught Error: Class 'vendor\\Aws\\Ses\\SesClient' not found
Comment: Yup, so that's what I thought. Take off the `vendor` bits in your `use` statements.
Comment: Yep that got rid of that error. Now trying to figure out this error Uncaught Aws\Exception\CredentialsException: Cannot read credentials from /.aws/credentials that file is definitely in that directory
Comment: I hardcoded my keys and it worked, not sure why using the ~/.aws/credentials file did not work
Comment: Chances are your webserver is running as something like a `www-data` user rather than your main user, which'll mean *your* `~` is not *its* `~`.
Comment: I changed permissions to that directory to be owned by www-data recursively but didnt do anything
Comment: That's not what I'm saying. I'm saying your credentials file may be expected to be somewhere like `/home/www-data/.aws/credentials`.
Answer: try this code:
<?php
require 'vendor/autoload.php';

use Aws\Ses\SesClient;
use Aws\Exception\AwsException;

Comment: Could you please explain a bit more about what you think is wrong and why this change will fix it?

How to use Amazon SES in a PHP Class


Embed rate number up down widget in panel node

Question: I am using rate module and the number up down widget, and in the settings for this module I had set it to appear at the top of content. It was appearing fine. However, now I am using a panel for this node and the widget no longer appears as expected. I need to embed it into my panel. How would I go about this? I have done a few searchs and found rate_embed, but I am not having any luck getting this to work. I have tried the following. My rate widget is called 'points', and its settings are at /admin/structure/rate/:
function:
<?php rate_embed(&$node, $machine_name, $mode = RATE_FULL); ?>

What I tried:
<?php print rate_embed($node, 'points', $mode = RATE_FULL); ?>
<?php echo rate_embed($node, 'points', $mode = RATE_FULL); ?>

this was giving an error that rate_embed was acting on a non-object.
Comment: you have to display only count value alone?
Comment: No, I want to display the actual widget itself in my panel so that a plus / minus number button appears for the user to vote.
Answer: You can try the following code.
 $up_down = rate_generate_widget('1', 'node', {current node id}, RATE_FULL, TRUE, FALSE, NULL);
 print render($up_down);

Comment: this module could also work nicely with this code: http://drupal.org/project/widgets
Comment: how would I get the current node id in there? curently that code gives:  Parse error: syntax error, unexpected '{' in /home/andrewwe/public_html/wequest.co.uk/modules/php/php.module(80) : eval()'d code on line 4
Comment: You can get node id as arg(1). Verify did you enabled rating for that particular content type /admin/structure/rate/


Required sample size to reduce the interval size by half

Question: I have a small doubt regarding a statistics problem and would like a confirmation.
If we want to reduce the length by half of the confidence interval (at $95\%$), we should:
Multiply the size of the sample by $2$ ? $4$ ? or by $8$ ?
As for me, I think that the sample size should be multiplied by $4$.
Why do I think so?
We are looking for $\frac{1}{4}E$, $E$ being one side of the interval:
$$\frac{1}{4}E= 1.96 * \frac{\sigma}{\sqrt{n}} $$
So,
$4n=(1.96)^2 * \frac{\sigma^2}{E^2}  $
So it should be multiplied by $4$, as said before.
Am I right ?
Thanks in advance.
Regards
Answer: Because this is a homework tag, I won't give you the explicit confirmation/explanation, but a simple way to check yourself is to simulate this with known $\sigma$ and known confidence intervals.
Simulate using a variety of sizes for $n$ and see if you can deduce the relationship explicitly. The main things to think about are
1- How the value of $\sqrt{n}$ changes as $n$ changes
2- How the symmetry of the confidence interval effects the answer, i.e, accounting for the $+/-$


How to Iterate Through GroupBy - Getting Duplicate Key Error

Question: I can't figure out how to do this right.  I want to be able to iterate this dictionary because it's for my unit test and so each pair for me is important to have in here
var invalidPageNumberAndSize = new Dictionary<string, string>
{
    {"0", ""},
    {"", "0"},
    {"abc", ""},
    {"", "abc"}
}.GroupBy(p => p.Key);

foreach (var invalidPagingCombination in invalidPageNumberAndSize)
{

    Console.WriteLine(invalidPagingCombination.Key + " " + invalidPagingCombination);
}

Comment: You're adding two dictionary items with an empty string as the key.
Comment: As I think eddie_cat was trying to say, you can not have 2 entries in a `Dictionary` with the same key.
Answer: You are entering two keys in your dictionary that are empty:
 {"", "0"},

and
 {"", "abc"}

change this to
{"foo", "abc"}

and the error will go away.  A dictionary can only have 1 instance of each key.  You could also use a List of Tuples if you needed to:
var list = new List<Tuple<string, string>>();
list.Add(new Tuple<string, string>("", "apple"));
list.Add(new Tuple<string, string>("", "zebra"));

Comment: @CoffeeAddict  BTW, decision on whether to use Tuples or KeyValuePairs really depends on your usage.  This is a good link for the test between the two:  http://www.dotnetperls.com/tuple-keyvaluepair.  Usually, Tuples is a better route to go in terms of performance due to KeyvaluePairs being implemented as a struct.
Answer: Use a collection of KeyValuePair instead of dictionary:
var invalidPageNumberAndSize = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("0", ""),
    new KeyValuePair<string, string>("", "0"),
    new KeyValuePair<string, string>("abc", ""),
    new KeyValuePair<string, string>("", "abc")
}.GroupBy(p => p.Key);


Custom control rendering twice

Question: I am extending sap.ui.unified.Calendar with a custom control, overriding the renderDays() function, to place an extra span tag in each day div.
The console indicates the hours array is undefined. It throws the error found below, but continues to work afterwards. This error prevents using the header arrows to move between months in the calendar. Is this rendering twice? Why is hours[] undefined at first but ok after?
If I put all the code into a single file JSBin, it does not error.
JSBin
The top of the code for the custom control:
sap.ui.unified.Calendar.extend("control.TimeCalendar", {
    metadata : {
        properties : {
            "hoursData" : "string[]"
        }
    },

  renderer: {
    renderDays: function(oRm, oCal, oDate){
        var hours = oCal.getHoursData();

Console output:
Cannot read property 'length' of undefined

Excerpt from the custom control TimeCalender.js. This is inside the do...while loop which places each day on the calendar. Where the function places the date, I also include a span tag with a number retrieved from the array 'hours'.
oRm.write("");

if ( (hours.length>i) && (hours[i].day == oDay.getUTCDate()) ) {
    oRm.write("");
    oRm.write(hours[i].hours);
    oRm.write("");
    if(i <= hours.length) { i++; }
}

oRm.write(oDay.getUTCDate());
oRm.write("");

Answer: Taking a guess, I would say that in your non-jsbin scenario you are using databinding and the data is either received asynchonously from the back-end or it is set after the first rendering?
In that case the hoursdata value is set to undefined, which causes the error.
If you define the property like this:
properties : {
    "hoursData" : { type: "string[]", defaultValue: [] }
}

...this way you make sure that there is always an array, which has a length property.
Comment: Synchronous loading is the wrong way to do it in almost every case - it blocks the UI thread and often leads to poor user experience. You should use the default value and think about some logic inside your renderer - for example abort when no data is set so you can use async loading when it is needed.
Comment: You can still check for undefined before the error happens: "if (!oControl.getHoursData()) return;"
Comment: Thanks for your help. I believe the problem was with it loading asynchronously, as you said. When I changed the model in the controller to read from a variable I defined in the same file, instead of pointing to the url of a json file, it worked. So I changed the controller to use loadData and set the async flag to false, and that fixed the problem. I later changed to an OData service which also had async to false, and it worked, too.
Comment: I understand it's a bad idea to load it synchronously. However I still get the undefined error when changing my OData call to be asynchronous even with your defaultValue: [] suggestion. I have used typeof to determine the type of getHoursData() and it is an object, not undefined which I did not expect.

Custom control rendering twice


Finding dim(span(s)) Using a Basis

Question: I need to find the question for this answer.
Use the Simplified Span Method to find a simplified general form for all the vectors(basis) in $\mathrm{span} (S)$, where
$$S=\{ [1,2,3,-1,0] ,[3,6,8,-2,0], [-1,-1,-3,1,1], [-2,-3,-5,1,1]\}$$ and find $\dim(\mathrm{span}(S))$  using this basis.
I found the basis of $\mathrm{span}(S)$ as:
enter image description here
Comment: What is your question?  You have found a basis for the span... now what?  All you are left with is deciding what the dimension is?  All you need to do for that is to check how many vectors were used in the basis...
Comment: What is the "Simplified Span Method?"
Answer: Great! now, if you calculated right, then $dim (Sp { S})=3$

Finding dim(span(s)) Using a Basis


How to debug cannot access services from outside Kubernetes cluster (onpremise) with load balancer IP

Question: I have an on-premise Kubernetes (v1.24) cluster setup with cri-o as container runtime, calico as cni and metallb for load balancer IPs.
Masters and workers OS runs on rockylinux9, selinux enabled but firewalld disabled and kube proxy uses ipvs mode.
I have setup bgp peering with Mikrotik router and saw the IP ranges that I've set gets advertised to the router through the routes section with a record that shows
10.16.0.0/28 reachable through bridge
My test Nginx service external ip is 10.16.0.1, curling the ip from masters, workers and within pods works which it return the default Nginx welcome page but when curling from my laptop it just hanging until timeout and selinux audit logs does not show anything violations
nmap the ip shows port 80 opened, ping the ip also works, traceroute also show correct response and for insanity check I also delete the service and do the nmap, ping and traceroute again and it stop working as expected.
# commands below runs on my laptop
# that connected to local network
# but result also same as I run on
# other devices on the network

# ---

❯ nmap -T4 10.16.0.1
Starting Nmap 7.94 ( https://nmap.org ) at 2023-09-23 11:01 +07
Nmap scan report for 10.16.0.1
Host is up (0.0048s latency).
Not shown: 997 closed tcp ports (conn-refused)
PORT    STATE    SERVICE
22/tcp  open     ssh
80/tcp  filtered http
179/tcp open     bgp

# ---

# the 192.168.88.43 is local master node ip
❯ ping 10.16.0.1
PING 10.16.0.1 (10.16.0.1): 56 data bytes
64 bytes from 10.16.0.1: icmp_seq=0 ttl=64 time=9.144 ms
92 bytes from 192.168.88.1: Redirect Host(New addr: 192.168.88.43)
Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst
 4  5  00 0054 c3b4   0 0000  3f  01 94cc 192.168.88.111  10.16.0.1

64 bytes from 10.16.0.1: icmp_seq=1 ttl=64 time=3.003 ms
92 bytes from 192.168.88.1: Redirect Host(New addr: 192.168.88.43)
Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst
 4  5  00 0054 c9cc   0 0000  3f  01 8eb4 192.168.88.111  10.16.0.1

64 bytes from 10.16.0.1: icmp_seq=2 ttl=64 time=3.209 ms
92 bytes from 192.168.88.1: Redirect Host(New addr: 192.168.88.43)
Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst
 4  5  00 0054 305b   0 0000  3f  01 2826 192.168.88.111  10.16.0.1

64 bytes from 10.16.0.1: icmp_seq=3 ttl=64 time=2.557 ms
92 bytes from 192.168.88.1: Redirect Host(New addr: 192.168.88.43)
Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst
 4  5  00 0054 25d8   0 0000  3f  01 32a9 192.168.88.111  10.16.0.1

64 bytes from 10.16.0.1: icmp_seq=4 ttl=64 time=3.594 ms
x92 bytes from 192.168.88.1: Redirect Host(New addr: 192.168.88.43)
Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst
 4  5  00 0054 4016   0 0000  3f  01 186b 192.168.88.111  10.16.0.1

64 bytes from 10.16.0.1: icmp_seq=5 ttl=64 time=2.974 ms

64 bytes from 10.16.0.1: icmp_seq=6 ttl=64 time=4.397 ms
^C
--- 10.16.0.1 ping statistics ---
7 packets transmitted, 7 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 2.557/4.125/9.144/2.119 ms

# --

# 192.168.88.1 is my default gateway
❯ traceroute 10.16.0.1
traceroute to 10.16.0.1 (10.16.0.1), 64 hops max, 52 byte packets
 1  192.168.88.1 (192.168.88.1)  3.669 ms  2.713 ms  2.552 ms
 2  10.16.0.1 (10.16.0.1)  3.303 ms  3.292 ms  3.145 ms

checking for nginx info
❯ kubectl get pods -o wide
NAME                                 READY   STATUS    RESTARTS        AGE   IP              NODE           NOMINATED NODE   READINESS GATES
nginx                                1/1     Running   0               39m   172.16.29.154   k8s-worker-0   <none>           <none>

❯ kubectl get svc
NAME                 TYPE           CLUSTER-IP     EXTERNAL-IP   PORT(S)                               AGE                              42h
kubernetes           ClusterIP      10.96.0.1      <none>        443/TCP                               2d5h
nginx                LoadBalancer   10.97.153.41   10.16.0.1     80:30422/TCP                          40m

❯ kubectl get endpoints
NAME                 ENDPOINTS                                                               AGE                                                    42h
kubernetes           192.168.88.43:6443                                                      2d5h
nginx                172.16.29.154:80                                                        41m

❯ kubectl describe service nginx
Name:                     nginx
Namespace:                default
Labels:                   <none>
Annotations:              metallb.universe.tf/address-pool: public
                          metallb.universe.tf/ip-allocated-from-pool: public
Selector:                 app=nginx
Type:                     LoadBalancer
IP Family Policy:         SingleStack
IP Families:              IPv4
IP:                       10.97.153.41
IPs:                      10.97.153.41
LoadBalancer Ingress:     10.16.0.1
Port:                     <unset>  80/TCP
TargetPort:               80/TCP
NodePort:                 <unset>  30422/TCP
Endpoints:                172.16.29.154:80
Session Affinity:         None
External Traffic Policy:  Local
HealthCheck NodePort:     31552
Events:
  Type    Reason       Age   From                Message
  ----    ------       ----  ----                -------
  Normal  IPAllocated  41m   metallb-controller  Assigned IP ["10.16.0.1"]

calico configs
❯ kubectl describe bgppeer
Name:         global-peer
Namespace:
Labels:       <none>
Annotations:  <none>
API Version:  projectcalico.org/v3
Kind:         BGPPeer
Metadata:
  Creation Timestamp:  2023-09-22T06:37:35Z
  Resource Version:    430164
  UID:                 62d549ac-b7ed-47ab-bc2c-b94de8a08939
Spec:
  As Number:  65530
  Filters:
    default
  Peer IP:  192.168.88.1
Events:     <none>

❯ kubectl describe bgpconfiguration
Name:         default
Namespace:
Labels:       <none>
Annotations:  <none>
API Version:  projectcalico.org/v3
Kind:         BGPConfiguration
Metadata:
  Creation Timestamp:  2023-09-22T06:37:24Z
  Resource Version:    839696
  UID:                 fd6aef3e-0a4c-4ecc-afe4-09395b76d107
Spec:
  As Number:                  65500
  Node To Node Mesh Enabled:  false
  Service Load Balancer I Ps:
    Cidr:  10.16.0.0/28
Events:    <none>

❯ kubectl describe bgpfilter
Name:         default
Namespace:
Labels:       <none>
Annotations:  <none>
API Version:  projectcalico.org/v3
Kind:         BGPFilter
Metadata:
  Creation Timestamp:  2023-09-22T06:37:34Z
  Resource Version:    434512
  UID:                 df8b5aeb-e25e-481c-9403-fcc54727eea8
Spec:
  exportV4:
    Action:          Reject
    Cidr:            10.16.0.0/28
    Match Operator:  NotIn
Events:              <none>

❯ kubectl describe installation
Name:         default
Namespace:
Labels:       <none>
Annotations:  <none>
API Version:  operator.tigera.io/v1
Kind:         Installation
Metadata:
  Creation Timestamp:  2023-09-21T05:32:53Z
  Finalizers:
    tigera.io/operator-cleanup
  Generation:        3
  Resource Version:  1052996
  UID:               2f7928cd-3815-42be-9483-512f2f39fcf9
Spec:
  Calico Network:
    Bgp:         Enabled
    Host Ports:  Enabled
    Ip Pools:
      Block Size:          26
      Cidr:                172.16.0.0/16
      Disable BGP Export:  false
      Encapsulation:       None
      Nat Outgoing:        Disabled
      Node Selector:       all()
    Linux Dataplane:       Iptables
    Multi Interface Mode:  None
    nodeAddressAutodetectionV4:
      First Found:  true
  Cni:
    Ipam:
      Type:                    Calico
    Type:                      Calico
  Control Plane Replicas:      2
  Flex Volume Path:            /usr/libexec/kubernetes/kubelet-plugins/volume/exec/
  Kubelet Volume Plugin Path:  /var/lib/kubelet
  Logging:
    Cni:
      Log File Max Age Days:  30
      Log File Max Count:     10
      Log File Max Size:      100Mi
      Log Severity:           Info
  Node Update Strategy:
    Rolling Update:
      Max Unavailable:  1
    Type:               RollingUpdate
  Non Privileged:       Disabled
  Variant:              Calico
Status:
  Calico Version:  v3.26.1
  Computed:
    Calico Network:
      Bgp:         Enabled
      Host Ports:  Enabled
      Ip Pools:
        Block Size:          26
        Cidr:                172.16.0.0/16
        Disable BGP Export:  false
        Encapsulation:       None
        Nat Outgoing:        Disabled
        Node Selector:       all()
      Linux Dataplane:       Iptables
      Multi Interface Mode:  None
      nodeAddressAutodetectionV4:
        First Found:  true
    Cni:
      Ipam:
        Type:                    Calico
      Type:                      Calico
    Control Plane Replicas:      2
    Flex Volume Path:            /usr/libexec/kubernetes/kubelet-plugins/volume/exec/
    Kubelet Volume Plugin Path:  /var/lib/kubelet
    Logging:
      Cni:
        Log File Max Age Days:  30
        Log File Max Count:     10
        Log File Max Size:      100Mi
        Log Severity:           Info
    Node Update Strategy:
      Rolling Update:
        Max Unavailable:  1
      Type:               RollingUpdate
    Non Privileged:       Disabled
    Variant:              Calico
  Conditions:
    Last Transition Time:  2023-09-23T15:08:30Z
    Message:
    Observed Generation:   3
    Reason:                Unknown
    Status:                False
    Type:                  Degraded
    Last Transition Time:  2023-09-23T15:08:30Z
    Message:
    Observed Generation:   3
    Reason:                Unknown
    Status:                False
    Type:                  Ready
    Last Transition Time:  2023-09-23T15:08:30Z
    Message:               DaemonSet "calico-system/calico-node" is not available (awaiting 1 nodes)
    Observed Generation:   3
    Reason:                ResourceNotReady
    Status:                True
    Type:                  Progressing
  Mtu:                     1450
  Variant:                 Calico
Events:                    <none>

calicoctl node status shows

metallb config
❯ kubectl -n metallb-system describe ipaddresspool
Name:         public
Namespace:    metallb-system
Labels:       <none>
Annotations:  <none>
API Version:  metallb.io/v1beta1
Kind:         IPAddressPool
Metadata:
  Creation Timestamp:  2023-09-22T07:57:01Z
  Generation:          3
  Resource Version:    434511
  UID:                 aa2d0e08-4fee-4ce1-a822-9bf4f52a3a3c
Spec:
  Addresses:
    10.16.0.0/28
  Auto Assign:       true
  Avoid Buggy I Ps:  true
Events:              <none>

So how to debug this, why I cannot access to the Nginx service from outside cluster.
update0
Running tcpdump -n -i ens18 host 10.16.0.1 on both master and worker node and then trying to run ping 10.16.0.1 and arping -I 10.16.0.1 on other machine outside of the cluster give me these on both master and worker node
# ping only show on master node
# 192.168.88.111 is the other machine(my laptop)
dropped privs to tcpdump
tcpdump: listening on ens18, link-type EN10MB (Ethernet), snapshot length 262144 bytes
15:31:29.842416 IP (tos 0x0, ttl 63, id 33297, offset 0, flags [none], proto ICMP (1), length 84)
    192.168.88.111 > 10.16.0.1: ICMP echo request, id 14677, seq 0, length 64
15:31:29.842465 IP (tos 0x0, ttl 64, id 38235, offset 0, flags [none], proto ICMP (1), length 84)
    10.16.0.1 > 192.168.88.111: ICMP echo reply, id 14677, seq 0, length 64
15:31:30.846173 IP (tos 0x0, ttl 63, id 14503, offset 0, flags [none], proto ICMP (1), length 84)
    192.168.88.111 > 10.16.0.1: ICMP echo request, id 14677, seq 1, length 64
15:31:30.846206 IP (tos 0x0, ttl 64, id 38836, offset 0, flags [none], proto ICMP (1), length 84)
    10.16.0.1 > 192.168.88.111: ICMP echo reply, id 14677, seq 1, length 64

# arping received 0 responses
# arping showing both on master and worker node
15:33:08.269603 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 10.16.0.1 (Broadcast) tell 192.168.88.63, length 46
15:33:09.269759 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 10.16.0.1 (Broadcast) tell 192.168.88.63, length 46
15:33:10.269768 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 10.16.0.1 (Broadcast) tell 192.168.88.63, length 46
15:33:11.269725 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 10.16.0.1 (Broadcast) tell 192.168.88.63, length 46
15:33:12.269575 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 10.16.0.1 (Broadcast) tell 192.168.88.63, length 46
15:33:13.269695 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 10.16.0.1 (Broadcast) tell 192.168.88.63, length 46
15:33:14.269685 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 10.16.0.1 (Broadcast) tell 192.168.88.63, length 46
15:33:15.269715 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 10.16.0.1 (Broadcast) tell 192.168.88.63, length 46
15:33:16.269754 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 10.16.0.1 (Broadcast) tell 192.168.88.63, length 46

Answer: I would suggest asking this in Calico Users slack.
In your BGPConfigurations I saw that you have disabled fullmesh, is that intentional? are you using route-reflectors?
  Node To Node Mesh Enabled:  false
I would start by checking the BGP route on Mikrotik
Something like "adjust if you are running older version of router OS"
 /ip/route/print detail from=[find gateway~"^192.168.88.63[0x00-0 xff]*"]
If that looks correct I would check if LB is accisable via Miki
/tool/fetch http://10.43.1.1
Then check the Bird protocol status, try birdcl from calico-node pods
kubectl exec -n calico-system ds/calico-node -c calico-node -- birdcl show protocols
kubectl exec -n calico-system ds/calico-node -c calico-node -- birdcl show route


Dart unittest produces unhelpful output

Question: I am working through the AngularDart tutorial and trying to write unit tests as I complete the exercises.
I have a test that looks like this:
test('should convert sugar ingredient to maple syrup', inject((SugarFilter filter) {
  var r1 = new Recipe(null, null, null, ['has sugar in ingredients '], 'bla', null, null);
  var r1New = new Recipe(null, null, null, ['has maple syrup in ingredient '], 'bla', null, null);
  var r2 = new Recipe(null, null, null,[ 'has pure ingredients'], 'bla', null, null);
  var inList = [r1, r2];
  var outList = [r1New, r2];
  expect(filter(inList), equals(outList));
}));

The test fails with this output:
Test failed: Caught Expected: [Instance of 'Recipe', Instance of 'Recipe']
  Actual: [Instance of 'Recipe', Instance of 'Recipe']
   Which: was <Instance of 'Recipe'> instead of <Instance of 'Recipe'> at location [0]

I tried modifying the existing test for 'categoryFilter' to make that fail and I get the same, rather unhelpful output.
Is there a way to make the output from the comparison of two objects more meaningful?
Answer: What exactly do you expect when you compare two lists which contain different objects?
Should they be equal because each list contains two Receipe instances?
What is filter() anyway?
Two lists are only equal if it is the same list:
expect(inList, equals(inList));

You can use a matcher like everyElement, orderedEquals or unorderedEquals to compare the contents of a list. But if you put different instances into the list even if they are of the same class the comparsion will still fail.
If you want the comparsion to behave differently you have to override the equals() method of the Receipe class (this requires also to override get hashCode).
You could override the toString() method in Receipe to get a better error message, for example adding the value of some fields to the output string.
@override
String toString() => '${super.toString()} ${name}'; // I don't know if the Receipe class has a name field though

Dart unittest produces unhelpful output


Do you need to change instances to rates for OLS regressions

Question: I am interested in performing a regression on data on a population. This population causes events X and Y. I have monthly data for population, event X, and event Y. Do I need to change my variables X and Y into rates (X divided by population) before running the regression?
Some details about the model: the population are students at a university. That's one IV. Another IV will be a yet to be determined demographic characteristic. As output variables, I have cheating instances and plagiarism instances. I'm going to combine these into one DV "academic dishonesty" and run three models, one with cheating as a DV, the other with plagiarism, and the last with academic dishonesty as the DV. In all cases university population and demographics will be the two IVs.
Should I change these cheating and plagiarism instances into rates? Thanks for the advice.
Comment: It depends on the model and on what these events are. Could you edit this question to include some more information about that?
Comment: You can model the rate of, say, cheating, without transforming anything by adding log(population) as an offset to the regression model.  In R: `model <- glm(cheating ~ demog1 + demog2 + offset(log(population)), family=poisson)` where all but the demographic variables are numbers of students.
Comment: Usually events occur *within* a population, and are not *caused* by it. I feel there's lots more required before we can answer this question.
Comment: Fair enough. Added details. At first I did not think rates were necessary but a colleague recommended switching to rates to control for the effect of population (i.e. more students = more cheating) as a way to control for population size. But I feel as though since I'm already including population in my model, changing to rates will "double control" for population. Thoughts?
Comment: Thanks folks. I liked going through your suggestions and I've worked it out. Enjoy your weekends
Answer: I would consider a log transformation, which imposes a constant elasticity of substitution on your model.
If you estimate
$$ (NoCases) = \alpha + \beta (Characteristics) $$
In this case, $\beta$ is the increase on the number of cases resulting from a marginal increase in the characteristics.
You will of course see that larger universities have a higher number of cases. You could control for university size by including that as a characteristic, but there may still be some effects that you'll want to control for in another way. Your colleague is correct that you should do something to control for this.
Using rates is one way, but I would suggest you estimate
$$ log(NoCases) = \alpha + \beta(log(Characteristics))$$
In this case, $\beta$ represents the percent increase in cases due to a percent increase in your characteristics. This solves your rates issue, and will likely correct some outlier problems, too!
Answer: A feature of models in which the dependent variable is a rate per unit of population is that they are likely to be subject to heteroscedasticity. Other things being equal, smaller populations are likely to be associated with greater variability in rates.  An easy way to see this is to compare the rates for one student and for a large population of students, making the simplifying assumption that no student has more than one instance of academic dishonesty in any one month.  The rate for the one student must be either 0 or 1. Within the population, however, it is likely that some students are honest and some dishonest, so that the rate will be between 0 and 1. A larger population allows for more averaging out than a smaller one.
Although heteroscedasticity does not lead to bias in regression coefficients estimated by OLS, it does imply that the conventionally calculated standard errors of those coefficients are unreliable.  This would mean, in particular, that a test of significance of the estimated coefficient of your demographic characteristic would be unreliable.
The above is not intended to suggest that you should avoid using rates.  However, if you do use rates and you intend to apply hypothesis tests or calculate confidence intervals, then you need to consider how you will address heteroscedasticity arising from different population sizes.  Three approaches you might consider are:

OLS with robust or heteroscedasticity-consistent standard errors.
Weighted least squares, giving a higher weighting to larger populations since they are expected to be associated with lower rate variability.
Calculating your regression on a sub-sample of your data selected so that the populations are fairly similar.  This is unlikely to be helpful unless you have data for a very large number of universities.

All these approaches have their pros and cons.  One of many sources which consider in general terms the relative merits of 1 and 2 above is here.


How to assess whether a set of cells all have a specified value in Excel

Question: I have collected a bunch of statistical results in the form of "YES" and "NO" strings.
Now I would like to have a summary cell displaying "YES" if all these cells equal "YES" (or are empty).
Answer: Would you settle for a "TRUE" instead of a "YES" in case there are no "NO" cells?  If so, in a nearby cell type
=countif([first cell in range]:[last cell in range],"NO")
Then in an adjoining cell type
=and([previous cell]="0")
As an example, if you had YES or NO strings in A1 through A20, then in A22 you would type
=countif(a1:a20,"NO")
and in A21 you would type
=and(a22="0")
Comment: You could combine these into `=if(countif(a1:a20,"NO")=0,"YES","NO")`
Comment: Sorry for late reply, but THANKS. I ended up using `=IF(COUNTIF(B5:B17, "<>Yes"), "No", "Yes")`


Indexing tables jQuery

Question: In this HTML page I have many tables...
I just need to assign an unique id to each row.
I have also a jQuery function that add and remove single rows:

         something1

         something2

// add rows
$(document).on('click', '#add_row' , function() {
    $(add_row_string).appendTo(tab_voce);
});
// index table
$(document).on('click' , '#index_row' , function(){
    var n_tr = $('#tab_1 tr').size()-1;
    $('tr.voce > td:first-child').text("voce_"+ n_tr);  //I cant fix the selector
                                                        //In this way it selects every  of every table
});

Answer: You can simplify everything out to get what I believe you are trying to achieve.
The below creates new rows and also gets the current clicked row's id and outputs it. You can then use this ID for whatever you need it to do.

$(document).on('click', '#add_row', function() {
  var i = $('#tab_voce tr').length + 1;
  $('#tab_voce').append('
New Row	New Row	');

});
$(document).on('click', '.row', function() {
  $('#clicked_row span').text($(this).attr('id'));
});

      something1

      something2

<button id="add_row">Add Row</button>

Clicked Row:

Indexing tables jQuery


Display guitar or boxed one?

Question: I'm planning to buy a new guitar (an Ibanez RGA-T62 if it makes any difference) from a brick-and-mortar shop and my dillema is if I should get the display unit that potentially 100s of customers have tried or ask for a boxed one (they do have it)? The salesmen insists (perhaps too strongly IMHO) that the display unit has been properly set up by them and that I would be better off taking that.
Since I am not very experienced player, I am not entirely sure what to do here. Any advice?
Comment: @AlexandruCristescu that 9 gauge would just be referring to the high E string. There are different sets that all start at 9, and go to very different numbers on the other side. Usually you would say something like 9 - 46 or 9 - 42, or something like that. Do you know WHY you want the high E to be .09 gauge? I fell into the trap of trying to just do what my guitar idols chose, and that is usually a bad choice imo. Try a bunch and find your own preference. Of course you may have already done that haha
Comment: Hi @Tim, can you please change that to an answer. I think it is worth having as an answer post rather than a comment.
Comment: What if as I beginner I don't know what to ask for a setup? I know I want to try 9 gauge strings on it and that I like low action, but that's about it...
Comment: I only ever take the display one if there's a discount for it or if I really want the model and it's the only one available.
Comment: @Tim: Stores that don't include a set up should be cheaper than those that do, but having a guitar set up before purchase may not always add value.  If one would want to use one's own labor to modify the guitar in ways that would alter the setup, it would be better for the store to either offer to do the setup after purchase, or offer a discount for going without the initial setup and then do the later setup on a "cash" basis.
Answer: That could go either way.  Many mom and pop music shops will include the set up as part of the retail cost, other will charge a fee for set up.  That varies depending on complexity and location.  In NJ it's ~$75 for a set up and new strings.
The situation sounds similar to buying a house.  New houses have never been touched, but they haven't settled and could have problems.  I would expect that your new guitar has a warranty (1 year I'd guess) so you should be covered if its defective.  I am not impressed by the argument that the display model is "set up" because it may not feel just right for you and needs to be set up again.  So why not go for the brand-spanking-new guitar?
The other issue is condition.  Does the display model have chips in the finish, wear and tear on the hardware, pick guard, etc?  Are there pick and finger nail scratches on the top paint?  If it looks used I wouldn't take it.
Also, will the display model have the same warranty as a new one?  I'd find out.
Last but not least, are they offering a discount on the display?
It's a matter of weighing all these factors and whether or not you feel comfortable with the display model.  You have to live with the choice.
I'd find out the following.

What is the warranty on the guitar (manufacturer and store)?
Will the display model have the same warranty?
How much does the store charge for a set up, is it free with purchase?
Is there a discount for the display model?

And go from there.
Comment: So, after my after thought I'd lean to the box guitar.
Comment: Often times, the guitar on display is actually the only guitar of that model in the store.  I think only cheaper guitars will have multiple unboxed models available.
Comment: That depends on the store.  The OP didn't state if it's guitar center or some neighborhood store.  I've been in stores with a $5,000 ax on display and a dozen more in the back room.  You can't really make a seeping judgement like that.
Comment: Thank you for the answer. The answers to the follow up questions are as follows:
1. 3 years from the store (not sure about manufacturer)
2. yes
3. first one is included with the purchase
4. no discount

By the sound of it you are leaning towards getting the brand new one and having them set it up too, right?
Comment: It seems like the store wants to avoid doing the set up again (which I would make the do since I have my own action preference) and like all businesses they want to squeeze as much $$ out of their stock as they can.  I have purchased used guitars and been very happy with them so I am not really leaning either way.  If they will stand by the product the only issue is whether it have any apparent damage.  One thing I didn't think of is that the pots on guitars are cheap and usually break after 100's of turns.  These may be over worked on the display model.
Answer: A lot of stuff you buy is "used" as a display model.
Cars and clothing come to mind.
It would be very hard to find a car that hasn't been test driven and I wouldn't ever buy a car without test driving it first. I always assume clothes have been tried on before and wash them after buying, because yuck, and I always want to make sure the clothes fit, don't have holes etc, before buying.
For me I would:

Want to try the guitar that I was actually purchasing. So if you go for the in the box one, ask to play it first.
Make sure the guitar is in perfect condition. Even the one in the box could have a scratch or a ding....and you should be the one to scratch and ding it! (preferably when diving off the stage.)
Make them do a setup for either model. the one that has been played by others should get new strings and a set up. the one in the box should get a set up.

Remember when buying something it is a negotiation. That sales dude wants to make the sale. You want the guitar. Negotiate: Here is my money, I want to play the one in the box, and get a set up, if I find it is in good condition/like the way it feels.
EDIT: all that being said both my Taylor acoustic, and my Fender Strat have been on display and I bought them.
Answer: I would prefer the display guitar. If it had any problems, they would have been fixed (or the display model replaced). The one new-in-box might be shinier and have no buckle rash, but it might have loose connectors or some other issue. In general, if something is all electronic, I would prefer new-in-box.
Comment: This.  Buy the guitar you try out.  Not one in the box, which may be warped, dried out, have been dropped, a bent neck, etc.  Inspect the guitar you tried out, and if it all looks, sounds, plays good buy it.  If anything isn't perfect, then don't buy it.  When buying a guitar off the rack, make sure you know what comes with it and insist on getting those items (paperwork, bag, case, etc).
Comment: I've bought guitars from major retailers that have had problems that were not at all fixed. Maybe this is more of a big box store problem, but the techs just don't have the time or the mandate to make sure every guitar in the store is in perfect shape.
Answer: As the 'properly set up' one has been played by potentially hundreds, it ought to come along at a better price, possibly with the start of buckle rash thrown in! A 'brand new' one will probably need a set-up, for the purchaser in particular, rather than a generic set-up for the shop. That ought to be contained within the price. Or, as I oft say, look around for a pre-loved model which will usually save 30-40%.
Answer: What will your "pride of ownership" be? If you've thought about it this long, there's probably some amount of importance for you that you'll get a brand-new out-of-the-box new guitar, and if so, trust your instincts. It's your money and you should get what you want for it.
(It seems odd to me that the shop owner is pushing the display model, since he surely would have to take the boxed one and put it on the shelf to sell it. But that's his business. If he's keen to sell the display model, then he should be discounting it to the point where it's attractive to the customer.)

Display guitar or boxed one?


Programmatically generated views

Question: I'm adding a view at the top of the current view programmatically by inflating it from an XML.
The problem is that after the view is added and showed, I'm still able to press button from the underlying view. How can I prevent this?
Comment: Remove/disable/hide the other view/button?
Comment: I need to keep the other ones, can't hide or remove them
Answer: Try to set an empty click listener for the view at the top.
For example:
myTopView.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View view) {
          // empty, just to consume the event.
      }
});

It will do nothing except to consume the event and not let pass it to underlying view.
Answer: Your new view needs to handle the touch event instead. Just create a new, empty touch listener for this purpose:
myTopView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;//true to specify that the event was consumed by the top view
    }
});

Programmatically generated views


Ocultar uma div ao clicar no botão com CSS

Question: Tem como ocultar uma DIV com esse botão ai?

.button {
  display: block;
  position: absolute;
  width: 240px;
  height: 80px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
      -ms-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
  background: -webkit-linear-gradient(top, #11181f 0%, #161f29 100%);
  background: linear-gradient(to bottom, #11181f 0%, #161f29 100%);
  border-radius: 40px;
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1);
  cursor: pointer;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.button span {
  position: absolute;
  display: block;
}
.button span:first-of-type {
  z-index: 100;
  top: 4px;
  right: 4px;
  width: 160px;
  height: 72px;
  background: -webkit-linear-gradient(top, #2c3e50 0%, #1e2a36 100%);
  background: linear-gradient(to bottom, #2c3e50 0%, #1e2a36 100%);
  box-shadow: 0 6px 4px rgba(255, 255, 255, 0.1) inset, 0 2px 0px rgba(255, 255, 255, 0.2) inset, 0 -6px 0px rgba(0, 0, 0, 0.2) inset, 0 -2px 0px rgba(0, 0, 0, 0.2) inset, 0 2px 2px rgba(0, 0, 0, 0.4), -4px 2px 8px rgba(0, 0, 0, 0.4), 2px 0 1px rgba(242, 201, 197, 0.5) inset;
  border-radius: 36px;
  -webkit-transition: right 400ms cubic-bezier(1, 0, 0, 1), box-shadow 400ms ease;
          transition: right 400ms cubic-bezier(1, 0, 0, 1), box-shadow 400ms ease;
}
.button span:nth-last-of-type(-n+2) {
  z-index: 10;
  top: 4px;
  width: 116px;
  height: 72px;
  -webkit-transition: opacity 800ms ease 100ms;
          transition: opacity 800ms ease 100ms;
}
.button span:nth-last-of-type(-n+2):after {
  position: absolute;
  top: 26px;
  line-height: 1;
  font-family: "Open Sans";
  font-weight: 800;
  font-size: 24px;
  color: white;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2), 0 0 20px #ffffff;
}
.button span:nth-of-type(2) {
  left: 4px;
  background: -webkit-linear-gradient(top, #c0392b 0%, #d65548 100%);
  background: linear-gradient(to bottom, #c0392b 0%, #d65548 100%);
  border-top-left-radius: 36px;
  border-bottom-left-radius: 36px;
  box-shadow: 4px 4px 12px 4px rgba(0, 0, 0, 0.5) inset, 0 -2px 8px rgba(0, 0, 0, 0.4) inset;
}
.button span:nth-of-type(2):after {
  content: "OFF";
  left: 18px;
}
.button span:last-of-type {
  right: 4px;
  background: -webkit-linear-gradient(top, #2ecc71 0%, #7ee2a8 100%);
  background: linear-gradient(to bottom, #2ecc71 0%, #7ee2a8 100%);
  border-top-right-radius: 36px;
  border-bottom-right-radius: 36px;
  box-shadow: -4px 4px 12px 4px rgba(0, 0, 0, 0.5) inset, 0 -2px 8px rgba(0, 0, 0, 0.4) inset;
  opacity: 0.2;
}
.button span:last-of-type:after {
  content: "ON";
  right: 22px;
}
.button input[type="checkbox"] {
  display: none;
}
.button input[type="checkbox"]:checked ~ span:first-of-type {
  right: 76px;
  box-shadow: 0 6px 4px rgba(255, 255, 255, 0.1) inset, 0 2px 0px rgba(255, 255, 255, 0.2) inset, 0 -6px 0px rgba(0, 0, 0, 0.2) inset, 0 -2px 0px rgba(0, 0, 0, 0.2) inset, 0 2px 2px rgba(0, 0, 0, 0.4), 4px 2px 8px rgba(0, 0, 0, 0.4), -2px 0 1px rgba(209, 245, 224, 0.5) inset;
}
.button input[type="checkbox"]:checked ~ span:nth-of-type(2) {
  opacity: 0.2;
}
.button input[type="checkbox"]:checked ~ span:last-of-type {
  opacity: 1;
}

  <input type="checkbox">

 conteúdo aqui que oculta ao selecionar OFF

Comment: Acho que está a complicar algo simples. Ocultar ou mostrar com base no `checked` é uma linha em javascript: `onchange="document.querySelector('div').style.display=this.checked==true?'none':''"`
Answer: Uma forma de resolver isso só com HTML e CSS é retirando o elemento input de dentro da label, mas depois disso vc vai ter que usar um id no checkbox e colocar um for="" na label. Para entender melhor por que isso é preciso leia essa resposta: O atributo for de um elemento label serve pra alguma coisa?
Depois de tirar o checkbox de dentro da label, e usar o for para checkar o checkbox quando clica na label basta usar o seleto irmão + para setar as regras e mostrar e esconder a div com display:none/block nessa reposta vc pode ler mais sobre o seletor adjacente + O que significa o sinal de + no CSS?
Ok, agora que vc já viu como tudo funciona a regra principal é essa. Quando vc tem um input:check + label + div (ou seja, um checkbox checado, seguido de uma label, seguido de uma div vc mostra essa div)
Clique no btn para mostrar a div

.button {
  display: block;
  position: absolute;
  width: 240px;
  height: 80px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
      -ms-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
  background: -webkit-linear-gradient(top, #11181f 0%, #161f29 100%);
  background: linear-gradient(to bottom, #11181f 0%, #161f29 100%);
  border-radius: 40px;
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1);
  cursor: pointer;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.button span {
  position: absolute;
  display: block;
}
.button span:first-of-type {
  z-index: 100;
  top: 4px;
  right: 4px;
  width: 160px;
  height: 72px;
  background: -webkit-linear-gradient(top, #2c3e50 0%, #1e2a36 100%);
  background: linear-gradient(to bottom, #2c3e50 0%, #1e2a36 100%);
  box-shadow: 0 6px 4px rgba(255, 255, 255, 0.1) inset, 0 2px 0px rgba(255, 255, 255, 0.2) inset, 0 -6px 0px rgba(0, 0, 0, 0.2) inset, 0 -2px 0px rgba(0, 0, 0, 0.2) inset, 0 2px 2px rgba(0, 0, 0, 0.4), -4px 2px 8px rgba(0, 0, 0, 0.4), 2px 0 1px rgba(242, 201, 197, 0.5) inset;
  border-radius: 36px;
  -webkit-transition: right 400ms cubic-bezier(1, 0, 0, 1), box-shadow 400ms ease;
          transition: right 400ms cubic-bezier(1, 0, 0, 1), box-shadow 400ms ease;
}
.button span:nth-last-of-type(-n+2) {
  z-index: 10;
  top: 4px;
  width: 116px;
  height: 72px;
  -webkit-transition: opacity 800ms ease 100ms;
          transition: opacity 800ms ease 100ms;
}
.button span:nth-last-of-type(-n+2):after {
  position: absolute;
  top: 26px;
  line-height: 1;
  font-family: "Open Sans";
  font-weight: 800;
  font-size: 24px;
  color: white;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2), 0 0 20px #ffffff;
}
.button span:nth-of-type(2) {
  left: 4px;
  background: -webkit-linear-gradient(top, #c0392b 0%, #d65548 100%);
  background: linear-gradient(to bottom, #c0392b 0%, #d65548 100%);
  border-top-left-radius: 36px;
  border-bottom-left-radius: 36px;
  box-shadow: 4px 4px 12px 4px rgba(0, 0, 0, 0.5) inset, 0 -2px 8px rgba(0, 0, 0, 0.4) inset;
}
.button span:nth-of-type(2):after {
  content: "OFF";
  left: 18px;
}
.button span:last-of-type {
  right: 4px;
  background: -webkit-linear-gradient(top, #2ecc71 0%, #7ee2a8 100%);
  background: linear-gradient(to bottom, #2ecc71 0%, #7ee2a8 100%);
  border-top-right-radius: 36px;
  border-bottom-right-radius: 36px;
  box-shadow: -4px 4px 12px 4px rgba(0, 0, 0, 0.5) inset, 0 -2px 8px rgba(0, 0, 0, 0.4) inset;
  opacity: 0.2;
}
.button span:last-of-type:after {
  content: "ON";
  right: 22px;
}
input[type="checkbox"]  {
  display: none;
}
input[type="checkbox"]:checked + .button span:first-of-type {
  right: 76px;
  box-shadow: 0 6px 4px rgba(255, 255, 255, 0.1) inset, 0 2px 0px rgba(255, 255, 255, 0.2) inset, 0 -6px 0px rgba(0, 0, 0, 0.2) inset, 0 -2px 0px rgba(0, 0, 0, 0.2) inset, 0 2px 2px rgba(0, 0, 0, 0.4), 4px 2px 8px rgba(0, 0, 0, 0.4), -2px 0 1px rgba(209, 245, 224, 0.5) inset;
}
input[type="checkbox"]:checked + .button span:nth-of-type(2) {
  opacity: 0.2;
}
input[type="checkbox"]:checked + .button span:last-of-type {
  opacity: 1;
}

input[type="checkbox"] + .button + div {
  display: none;
}
input[type="checkbox"]:checked + .button + div {
  display: block;
}
<input type="checkbox" id="btn">

 conteúdo aqui que oculta ao selecionar OFF


For all real numbers $x$, we have $x \leq -5$ if and only if $1 \leq \frac{2x+3}{x-2} \leq 2$.

Question: I am trying to prove the Theorem in the title. I need help verifying my solution.

For all real numbers $x$, we have $x \leq -5$ if and only if $1 \leq \frac{2x+3}{x-2} \leq 2$.
Proof. To prove the implication, by adding $x+3$ to both sides of $x\leq -5$, one obtains
\begin{align}
2x+3 \leq x-2
\end{align}
Since $x \leq -5$, one can divide both sides of the inequality and obtains,
\begin{align}
\frac{2x+3 }{x-2} \geq 1
\end{align}
By taking the limit of $\frac{2x+3}{x-2}$ as $x$ approaches $-\infty$,
\begin{align}
\lim_{x\to-\infty} \frac{2x+3}{x-2} = \lim_{x\to-\infty} \frac{2+\frac{3}{x}}{1-\frac{2}{x}} = 2
\end{align}
Hence, $1 \leq \frac{2x+3}{x-2} \leq 2$.
To prove the converse, observe that if $x-2 \geq 0$, by multiplying both sides of $1 \leq \frac{2x+3}{x-2} \leq 2$ by $x-2$, one obtains
\begin{align}
x-2 \leq 2x+3 \leq 2x -4\\
-2 \leq x+3 \leq x-4\\
-5 \leq x \leq x-7
\end{align}
Since no non-negative $x$ satisfies the above inequalities, $x-2$ can not be greater than or equal to $0$.
In case that $x-2 < 0$ by multiplying both sides by $x-2$, one obtains
\begin{align}
x-2 \geq 2x+3 \geq 2x -4\\
-2 \geq x+3 \geq x-4\\
-5 \geq x \geq x-7
\end{align}
Because all $x \in (-\infty , -5]$ satisfy the above inequalities, $x-2 < 0$ and $x \leq -5$.
Since the implication and its converse are both true, $x\leq -5$ if and only if $1 \leq \frac{2x+3}{x-2} \leq 2$.
Comment: For the argument to work, you would first need to prove that $\frac{2x+3}{x-2}$ is a decreasing function (for $x<2$). Maybe you know that, in which case you proof is fine. By the way, for the converse direction, when you argue that $-5\leq x\leq x-7$ doesn't hold, it suffices to consider the right inequality; it gives that $0\leq -7$, a contradiction.
Comment: The statement should require $x\neq2$.
Comment: @MaximilianJanisch For most people, this is implicit: If $x\leq -5$, it is clear, and in order to write down $\frac{2x+3}{x-2}$, you silently assume $x\neq 2$.
Comment: For a more direct approach, multiply by the square of the denominator (to ensure positivity), then factorize accordingly.
Comment: Your limit argument for the direct implication does not work.
Comment: @Zuy Is it because the limit of the function is not equal to 2 or the limit can not be used in this proof?
Answer: learn to draw simple graphs by hand, say by plotting a few points (either $x$ or $y$ integers, for example).  In any case the graph of a non-constant, non-linear Mobius transformation is a hyperbola  with a horizontal asymptote and a vertical asymptote.
Furthermore, it is easy to invert a Mobius transformation, and this particular one is an agreeable surprise: if  $y = \frac{2x+3}{x-2}, $ then $$x = \frac{2y+3}{y-2}.$$
Answer: We have $1 \leq \frac{2x+3}{x-2} \leq 2$, which is a rational inequality in two parts. First, consider the first part: we have
$$ 1\leq \frac{2x+3}{x-2}\\
\frac{2x+3}{x-2}-1 = \frac{2x+3-x+2}{x-2} = \frac {x+5}{x-2} \geq 0\text{.} $$
For this fraction to be non-negative, its numerator and denominator must share the same sign, or the numerator has to be zero. We thus have
$$(x+5\geq 0\land x-2 > 0)\implies x > 2\bigvee (x+5\leq 0\land x-2 < 0)\implies x\leq -5\text{,}$$ giving us the partial set of solutions $$A = (-\infty ;-5]\cup (2;\infty )\text{.}$$
For the second part of the inequality:
$$ \frac{2x+3}{x-2} \leq 2\\
\frac{2x+3}{x-2} - 2 = \frac{2x+3-2x+4}{x-2} = \frac{7}{x-2} \leq 0\\
\frac{1}{x-2} \leq 0\text{,} $$
clearly giving $$ B = (-\infty ;2)\text{.} $$
Combining the two intervals yields $$ x\in A\cap B = (-\infty ;-5)\iff x\leq -5\text{.} $$
Answer: We have $x\le-5\iff x=-5-h$ where $h\ge0$ so we have
$$\frac{2x+3}{x-2}=\frac{-2h-7}{-7-h}=\frac{2h+7}{7+h}=1+\frac{h}{7+h}$$ We are done because it is evident that $1\le1+\dfrac{h}{7+h}\le2$.


How do I include static html in release bundle for ReactNative Android?

Question: I've got a WebView that uses a local file require to display web content.
  <WebView
    source={ require('./inline_web_view/inline_web_view.html') }
    injectedJavaScript={ scripts }
    scrollEnabled={ this.props.scrollEnabled || false }
    scalesPageToFit={ false }
    style={{
      width: this.state.width,
      height: this.state.height,
    }}
    onNavigationStateChange={ (navState)=> this.onNavigationStateChange(navState) }
  />

This works perfectly on ios and Android in dev mode, however, it seems as though the HTML file is not being included in the android release bundle.
How can I add it to the bundle?
Answer: This is a known issue in React Native.
The quick workaround is to load the content in a different way in iOS and Android. iOS will work as you described, but for Android release, you need to copy the static files into your native app assets folder (i.e. android/app/src/main/assets) and load the content with an { uri: 'file:///android_asset/-your-path-' } source.
See this post for full details and a complete example.
Comment: { uri: 'file:///android_asset/-your-path-' } //without S on android_asset


Fileuploading not work in PHP while I select file which contains = in it's name

Question: When i upload any image file which contains '=' in filename then server says that 404 page not found. and if i upload any other file which is not contain '=' in name then it will successfully uploaded. is there any server access issue. should i make change in .htaccess file? because i have host this code in two different host provider. godaddy and namecheap. godaddy allows us to upload any image with any name i.e it uploads image which containt '=' but same code not work on namecheap.
I am sure that code doesn't have any issue.
I am using below code

<form id="uploadForm" action="upload.php" method="post"  enctype="multipart/form-data">

No Image

  Upload Image File:

  <input name="userImage" type="file" class="inputFile" />
  <input type="submit" value="Submit" class="btnSubmit" />
</form>

Answer: Actually I have tried lot's off things but it was not code issues. it was server side issues. there were some mod_security rule which result in blocks for your image up-loader. Now, They(Namecheap) have whitelisted the rule related to the issue, and now everything work properly


How to recover raid? mount: can't read superblock

Question: I had a raid5 array on /dev/md0 created with mdadm and it was working fine for about a year. It consisted of three HDDs of 1TB each. A few days ago there was a power failure and UPS failure. It was not the first time unfortunately.
The OS is on a separate SSD disk (/dev/sda) which is not part of the raid array, so it boots but it cannot mount the array anymore. Sometimes /dev/md0 does not exists at all. Also I did something that might have get the things worse. I ran fsck /dev/sdb -y which wrote many many times on the disk.
I am afraid that I wont recover my files. Can you help me solve this problem?
Thanks.
mount /dev/md0 /mnt/raid5
mount: /dev/md0: can't read superblock

syslog:
Feb 25 15:59:53 pve kernel: [  365.559378] EXT4-fs (md0): unable to read superblock
Feb 25 15:59:53 pve kernel: [  365.560118] EXT4-fs (md0): unable to read superblock
Feb 25 15:59:53 pve kernel: [  365.560216] EXT4-fs (md0): unable to read superblock
Feb 25 15:59:53 pve kernel: [  365.560310] FAT-fs (md0): unable to read boot sector

cat /proc/mdstat
Personalities : [raid6] [raid5] [raid4]
unused devices: <none>

fdisk -l
Disk /dev/sdb: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x75633c0d

Device     Boot Start        End    Sectors  Size Id Type
/dev/sdb1        2048 1950353407 1950351360  930G fd Linux raid autodetect

Disk /dev/sdc: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: F397C12B-1549-45EA-97EA-6A41B713B58F

Device     Start        End    Sectors  Size Type
/dev/sdc1   2048 1950353407 1950351360  930G Linux RAID

Disk /dev/sdd: 931.5 GiB, 1000203804160 bytes, 1953523055 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xcced27e3

Device     Boot Start        End    Sectors  Size Id Type
/dev/sdd1        2048 1950353407 1950351360  930G fd Linux raid autodetect

sometimes fdisk -l
-bash: /sbin/fdisk: Input/output error

syslog:
Feb 25 16:03:25 pve kernel: [  577.221547] ata1.00: SRST failed (errno=-16)
Feb 25 16:03:25 pve kernel: [  577.232569] ata1.00: reset failed, giving up
Feb 25 16:03:25 pve kernel: [  577.232640] ata1.00: disabled
Feb 25 16:03:25 pve kernel: [  577.232643] ata1.01: disabled
Feb 25 16:03:25 pve kernel: [  577.232658] ata1: EH complete
Feb 25 16:03:25 pve kernel: [  577.232683] sd 0:0:0:0: [sda] tag#0 FAILED Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK
Feb 25 16:03:25 pve kernel: [  577.232697] sd 0:0:0:0: [sda] tag#0 CDB: Write(10) 2a 00 05 13 a0 38 00 00 08 00
Feb 25 16:03:25 pve kernel: [  577.232702] blk_update_request: I/O error, dev sda, sector 85172280
Feb 25 16:03:25 pve kernel: [  577.232784] Buffer I/O error on dev dm-6, logical block 9255, lost sync page write
Feb 25 16:03:25 pve kernel: [  577.232928] sd 0:0:0:0: [sda] tag#0 FAILED Result: hostbyte=DID_BAD_TARGET driverbyte=DRIVER_OK
Feb 25 16:03:25 pve kernel: [  577.232936] sd 0:0:0:0: [sda] tag#0 CDB: Write(10) 2a 00 02 88 6a 10 00 00 68 00
Feb 25 16:03:25 pve kernel: [  577.232941] blk_update_request: I/O error, dev sda, sector 42494480
Feb 25 16:03:25 pve kernel: [  577.232948] EXT4-fs error (device dm-6): kmmpd:176: comm kmmpd-dm-6: Error writing to MMP block

EDIT 1:

sudo mdadm --examine /dev/sdb1
mdadm: No md superblock detected on /dev/sdb1.

sudo mdadm --examine /dev/sdc1
/dev/sdc1:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x1
     Array UUID : 34c11bda:11bbb8c9:c4cf5f56:7c38e1c3
           Name : pve:0
  Creation Time : Sun Jun  5 21:06:33 2016
     Raid Level : raid5
   Raid Devices : 3

 Avail Dev Size : 1950089216 (929.88 GiB 998.45 GB)
     Array Size : 1950089216 (1859.75 GiB 1996.89 GB)
    Data Offset : 262144 sectors
   Super Offset : 8 sectors
   Unused Space : before=262056 sectors, after=0 sectors
          State : active
    Device UUID : be76ecf7:b0f28a7d:718c3d58:3afae9f7

Internal Bitmap : 8 sectors from superblock
    Update Time : Mon Feb 20 14:48:51 2017
  Bad Block Log : 512 entries available at offset 72 sectors
       Checksum : ffbc1988 - correct
         Events : 2901112

         Layout : left-symmetric
     Chunk Size : 512K

   Device Role : Active device 1
   Array State : .AA ('A' == active, '.' == missing, 'R' == replacing)

sudo mdadm --examine /dev/sdd1
/dev/sdd1:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x9
     Array UUID : 34c11bda:11bbb8c9:c4cf5f56:7c38e1c3
           Name : pve:0
  Creation Time : Sun Jun  5 21:06:33 2016
     Raid Level : raid5
   Raid Devices : 3

 Avail Dev Size : 1950089216 (929.88 GiB 998.45 GB)
     Array Size : 1950089216 (1859.75 GiB 1996.89 GB)
    Data Offset : 262144 sectors
   Super Offset : 8 sectors
   Unused Space : before=262056 sectors, after=0 sectors
          State : active
    Device UUID : 7b9ed6e0:ffad7603:b226e752:355765a8

Internal Bitmap : 8 sectors from superblock
    Update Time : Mon Feb 20 14:48:51 2017
  Bad Block Log : 512 entries available at offset 72 sectors - bad blocks present.
       Checksum : 19b6f3da - correct
         Events : 2901112

         Layout : left-symmetric
     Chunk Size : 512K

   Device Role : Active device 2
   Array State : .AA ('A' == active, '.' == missing, 'R' == replacing)

Comment: Do you have backups ?
Comment: Unfortunately I made a series of mistakes. No I do not have backups.
Answer: Thanks to all I recovered the data.
I ran sudo mdadm --verbose --assemble --force /dev/md0 /dev/sdc1 /dev/sdd1 to assemble the array from the two remaining good HDDs and it worked!
Then I formated sdb and re-added it to the array with sudo mdadm --manage /dev/md0 --add /dev/sdb1 and I am going to buy a new one to replace it soon. Also I am looking on backup solutions..
Comment: More importantly fix your backup solution.
Comment: please explain what /dev/md0 /dev/sdc1 /dev/sdd1 are as far as that syntax goes? Which disk is which among those? Which goes first?
Comment: the syntax is `mdadm --assemble device options devices` where `device` is the logical (software) raid device and `devices` are the physical disk devices. So /dev/sdc1 /dev/sdd1 (the order does not matter) are the two real 1TB disks that are assembled into the one logical raid disk at /dev/md0.
Answer: If you gave input/output errors i think you have one or more bad disk. You need to check SMART attributes of all disks by command smartctl -a /dev/sdx. Check status and Update Time of each disk by command mdadm --examine /dev/sdx1. Choose one worst disk witch has more bad smart attributes and oldest Update Time and remove it from array.
If you have two bad disks you need to choose less bad disk and it must be recovered to new disk by program ddrecovery. Remove this bad disk and insert the new recovered disk to the same place.
Then you will can restore RAID 5 array with one missed disk (by example sdc) by command:
mdadm --verbose --create /dev/md0 --chunk=512 --level=5 --raid-devices=3 /dev/sdb1 missing /dev/sdd1

Be sure that chunk parameter is the same as on good disks.
Also you have bad sda disk, which isn't a member of RAID 5 array.
Be carefully with each command. There's only way to restore your RAID array.
Read this by example.
Comment: I ran:
`sudo mdadm --verbose --assemble --force /dev/md0 /dev/sdc1 /dev/sdd1`
and it worked!
I then formated the /dev/sdb and readded to the array with `sudo mdadm --manage /dev/md0 --add /dev/sdb1` because I dont have a new one to replace it. I will buy a new one soon.
I can mark your Answer if it is possible for you to add the --assemble as an option. Thanks.
Comment: hello, I have edited my question to include mdadm --examine results. Is it safe to --create? Shouldn't be better to --assemble? Thanks.
Comment: Also SMART shows sdb to have many errors. sdc and sdd seems ok.
Comment: You must be sure that RAID disks are good by SMART attributes.
Answer: Running fsck was the right idea, but I think you ran it on the wrong device. Try running fsck on /dev/md0 using a backup superblock. This link will give you some tips on how to find the backup and repair when you do. In particular, running dumpe2fs is your best bet for finding the filesystem block size. Even if the first backup is corrupted, ext4 will have created others.
Comment: Oops...meant to make this a comment, since there's no certainty it will work given the fsck run on the underlying disk. But with the error mounting the RAID, this is a good thing to try.
Answer: You have several problems.
First, you say that /dev/sda is your system disk, not part of a RAID array, with the OS on it. Well, look in the exact syslog snippet you showed us:
Feb 25 16:03:25 pve kernel: [  577.232702] blk_update_request: I/O error, dev sda, sector 85172280
Feb 25 16:03:25 pve kernel: [  577.232941] blk_update_request: I/O error, dev sda, sector 42494480

Two I/O errors during writes, reported within a millisecond of each other, to two different locations, on the system disk. Your system disk is having serious problems; get it replaced immediately. Might be well worth it replacing the cabling to it too, while you are at it. In my experience, I/O errors are usually indicative of either cabling or disk problems (though the HBA can be at fault). Expect data on the system disk to be corrupted to at least some degree as a result of this problem.
Second, fsck /dev/sdb -y very likely scribbled all over your RAID data in attempting to make sense of partial file system data and automatically writing out whatever it thought looked right. I would suggest physically disconnecting that disk, remove it from the system, and place it some place safe for now. Treat it as dead.
Thankfully, you are lucky; the system is still talking to all three disks, and the metadata looks sane on the two disks out of the three that still hold md metadata.
Grab three new disks, and use ddrescue to copy everything that you can from the two remaining disks onto two new ones. Unplug the old disks and set them together with what used to be /dev/sdb (make sure you keep track of which disk is which), and plug in the two new disks along with the third new, blank, one.
Feed the resulting array to mdadm and pray to your deity of choice that md will be able to make sense of the resulting situation. If you are lucky, it will be able to, and will restore most of the data to readable condition now that there are no read errors (since you brought in new disks). Again, there may be some corruption in places.
Third, figure out what caused the UPS failure and correct that, and set up regular backups so that if the worst happens, at least you will have a backup that you can restore onto new media. Consider this incident a learning experience illustrating why RAID is not a backup.
Comment: Thank you! I saw that sda also gives errors.. I will replace everything eventually. The raid is working now!


Como guardar as variáveis para serem usadas nos próximos .Java?

Question: Meu código principal (do parser) está desta maneira:
public class pFormasDePagamento {

public static void parseXML(String xml)
        throws ParserConfigurationException, SAXException, IOException {
    InputSource is = new InputSource(new StringReader(xml));
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(is);
    doc.getDocumentElement().normalize();
    String valFormaOutros = doc.getElementsByTagName("VALOR").item(0)
            .getTextContent();
    String descForma = doc.getElementsByTagName("DESCRICAO").item(0)
            .getTextContent();
    String valForma = doc.getElementsByTagName("VALOR").item(1)
            .getTextContent();
    String descForma1 = doc.getElementsByTagName("DESCRICAO").item(1)
            .getTextContent();
    String valForma1 = doc.getElementsByTagName("VALOR").item(2)
            .getTextContent();
    String descForma2 = doc.getElementsByTagName("DESCRICAO").item(2)
            .getTextContent();
    String valForma2 = doc.getElementsByTagName("VALOR").item(3)
            .getTextContent();
    String descForma3 = doc.getElementsByTagName("DESCRICAO").item(3)
            .getTextContent();
    String valForma3 = doc.getElementsByTagName("VALOR").item(4)
            .getTextContent();
    String descForma4 = doc.getElementsByTagName("DESCRICAO").item(4)
            .getTextContent();
    String valForma4 = doc.getElementsByTagName("VALOR").item(5)
            .getTextContent();
    String descForma5 = doc.getElementsByTagName("DESCRICAO").item(5)
            .getTextContent();
    String valForma5 = doc.getElementsByTagName("VALOR").item(6)
            .getTextContent();
}}

Gostaria de guardar todas essas strings (valForma1...5) para serem reutilizadas em outros .Java
Como eu posso resolver isto?
Answer: Crie uma classe que contenha essas propriedades e retorne uma instancias(em um array, por exemplo) dessa classe.
Tipo assim:
public class FormaDePagamento {
    public String desc;
    public String valor;
}

public class pFormasDePagamento {

    public static FormaDePagamento[] parseXML(String xml)
            throws ParserConfigurationException, SAXException, IOException {
        InputSource is = new InputSource(new StringReader(xml));
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(is);
        doc.getDocumentElement().normalize();

        FormaDePagamento[] formas = new FormaDePagamento[5];
        for(int n = 0; n < 5; n++) {
            formas[n] = new FormaDePagamento();
            formas[n].desc = doc.getElementsByTagName("DESCRICAO").item(n).getTextContent();
            formas[n].valor = doc.getElementsByTagName("VALOR").item(n).getTextContent();
        }

        return formas;
    }
}

/* em:  "formas[n].val = doc.getElementsByTagName" não seria: "formas[n].valor = doc.getElementsByTagName"  ?
*/
Comment: como eu iria fazer a chamada então Rafael?
Comment: como eu posso chamar as variáveis separadas @RafaelTelles?
Comment: Poderia ser algo como "FormaDePagamento[] formas = pFormasDePagamento.parseXML(xml)", e nessa array você teria todos os objetos do xml.
Answer: Renan, você pode usar o banco de dados nativo do Android Sqlite ou SharedPreferences.
No caso do SharedPreferences é bem simples, e pode ser utilizado na sua Activity dessa maneira:
public static final String KEY = "nome_chave";
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
/*Para armazenar um valor*/
sharedPreferences.edit().putString(KEY , "valor").commit();
/*Para ler um valor armazenado*/
sharedPreferences.getString(KEY , "valor padrão caso não tenha valor para a chave");


Can't get div to appear when hovering over another div

Question: I apologize for posting a question that should be answered by the other threads, but after the last hour of trying solutions already provided with no success I have to assume my coding in another location is incorrect. If you would like skip to looking at the project , I need the #info_area to appear when mousing over the other divs, such as #final_sale. link to project
the css looks like this
#final_sale {
   width: 474px;
   position: absolute;
   top: 691px;
   left: 5px;
   transition: width 1s, height 1s;
   -webkit-transition: width 1s, height 1s, -webkit-transform 1s;
}
#final_sale:hover {
   width: 575px;
   position:absolute;
   top:691px;
   left:5px;
}

The code for all the hover divs looks like this they just have other names than "final_sale".  All of these divs also have a class of "show_info" (.show_info), which you can see in the html below.
Now going off of other posts answered I have the info area like this:
#info_area {
   background-color: #666;
   display: block;
   opacity:0;
   height: 175px;
   width: 325px;
   position: absolute;
   top: 365px;
   left: 397px;
   border: 1px solid;
   box-shadow: 1px 3px 12px;
   transition: opacity .25s ease-in-out;
   -webkit-transition: opacity .25s ease-in-out;
   -moz-transition: opacity .25s ease-in-out;
}
.show_info:hover #info_area {
   background-color: #666;
   display: block;
   opacity:0.5;
   height: 175px;
   width: 325px;
   position: absolute;
   top: 365px;
   left: 397px;
   border: 1px solid;
   box-shadow: 1px 3px 12px;
}

I have also tried ".show_info:hover + #info_area"
Here is the HTML, my best guess now is maybe because "info_area" is not nested within one of the other divs, but I have tried that as well and also tried including the main containing div in the CSS.
html

           info here

I uploaded the project HERE, might take a second to load since I have not completely made it web ready due to it not being finished or placed where it will eventually go.
Thank you in advance to anyone who can help, its been driving me crazy all evening and im hoping its something simple I have missed.
Comment: I haven't read your question, but isolate the issue.
Comment: .show_info:hover + #info_area or  .show_info:hover ~ #info_area will not work, unless #info_area stands last/after any .show_info blocks. change your structure, or use javascript. :p)
Answer: If you can make #info_area the last sibling, then you could achieve this with the general sibling combinator:
.show_info:hover ~ #info_area{
  ...
}

Comment: Thank you One Trick Pony! that did the trick. I will accept this answer as soon as it lets me.


terminating connection because of crash of another server process

Question: I have a java scraper that spawns around 1,500-2,100 threads, each of which connects to the same database via jdbc and makes inserts. These threads insert quite frequently.
It seems like the db crashes when there are too many connections. I always get to spawning 210 threads or connections when all threads lose connection. The following is the log msgs that get generated on the server side.
2015-07-15 20:18:37 UTC [10825-21] LOG:  checkpointer process (PID 13435) was terminated by signal 9: Killed
2015-07-15 20:18:37 UTC [10825-22] LOG:  terminating any other active server processes
2015-07-15 20:18:37 UTC [16836-1] user@db WARNING:  terminating connection because of crash of another server process
2015-07-15 20:18:37 UTC [16836-2] user@db DETAIL:  The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.
2015-07-15 20:18:37 UTC [16836-3] user@db HINT:  In a moment you should be able to reconnect to the database and repeat your command.

The following is the error msg displayed on the client(scraper) side.
SEVERE: An I/O error occurred while sending to the backend.
org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:283)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:570)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:420)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:366)
    at SocketBot.run(SocketBot.java:167)
Caused by: java.io.EOFException
    at org.postgresql.core.PGStream.ReceiveChar(PGStream.java:284)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1803)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
    ... 4 more

In the postgresql.conf file, I set max connections = 2500. But I'm thinking there are more things to adjust here. My server has 512MB RAM if anyone would like to know.
Comment: seems Linux out-of-memory (OOM) killer killed the process
Comment: Maybe, I don't know, take a look http://serverfault.com/questions/384686/can-you-help-me-with-my-capacity-planning
Comment: Is 512MB RAM not enough for what I hope to do? Or is there a setting I need to adjust?
Comment: Thanks for pointing me in the right direction. I found out each connection to db is consuming about 3% of memory and this is definitely not how I should handle things. I'll work on reducing the number of concurrent connections by streaming all inserts commands to something like 20 threads and see how it goes from there.
Answer: Linux's out-of-memory killer is probably terminating processes. This means your server is misconfigured. It's strongly advised that you not let Linux overcommit memory, so it responds with a proper out-of-memory error to the application instead of killing processes almost at random. PostgreSQL is designed to handle out-of-memory conditions, but cannot do so if Linux kills processes instead of reporting out-of-memory.
To confirm that's what is happening here, check the kernel message log with the dmesg command.
See http://www.postgresql.org/docs/current/static/kernel-resources.html#LINUX-MEMORY-OVERCOMMIT


Why does adding a mean datapoint decrease the Pearson correlation coefficient $R$?

Question: We know that for a sample (assume it's a data set that has two variables $x$ and $y$ of size $n$),
$$R = \frac1{n-1}\sum_{i=1}^n\left(\frac{x_i-\overline{x}}{s_x}\right)\left(\frac{y_i-\overline{y}}{s_y}\right)$$
Say we add in a data point $(\overline{x}, \overline{y})$ to the sample, which lies on the linear regression trendline of the sample (?).
We can mathematically see this actually decreases the $R$ value (the sum portion for this data point is $0$, but $n$ increases by $1$ so the denominator increases). However,  cannot intuitively understand why.
Is there an intuitive explanation for this?
Thanks!
Comment: I don't "mathematically see" this at all, because including that point *shrinks* both $s_x$ and $s_y,$ which could more than compensate for the change in $n.$  In fact, this *exactly* compensates for the change.  (I understand you really mean to ask about $|R|$ rather than $R$ itself, for otherwise the claim--if it were true for positive $R$--could easily be disproven by choosing very negative $R.$)
Comment: My answer [here](https://stats.stackexchange.com/a/612056/247274) might be helpful, even if this is not quite a duplicate. (My hope is that you will be able to read that answer and then figure out enough to be able to post a self-answer!)
Answer: $R$ is the ordinary least squares (OLS) estimate of the slope of the regression of the $y_i$ on the $x_i.$  Because the regression line must go through the point of averages $(\bar x, \bar y),$ adjoining any number of instances of that point to the dataset will not change the sum of squares and therefore will not change the OLS solution, whence $R$ will be unchanged.


Masquerade as User in Enterprise Windows Environment

Question: In a large Enterprise Windows Environment. What do IT people do to login as a user if needed? It seems impossible to me to keep user passwords in a large environment. In a Mac environment, you have the option to masquerade as a user and login using the admin credentials.
What do large Windows Environments do when it's necessary to login as the user?
Answer: This feature is not included in Windows server to my knowledge.  It would be a security issue.  What are you trying to do that would require acting as the user, perhaps we could assist with that?
Comment: In a large environment you'd script it, there's not much that can't somehow be scripted or customized at the profile level
Comment: Basically I need to log-in as a user once when setting up their profile in a new TS/XenApp farm. There are a few config items I need to do, which I can't rely on the user to do and I can't script out the config.
Comment: 1. Ask the user for their password, explaining to them why you need it. 2. Log in as the user and make the neccessary changes, then logout. 3. Force user to change their password on the next logon. 4. Done.
Comment: This is basically what I do. I'm just curious what a large Enterprise environment would do in this case if something different.
Comment: it's the 'not much' that needs this question answered.
Answer: You can do this with Group Policy. This is what you will need to do
<code>1. Setup a Startup Script

1a. In your script, you will create a new directory on the local drive or create a registry entry (with reg add)
1b. On startup, you will check to see if this directory/registry entry exists on the local PC. If it does, you skip it.

2. Your script would have to copy the necessary files (robocopy, or you can use PowerShell or VBScript) to copy the files to the necessary location.
</code>

I read that you can't script out the config. You should be able to manage this with Group Policy. Enterprise apps like XenApp have GPO's that are designed to allow you to do this specific task. You can then apply the policy to a group of users or specific users. However if you do not have access to Group Policy then you can get creative by doing the following
On a good known working machine (preferably one that has recently been imaged and all updates applied) and then use software to capture the before and after state and export the results as a registry entry. There are several tools to assist you with this but I won't recommend one over the other.

Asking the user for their password should never be done once the person has started working. If the person is about to start, you can assign the password and take all the necessary steps then use AD to force the user to change the password upon login.


why are users logged out after 2 days of not logging in

Question: We got LDAP SSO working for our site. Employees go to the site everyday and everyday they do not have to input their credentials... until Monday. I believe this has to do with cookies maybe? I think if the employees have not logged in in a couple of days (weekend) then they have to log back in. Every Monday they have a http authentication dialogue box (LDAP Authentication from the /user/login/sso url). It saves their credentials (if they hit remember my password), but they don't like hitting the enter key.
My /admin/config/people/ldap/authentication settings look like this:

I then found this post: Why is session.cookie_lifetime set to 23 days?, where they say that in drupal it might have a session.gc_maxlifetimesetting in settings.php that is set to 23 days, but that the session.cookie_lifetime is set to 2.3 days. And that if the user doesn't visit the page withing 2.3 days then they start a new session or something. Does this mean if I adjust the ini_set('session.cookie_lifetime', 200000); to like 4 days that the employees wont need to hit enter anymore?
Comment: What is your cookie lifetime on admin/settings/ldap/sso?
Comment: Under /admin/config/people/ldap/authentication cookie lifetime is set to 10yrs. But the url you gave me doesn't seem to be a valid one.
Comment: It was from the ldap sso module description page. But I suppose that's not it then...
Answer: The answer here explains the difference between the cookie types and when they destroy the session: Why is session.cookie_lifetime set to 23 days?
To answer your question specifically:
If you extend the session.cookie_lifetime to be longer, the session will last longer and users will less frequently require to login. If the user opens the page within session.cookie_lifetime from the last visit, the session will be extended for another session.cookie_lifetime. This can be repeated several times, but never longer then session.gc_maxlifetime after which a user is always forced to log in again.
If you extend the session.cookie_lifetime to last for eg. 4 days (so it survives the weekend), users that always open the page on workdays will have to login once every 23 days (session.gc_maxlifetime). You can also extend this value to last as long as you want.
Please keep in mind that although hitting the enter might be annoying, if security is part of your job as well, it might not be a good idea to have sessions lasting for long periods of time. Have them survive the weekend by having them last a day longer will not cause much problems, but allowing them to extend for ever and ever (session.gc_maxlifetime) could introduce security vulnerabilities.
Comment: Good to know! I had a feeling this was going to be the case. But your answer gives me the confidence in saying it is a done. I implemented it this morning. So I won't empirically know if it worked till 2.3 days away. I Made a 14 day `session.cookie_lifetime` and a 90 day `session.gc_maxlifetime.` In our environment users have to change AD passwords every 90 days, so I used AD duration credentials as the demarcation for the `session.gc_maxlifetime` value. Our site is an intranet behind the firewall so vulnerabilities isn't a huge concern.
Comment: Good to know it was of value to you! :)