Reconnecting secondary DRBD node

Question: I have set up test DRBD installation succesfully, with switching, synchronization etc working correctly.
But I also wanted to test the reliatbility of the setup, so I gave it a good "trashing" like disconnecting network interfaces midflight, etc. In the course of such testing I have "managed" to get secondary to Diskless state:
root@h2 ~ % drbd-overview
 0:r0/0  Connected Secondary/Primary Diskless/UpToDate

Now I cannot connect the resource back:
root@h2 ~ % drbdadm  --discard-my-data connect r0
r0: Failure: (102) Local address(port) already in use.
Command 'drbdsetup-84 connect r0 ipv4:10.0.1.90:7788 ipv4:10.0.0.90:7788 --protocol=C --max-buffers=36k --sndbuf-size=1024k --rcvbuf-size=2048k --discard-my-data' terminated with exit code 10

Even rebooting secondary does not help (I still get the message r0: Failure: (102) Local address(port) already in use.
Primary:
root@h1 ~ % drbd-overview
 0:r0/0  Connected Primary/Secondary UpToDate/Diskless

Configuration:
root@h1 ~ % cat /etc/drbd.d/r0.res
resource r0 {
        protocol C;
        startup {
                wfc-timeout  15;
                degr-wfc-timeout 60;
        }
        disk {
                on-io-error     detach;
                c-fill-target   10M;
                c-max-rate      700M;
                c-plan-ahead    7;
                c-min-rate      4M;
        }
        net {
                # max-epoch-size  20000;
                max-buffers       36k;
                sndbuf-size       1024k;
                rcvbuf-size       2048k;
        }
        syncer {
                rate                    400M;
                al-extents              6433;
        }
        on h1 {
                device /dev/drbd0;
                disk /dev/sdc1;
                address 10.0.0.90:7788;
                meta-disk internal;
        }
        on h2 {
                device /dev/drbd0;
                disk /dev/vg/drbdtest2;
                address 10.0.1.90:7788;
                meta-disk internal;
        }
}

OS:
% lsb_release -a
Description:    Debian GNU/Linux 9.6 (stretch)
Release:    9.6
Codename:   stretch

% dpkg -l | grep drbd
ii  drbd-utils                                    8.9.10-2                                   amd64        RAID 1 over TCP/IP for Linux (user utilities)

Answer: DRBD is already Connected, but it's in a Diskless disk state. This means that there is either something wrong with the backing disk causing it to throw IO errors, or something else is preventing DRBD from accessing that disk.
/var/log/syslog should be full of messages surrounding the issue, but you can also try a, drbdadm attach r0 from the node that's Diskless to see what it tells you.

Reconnecting secondary DRBD node


how to display a custom entity in a view

Question: This is my first time making a custom module and I want to display some of the content that is produced in a view, but I can't figure out how to make my custom entity show up in the SHOW: select list when making a new view.
What code do I need to add to my custom module to have it show up there?
Comment: https://www.drupal.org/node/1208874
Comment: I'm pretty sure it was in views  documentation. Can't start looking now, to late night for me.
Comment: @Andrew I did my best to do what it said(as far as I understood), but my custom entity didn't show up in the list
Answer: Include this in your hook_entity_info
<code>MyModule_entity_info() {
...
'views controller class' => 'EntityDefaultViewsController',
...
}
</code>
For more details check this link : http://www.sitepoint.com/build-custom-drupal-entities/
Comment: Ok, thanks!
In the MyModule_entity_info() it has a base table field, do you know how to set up an entity that is built with two tables? (for example, a person who can select multiple values in a select list, so the person is stored in one table, and the selected values are stored by user_id in another table)
Answer: You can use this and this articles or download Model Entities module and look how new entity is implemented in this module.
Comment: A question on that,
In MyModule_entity_info() it has a base table field, but I can't figure out how to set up an entity with more than one table.
Do you know how to set up an entity that is built with two tables? (for example, a person who can select multiple values in a select list, so the person is stored in one table, and the selected values are stored by user_id in another table)


How do I show these two functions are integrable?

Question: Let $f:[a,b]\to \mathbb R $ be an integrable function. Define $$f_+(x)=\begin{cases}f(x)&\text{if } f(x)\geq0,\\0&\text{if }f(x)<0, \end{cases} \text{  and  } f_-(x)=\begin{cases}0 & \text{if }f(x)\geq0,\\-f(x) &\text{if }f(x)<0. \end{cases}$$
Prove that $f_+,f_-:[a,b]\to\mathbb{R}$ are integrable and $$\int_a^bf(x)dx=\int_a^bf_+(x)dx -\int_a^bf_-(x)dx.$$
I see that $f(x)=f_+(x)-f_-(x)$, so the last part seems fairly obvious. I'm not how to show the functions are integrable, though. I feel like I must be missing something obvious, but their upper and lower sums don't seem to relate nicely to $f(x)$.
Comment: See http://math.stackexchange.com/q/306326/27978. The function $x \mapsto \max(0,x)$ is continuous.
Comment: @rtybase Actually I am pretty sure that for Lebesgue we can have an *uncountable* set of discontinuities so long as its lebesgue measure is 0.
Comment: Riemann or Lebesgue integrable?
Comment: I guess it doesn't matter, it it's Riemann, http://math.stackexchange.com/questions/102844/how-do-i-prove-that-a-function-with-a-finite-number-of-discontinuities-is-rieman, then both $f_{+}$ and $f_{-}$ have a finite number of discontinuities (extra possible one at $x=0$). For  Lebesgue - both $f_{+}$ and $f_{-}$ have a countable set of discontinuities (extra possible one at $x=0$).
Comment: Riemann integrable.
Comment: @Ainlaen It will be a lot easier to prove that they are Lebesgue integrable and from that point we can deduce that they are also riemann integrable.
Comment: @christina_g: Yes, take $1_\mathbb{Q}$.
Comment: @christina_g, yes, you are right!
Answer: Thanks to copper.hat's remark it finally made -clonk- and here it is:
$$
\DeclareMathOperator{abs}{abs}
f_+(x) = \max(f(x),0) = \frac{\abs(f(x))+f(x)}{2} \\
f_-(x) = -\min(f(x), 0) = \frac{\abs(f(x))-f(x)}{2}
$$
We need the theorem that if $f$ is Riemann integrable on $[a,b]$, then so is $\abs(f)$ (Link).
Together with linearity, this gives integrability of $f_+$ and $f_-$ on $[a,b]$.
Subtraction of the two equations above gives $f_+(x) - f_-(x) = f(x)$, together with the integrability and linearity it should yield the decomposition
$$
\int\limits_a^b f(x) \, dx
= \int\limits_a^b f_+(x) \, dx - \int\limits_a^b f_-(x) \, dx
$$


Ordering by two columns sorted by priority

Question: I have to show the result of the query below sorted by the priority.
mysql> select CouponId, CouponCode, DateAdded, Priority from Coupon where IsFeatured=1 and IsApproved=1 order by DateAdded desc limit 12;
+----------+--------------+---------------------+----------+
| CouponId | CouponCode   | DateAdded           | Priority |
+----------+--------------+---------------------+----------+
|    42699 | cc2          | 2013-09-12 14:54:39 |     NULL |
|    42698 | c1           | 2013-09-12 14:53:36 |     NULL |
|    42697 | cc2          | 2013-09-12 14:51:57 |     NULL |
|    42679 | GLMR20       | 2013-05-14 13:21:07 |        5 |
|    42678 | HKBAJAJ20    | 2013-05-14 12:35:31 |        1 |
|    42677 | SIPPER51     | 2013-05-14 12:11:36 |     NULL |
|    42654 | GL13MAYCHILL | 2013-05-14 07:09:08 |        7 |
|    41978 | POLARSPL     | 2013-05-03 13:31:32 |     NULL |
|    41958 | COMBO30      | 2013-05-03 12:16:53 |     NULL |
|    41357 | BRANDED60    | 2013-04-25 13:49:56 |     NULL |
|    41073 | PKCCR500     | 2013-04-22 11:10:27 |     NULL |
|    40794 | SWC15        | 2013-04-18 13:57:54 |     NULL |
+----------+--------------+---------------------+----------+
12 rows in set (0.00 sec)

I though another order by Priority desc would do it but it produces the same result
mysql> select CouponId, CouponCode, DateAdded, Priority from Coupon where IsFeatured=1 and IsApproved=1 order by DateAdded desc, Priority desc limit 12;
+----------+--------------+---------------------+----------+
| CouponId | CouponCode   | DateAdded           | Priority |
+----------+--------------+---------------------+----------+
|    42699 | cc2          | 2013-09-12 14:54:39 |     NULL |
|    42698 | c1           | 2013-09-12 14:53:36 |     NULL |
|    42697 | cc2          | 2013-09-12 14:51:57 |     NULL |
|    42679 | GLMR20       | 2013-05-14 13:21:07 |        5 |
|    42678 | HKBAJAJ20    | 2013-05-14 12:35:31 |        1 |
|    42677 | SIPPER51     | 2013-05-14 12:11:36 |     NULL |
|    42654 | GL13MAYCHILL | 2013-05-14 07:09:08 |        7 |
|    41978 | POLARSPL     | 2013-05-03 13:31:32 |     NULL |
|    41958 | COMBO30      | 2013-05-03 12:16:53 |     NULL |
|    41357 | BRANDED60    | 2013-04-25 13:49:56 |     NULL |
|    41073 | PKCCR500     | 2013-04-22 11:10:27 |     NULL |
|    40794 | SWC15        | 2013-04-18 13:57:54 |     NULL |
+----------+--------------+---------------------+----------+
12 rows in set (0.00 sec)

mysql>

How can I order the result of this query by Priority, so that the row with Priority 7 appears at top irrespective of its DateAdded?
I need the sort by DateAdded in the query to just pick the top 12 rows with regard to time and then sort them according to the priority.
Answer: select CouponId, CouponCode, DateAdded, Priority
from
(
   select CouponId, CouponCode, DateAdded, Priority
   from Coupon
   where IsFeatured=1
   and IsApproved=1
   order by DateAdded desc
   limit 12
) x
order by Priority desc

Comment: You need to name subqueries with an alias. I used `x`.
Answer: Use this query to order by non nulls first (after Date Added):
SELECT CouponId, CouponCode, DateAdded, Priority
FROM Coupon WHERE (IsFeatured = 1) and (IsApproved = 1)
ORDER BY   DateAdded desc, Priority IS Null, Priority desc limit 12;


How is the global truncation error and stability criterion of the forward Euler method consistent with each other?

Question: The forward Euler method can be used to solve ODE's with some initial value by using the update rule
$$y_{k+1} = y_k + hf(t_k, y_k),$$
where $0\leq k \leq n-1$ and $h$ is the step size $\dfrac{t_n-t_0}{n}$. Reading from wikipedia, the global truncation error (the difference between the true value and approximate value at last time step) is said to be bounded by a value proportional to the step size $h$, provided the solution $y$ has a bounded second derivative and $f$ is Lipschitz continuous in its second argument. In particular, there does not seem to be any requirement on the step size $h$ for this to hold.
At the same time, it is said that the forward Euler method needs a sufficiently small step size $h$ in order to be numerically stable, i.e. for $h$ that is too large the numerical solution grows without bound while the exact solution decays to zero.
What confuses me is that I think this implies that the global truncation error is unbounded for some $h$ (since the numerical solution can grow without bound while the exact solution decays to zero), while at the same time the validity of the bound on the global truncation error seems to be independent of the value of $h$. This seems contradictory, what am I getting wrong here?
Answer: Yes, your objection is valid. In the error order computation one has to assume that $h$ is small enough. More precisely, one needs that the region where the Lipschitz constant and bound on the second derivative are taken contains the exact solution and the numerical solution for the range of $h\in[0,\bar h]$ under consideration.
If $\bar h$ increases, the numerical solution will have wilder deviations from the exact solution, as you said, and thus the region for the constants has to become larger. This again will increase the constants. As long as no division-by-zero is encountered, the error bound for the large step size $h=\bar h$ will again be correct, but it can become be horribly pessimistic for the smaller step sizes.

For the statements in the second half in the post, note that the claims in the first half and the considerations above are for a fixed integration interval of finite length. For large step sizes the error will lose its almost linear behavior and show growth that is polynomial in $h$. It will be rare to get actual divergence in this situation.
The divergence due to missing stability occurs for an unbounded integration interval. This divergence will be exponential or in the growth behavior of a geometric series. Mathematically this is slow, controlled. Numerically such a divergence can rapidly exhaust the range of the number type.


drupal_add_js and inline code

Question: I am trying to use inline javascript, added with hook_alpha_preprocess_page, to add support to IE.
drupal_add_js('
jQuery(document).ready(function () {
    if (jQuery.browser.msie && jQuery.browser.version < 10) {
            $("li#megamenu-mlid-774 .megamenu-items, li#megamenu-mlid-842 .megamenu-items").columnize({
                width: 420,
                columns: 3
            });
        }
  });', 'inline');

While this loads on the page, nothing is happening. Is this because my selector starts with $? What should I change it to for this to work?
Answer: First of all you need to replace $ with jQuery and secondly you also need to put the width and coulmn properties inside double quotes. i.e,
drupal_add_js('
jQuery(document).ready(function () {
    if (jQuery.browser.msie && jQuery.browser.version < 10) {
            jQuery("li#megamenu-mlid-774 .megamenu-items, li#megamenu-mlid-842 .megamenu-items").columnize({
                "width": "420",
                "columns": "3"
            });
        }
  });', 'inline');

Answer: yes it has something to do with your selector starting with $.    Your code in your question may have worked in Drupal 6.  jQuery has changed in Drupal 7
Try wrapping your function like this:
(function ($) {

 // in this function, you can use the $ which refers to the jQuery object

}(jQuery));

For more information checkout
http://drupal.org/update/modules/6/7#javascript_compatibility

drupal_add_js and inline code


Generating PDF reports in Node JS/Express Web Application

Question: I am a newbie trying to build a web-app using NodeJS/Express and Handlebars for templating needs.
A part of the application deals with generating invoice for sales. I have written a handlebars template along with some javascript code to deal with addition/deletion of items and calculating total etc which works fine.
There is a need to generate PDF form of this invoice at the NodeJS server which contains dynamic content added at client side.
I am unsure how to proceed in implementing this. I have evaluated client side PDF generation options but it is not desirable for my use case.
Could you please let me know if it is possible to generate pdf at server side when there are dynamic elements in client side html page?
The app is similar to the one in this link: http://www.smarttutorials.net/invoice-system-using-jquery-autocomplete/
Dynamic part of the code is below:
//adds extra table rows
var i=$('table tr').length;
$(".addmore").on('click',function(){
    html = '
';
    html += '<input class="case" type="checkbox"/>	';
    html += '<input type="text" data-type="productCode" name="itemNo[]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off">	';
    html += '<input type="text" data-type="productName" name="itemName[]" id="itemName_'+i+'" class="form-control autocomplete_txt" autocomplete="off">	';
    html += '<input type="text" name="price[]" id="price_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">	';
    html += '<input type="text" name="quantity[]" id="quantity_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">	';
    html += '<input type="text" name="total[]" id="total_'+i+'" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">	';
    html += '
';
    $('table').append(html);
    i++;
});

//deletes the selected table rows
$(".delete").on('click', function() {
    $('.case:checkbox:checked').parents("tr").remove();
    $('#check_all').prop("checked", false);
});

Comment: Send data to server (AJAX), then use PDFKit.
Comment: @Chris G: Thanks for the quick reply. Do you mean that I should send the only data in these dynamically added rows or the entire html page to the server to generate pdf?
Comment: Check out PDFKit, then figure out the best route for yourself.
Answer: Seen as your using express, and have the ability to create web pages with this data on.
I would use https://www.npmjs.com/package/phantom
This can be used to convert you webpage into PDF's, you can also control page breaks using the CSS attribute page-break-after.. etc.
Comment: Thanks for the reply. I think phantom-html2pdf(https://www.npmjs.com/package/phantom-html2pdf) might be useful for me in this case as it supports css. I will give it a shot and let you guys know how it went.
Comment: @UmashankarVarma  The phantom package I pointed out of course also supports CSS.  There both internally using phantomjs-prebuilt, that in turn in is running phantomjs.  Basically phantom gives you more low level control, so it can be used for other things, not just creating PDF's.  eg. Unit Testing, screen grabbing into PNG's. etc.
Comment: I tried puppeteer: https://www.npmjs.com/package/puppeteer. Works as expected with code as in examples.
Answer: There is a github library called serverless-chrome that comes close to the functionality you are looking for.
It works with AWS lambda and nodejs. It uses serverless chrome to visit your website and take screenshot or save the whole website as a PDF file and displays the PDF file. The deployment is pretty simple and uses the serverless framework. I deployed the github library on a client's AWS account.
Here is how the demo link which you get after deployment.
https://1wphj1kzch.execute-api.ap-southeast-1.amazonaws.com/dev/pdf?url=http://www.gmail.com

Replace the http://www.gmail.com with the website link of your choice. It waits for the website to load completely and then takes the screenshot. You can deploy this and use the link like the one generated above to take screenshot and save them or you can use another lambda function and save the pdfs to your S3 bucket on AWS.
Best of all if you are new to AWS you get 400,000 lambda executions free every month.


Inserir coluna Oracle, apos uma coluna existente

Question: Estou precisando de ajuda. Tenho a tabela USUARIO, aonde tenho as colunas LOGIN, SENHA  porem preciso incluir a coluna chamada DATACRIACAO, porém gostaria de saber como inserir essa coluna DATACRIACAO após a coluna LOGIN, estou trabalhando com o Oracle 11g.
Answer: Para adicionar a coluna datacriacao na tabela usuario
ALTER TABLE usuario
ADD (datacriacao date)

Porém não é indicado alterar a sequencia das colunas assim como você quer, aqui é explicado o motivo
Comment: Esse comando por padrao inserir a coluna na ultima posição, porem precisa inserir ela apos a primeira coluna existente.
Comment: No caso eu ja tenho dados inseridos, não teria uma forma de fazer via comando, eu sei que no mysql se utilizar o comando AFTER + {COLUNA} ele inserir apos a coluna informada no after, no oracle não tem nada parecido ?
Comment: Alterei minha resposta com uma informação interessante que encontrei referente a alterar a sequencia de colunas após já ter dados inseridos na tabela
Comment: Faz um scriipt de insert (um programa como o sql developer faz automatico)  , dropa a tabela , recria a tabela com as posições corretas , roda o script de insert , mas na minha opinião muito trabalho por nada
Comment: Acredito que não há a necessidade assim como você comentou @Motta, pois o que vai determinar o retorno que ele vai ter é o `Select` que ele fizer. Pois se ao invés de `Select *` ele determinar a ordem das colunas `Select login, datacriacao, senha from usuario` o resultado sai na ordem que ele deseja. O que você acha?
Comment: Ajudou muito esse artigo, obrigado R.santos, me deu uma clareada no que preciso fazer.
Comment: Como disse dá para fazer mas não acho que fala o esforço.


Inner html add by ng-bind-html in angularjs

Question: I am generating bootstrap navigation menu by using angular directive. All of the things were Ok but when I reached finally to generate dropdown menu then I need to generate HTML dynamically. To generate HTML I have used angular ng-bind-html. The angular ng-bind-html is creating HTML very well. The ng-bind-html generating HTML looks like this.

Action

Another action

Something else here

Separated link

One more separated link

But I need only HTML looks like below no need this div ''.

Action

Another action

Something else here

Separated link

One more separated link

To generate HTML I have used method looks like this.
$scope.getDropdownMenu = function (menu) {
  try {
      var dropdownMenu = '
' +
      '
Action
' +
      '
Another action
' +
      '
Something else here
' +
      '

' +
      '
Separated link
' +
      '

' +
      '
One more separated link
' +
       '
';
        var trustedHtml = $sce.trustAsHtml(dropdownMenu);
            return trustedHtml;
        } catch (e) {
            throw e;
        }
    };

The full of bootstrap menu code is

Link

Link

        Dropdown

So how can i remove That dive which is no need to me. Is there any way Thanks.
Comment: Not sure what the problem is... [Works HERE](http://plnkr.co/edit/tT2oLYQZXZoJvXgIFETv?p=preview)
Comment: I'm not sure what your actual question is, but since you're generating HTML markup within your javascript function, you probably want [`ng-bind`](https://docs.angularjs.org/api/ng/directive/ngBind) instead of `ng-bind-html`. The latter will escape the angle brackets.
Comment: Hi @Dan, yes I want to generate Inner HTML by this method getDropdownMenu(submenu). ng-bind supports string but I need HTML.
Comment: I think that div is the least of what's wrong with your code... There's simpler ways to achieve what you're trying to do.
Answer: You'll need to create a custom directive
Plunker
app.directive('ngHtmlSafe',['$sce',function($sce){
  return {
    replace: true, /* don't use the parent element replace with your custom directive */
    template: 'template.html',
    restrict: 'A',
    scope: {
      text: '='
    },
    link: function(scope,el, attrs){
      scope.safe = $sce.trustAsHtml(scope.text)

      /* copy all parent attributes from the element you added the directive to */
      for (var i=0; i < attrs.length; i++) {
         el.attr(attrs.item(i).nodeName, attrs.item(i).nodeValue);
      }
    }
  }
}])

and add the directive to your element using ul instead of a div.

Change your Controller to only include the lis
$scope.getDropdownMenu = function (menu) {
  try {
      var dropdownMenu = '
Action
' +
      '
Another action
' +
      '
Something else here
' +
      '

' +
      '
Separated link
' +
      '

' +
      '
One more separated link
';
        var trustedHtml = $sce.trustAsHtml(dropdownMenu);
            return trustedHtml;
        } catch (e) {
            throw e;
        }
    };

This will essentially replace the element you attach your directive to.  So there's probably a better way to make it more generic but this works for your use case.
Comment: No this is not working. In this way the method getDropdownMenu(submenu) returns only string. I have to tagged as a HTML.
Answer: For HTML, you will need to bind to the property
Solution :

Note I moved the [innerHtml] to inside the div tag.
Leaving out the square brackets would bind to the attribute, so you would need to interpolate again


Extracting Multilevel xml into pandas dataframe along with node's absolute path as column names

Question: I have a huge xml with multilevel nodes and I am trying to parse the data into pandas dataframe.

`<?xml version="1.0" encoding="UTF-8"?>
<TestCodes>
  <TestCode ID="1">
      <Count>
          <Blant>
            <app_1>1</app_1>
            <app_s>2</app_s>
          </Blant>
          </Count>
        <TestCode>

The XML structure is fixed and doesn't change.I am new to python and XML parsing.I have tried to convert above XML to Dictionary but failed.Any help or inputs will be much appreciated.
Comment: Does this answer your question? https://stackoverflow.com/questions/28259301/how-to-convert-an-xml-file-to-nice-pandas-dataframe
Comment: @dheinz Thank you, But this doesn't apply to my question because in the above link key,web all are attributes of single node document. But mine is multilevel xml with nested child nodes.
Comment: Hmm, ok, I'm sorry but then I do not know the answer. I know that there is a method for deeply nested JSON files (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html)  but I cannot figure out a similar function for xml files.
Comment: @dheinz Thank you, I dont mind manually specifying the column names in dataframe but i need a way to parse through this XML
Comment: i dont think ur xml is properly formatted. check it again
Comment: @sammywemmyThank you, this is just a sample XML i generated which imitates actual XML but structure remains same. I have generated it just to show levels of parsing required
Answer: u can make use of parsel to extract the data u want; it has a simple syntax and  can help with malformed xml structures :
I used xpath syntax to get the data ... have a look at w3schools xpath syntax for guidance. summary : - if u r referencing a node, u can use / or // depending on the path u wish to take, and for attributes, u affix the @ symbol. To get the text from the path, attach the text() to it and use the getall() method to get all the values, or get() if u r interested in just the first element.
from parsel import Selector

#if you are reading from file :
with open('data.xml') as xml:
    data = xml.read()

content = Selector(text=data, type="xml")

mapping = {}
mapping["DeptCode"] = content.xpath("//DeptCode/@ID").getall()

mapping["OCC_TotalCount"] = content.xpath("//OCCCounter/TotalCount/text()").getall()

mapping["Test_app_large"] = content.xpath("//Test//app_large//text()").getall()

mapping["Test_app_small"] = content.xpath("//Test//app_small//text()").getall()

print(mapping)

{'DeptCode': ['1', '2'],
 'OCC_TotalCount': ['1', '1'],
 'Test_app_large': ['1', '1'],
 'Test_app_small': ['2', '2']}

#create dataframe
res = pd.DataFrame(mapping)

  DeptCode  OCC_TotalCount  Test_app_large  Test_app_small
0   1              1              1               2
1   2              1              1               2

Comment: Thank you for the answer,I tried this solution and here  "content = Selector(text=data, type="xml")" for "data=" I cannot copy the entire XML file contents because XML file is huge. Can I use XML file name instead and parse directly from file ?
Comment: Thanks a lot, I have tried to implement this solution it works fine but is there any error handling i have to care any page related to error handling concepts in selectors would be helpful.
Comment: Errors ... cant live with them, cant live without them ... i'll suggest u have a look at the [parsel](https://parsel.readthedocs.io/en/latest/index.html) docs for more info...  but if u do get any errors, it would have to be when reading in the file, and that means u have to spend some time with the ```requests``` docs.
Answer: Another method.
from simplified_scrapy import SimplifiedDoc
html = '''Your xml'''
doc = SimplifiedDoc(html)
for dept in doc.selects('DeptCode'):
    print(dept.ID, dept.TotalCount.text, dept.app_large.text, dept.app_small.text)

Result:
1 1 1 2
1 1 1 2


On a scale of 1 to 10, how likely is it that this question is using binary?

Question: I just read this interesting xkcd strip:

At first I thought it was funny, but as I got to ruminate a little over it, I was surprised to be unable to find an answer. As Karolis Juodelė pointed out, the probability is ε, as there is an infinite number of bases containing 1 and 10.
However, to get a finite answer, we can modify the puzzle like this:

On a scale of 1 to 10, how likely is it that this question is using
  binary vs. decimal?

So my question is: How should I solve this puzzle? Is there a correct answer at all? Is this what we call a self-reference paradox, like Multiple-choice question about the probability of a random answer to itself being correct?
Comment: This is not a puzzle. There is no method of evaluating the likelihood of things happening in other peoples heads. If you just want to get the right base, say $1$.
Comment: Actually, if you assume that all possible interpretations of $1$ and $10$ are equally likely, the probability is $0$, because all bases have $1$ and $10$. This could be base $2$, base $10$ or base $123456$.
Comment: She doesn't know what a 4 is, so it is either binary, ternary or base-4.  (It can't be unary because 10 is a number).
Comment: @anustart in your modified version, if your question is in binary (the word in common sense), then I don't understand your "2" there, but still your question is in base 10. Alternatively, if your question is in, say, tridecimal (the word in common sense), then your question is not in base 2 but in base 10. So I will definitely vote for base 10, like I said above.
Comment: Base $10$, definitely base $10$, [all number bases are base $10$](http://math.stackexchange.com/questions/166869/is-10-a-magical-number-or-i-am-missing-something)
Comment: @KarolisJuodelė, I meant the probability of binary vs. decimal. I edited my question for clarity now.
Comment: @peterwhy Oh, I see your point now, that base-10 is not the same as decimal if the question is base-2.
Comment: AFAIS if the question is decimal, the answer is `1+(10-1)\2 = 5.5`, but if it's binary, the answer is `1_2+(10_2-1_2)\10_2 = 1+(2-1)\2 = 1.5`.
Comment: This type of question is not to be taken seriously. But if I read the strip correctly, there is the indication that $4$ is not a known digit, so it is definitely not in decimal. Taking as (completely unreasonable) axiom that digits must be taken from the list $0,1,2,3,\ldots,9,A,B,\ldots$ in that order, the base can only be two, three, or four.
Comment: @MarcvanLeeuwen It is not a puzzle, I am asking whether there is a single correct answer that does not depend on itself. If there is an answer that will be the same no matter whether the question is binary or decimal. I didn't ask this question to "riddle" others.
Comment: @anustart: My point is that one should take into account the fact that the strip mentions the digit $4$ (twice), and something should be done with that information, which none of the comments/answer so far do (except one). Since the digit appears to cause puzzlement (my interpretation of the drawing), I conclude that it is **definitely not decimal**. And asking about (only) binary vs. decimal is certainly not implied by the strip, other bases must be considered too.
Comment: @MarcvanLeeuwen I'm looking for a generic answer, an answer that is correct no matter what happens in the asker's head.
Comment: @anustart: MU..
Answer: (If I understand correctly, $10$ means certainly in binary and $1$ means certainly in decimal)
To answer your modified question, if I were to think like in your last comment (2014-01-11 20:48:42Z), then I would answer:

As likely as $1+\dfrac{10-1}{1+1} = \dfrac{11}{1+1}$

But for me, I choose to answer

As likely as $1+1+\dfrac{1+1-10}{(1+1)^{1+1+1}}$
Comment: But then, why assign 50:50 chance to 1 and 10? If the question is in decimal, then 1, if binary then 10.
Comment: If the question is decimal, the scale is 1 to 10, which means 1 = never binary and 10 = always binary, and also 5.5 will be a 50/50 chance. If the question is binary, the scale is 1 to 2, which means 2 = always binary and 1.5 (or 1.1 as binary) will be a 50/50 chance. Therefore I'd choose to answer "If decimal 5.5, if binary 1.1". Is there a single answer that will be correct independent on its base?
Comment: How about `(b+1)/2` where `b` is the base?
Comment: That is equivalent to the first answer I gave above: $\frac{11}{1+1}$.
Comment: Ok, then I just realized the if the question is binary, the answer is binary as well. +1!
Comment: Ok, I get it now. You're absolutely right. Thanks!


How to SUM columns on multiple conditions in a GROUP BY

Question: I am trying to return a list of Accounts with their Balances, Outcome and Income
Account            Transaction
-------            -----------
AccountID          TransactionID
BankName           AccountID
Locale             Amount
Status

Here is what I currently have. Could someone explain where I am going wrong?
select
    a.ACCOUNT_ID,
    a.BANK_NAME,
    a.LOCALE,
    a.STATUS,
    sum(t1.AMOUNT) as BALANCE,
    sum(t2.AMOUNT) as OUTCOME,
    sum(t3.AMOUNT) as INCOME
from ACCOUNT a
left join TRANSACTION t1 on t1.ACCOUNT_ID = a.ACCOUNT_ID
left join TRANSACTION t2 on t2.ACCOUNT_ID = a.ACCOUNT_ID and t2.AMOUNT < 0
left join TRANSACTION t3 on t3.ACCOUNT_ID = a.ACCOUNT_ID and t3.AMOUNT > 0
group by a.ACCOUNT_ID, a.BANK_NAME, a.LOCALE, a.[STATUS]

UPDATE
Have corrected the t2 left join syntax as per the comment below.
The output I am expecting is hopefully obvious from the question. For 6 accounts, the SQL should return 6 accounts with their Balance, Income and Outcome of that account.
The problem with the SQL I provided was that the numbers are wrong! As per the comments I think the problem stems from joining multiple times which is summing the amounts incorrectly.
Comment: Shouldn't the join for TRANSACTION t2 be on t2 as in on t2.ACCOUNT_ID = a.ACCOUNT_ID ? {Please edit the question. Promoted to comment from Neil Moss' answer below}
Answer: Since you didn't tell us what's going wrong (that is, describe the behavior you get in addition to describing the the behavior you expect), it's hard to say where, but there are a couple of possibilities. Neil points out one. Another is that since you join on the transaction table three times, you're pairing transactions with transactions and getting repetitions. Instead, join on the transaction table a single time and change how you sum up the Amount column.
Select
    a.ACCOUNT_ID,
    a.BANK_NAME,
    a.LOCALE,
    a.STATUS,
    sum(t.AMOUNT) as BALANCE,
    sum((t.AMOUNT < 0) * t.AMOUNT) As OUTGOING,
    sum((t.AMOUNT > 0) * t.AMOUNT) As INCOMING
From ACCOUNT a
Left Join TRANSACTION t On t.ACCOUNT_ID = a.ACCOUNT_ID
Group By a.ACCOUNT_ID, a.BANK_NAME, a.LOCALE, a.[STATUS]

You can use CASE expressions as a more readable alternative to the multiplications:
Select
    a.ACCOUNT_ID,
    a.BANK_NAME,
    a.LOCALE,
    a.[STATUS],
    sum(t.AMOUNT) As BALANCE,
    sum(CASE WHEN t.AMOUNT < 0 THEN t.AMOUNT ELSE 0 end) As OUTCOME,
    sum(CASE WHEN t.AMOUNT > 0 THEN t.AMOUNT ELSE 0 end) As INCOME
From ACCOUNT a
Left Join [TRANSACTION] t On t.ACCOUNT_ID = a.ACCOUNT_ID
Group By a.ACCOUNT_ID, a.BANK_NAME, a.LOCALE, a.[STATUS]

Comment: @outis - AFAIK, t-sql does not have a `LEAST` nor `GREATEST` function.
Comment: @Thomas: well, that sucks. Altered so as not to use them.
Comment: Provided final answer in my question. Accepted your answer however used SUM(CASE WHEN... for OUTCOME and INCOME values.
Answer: Did you mean:
select
    a.ACCOUNT_ID,
    a.BANK_NAME,
    a.LOCALE,
    a.STATUS,
    sum(t1.AMOUNT) as BALANCE,
    sum(CASE WHEN t2.AMOUNT < 0 THEN t2.Amount ELSE 0 END) as OUTCOME,
    sum(CASE WHEN t3.AMOUNT > 0 THEN t3.Amount ELSE 0 END) as INCOME
from
    ACCOUNT a
    left join TRANSACTION t1 on t1.ACCOUNT_ID = a.ACCOUNT_ID
    left join TRANSACTION t2 on t2.ACCOUNT_ID = a.ACCOUNT_ID
    left join TRANSACTION t3 on t3.ACCOUNT_ID = a.ACCOUNT_ID
group by
    a.ACCOUNT_ID, a.BANK_NAME, a.LOCALE, a.[STATUS]

Comment: Just missing the END on the CASE statement.
Comment: Upvoted but could not accept answer as my question was vague regarding the results and should have only joined on transaction table once.
Answer: I'm not sure why you would need the multiple joins. Couldn't you simply do something like:
Select
    a.ACCOUNT_ID
    , a.BANK_NAME
    , a.LOCALE
    , a.STATUS
    , Sum ( t.Amount ) As Balance
    , Sum( Case When t.Amount < 0 Then Amount End ) As Outcome
    , Sum( Case When t.Amount > 0 Then Amount End ) As Income
From ACCOUNT a
    Left Join TRANSACTION t
        On t.ACCOUNT_ID = a.ACCOUNT_ID
Group By a.ACCOUNT_ID, a.BANK_NAME, a.LOCALE, a.[STATUS]

Answer: The join for TRANSACTION t2 should be on t2 as in on t2.ACCOUNT_ID = a.ACCOUNT_ID


Problem with displaying field using Views

Question: My goal is to use Search API so that I can create a custom search page using Views.  I want to add the "rating" widget (rate module), but there is no way to include it in the Search API fields. Thus, I tried to fix it by adding custom field to Search API index.
<code>function rate_entity_property_info_alter(&$info) {
  $info['node']['properties']['widget'] = array(
    'label' => t('Rating widget'),
    'description' => t('Rating widget'),
    'getter callback' => 'display_widget',
  );
}
function display_widget($node) {
     print rate_generate_widget('1', 'node', $node->nid);
}
</code>
However, I am getting AJAX errors

and problems with displaying widgets.

Please can someone help me to solve this problem.
Thanks
Comment: Is this a Solr based search?
Answer: If this is a Solr/ElasticDB search backend under Search API, you could try this approach.
Create a view mode on the node type (ex. Search Result), then create a template with the html markup when rendered for it. Include all the fields in the display and configure the formatters as you want them.
Next, install Search API View Modes, and configure that view mode to be indexed. It will render that node before indexing it into a new field (search server side). Then, you can create a view display that shows that field, which is just HTML, and bypass some of these issues.
I use this method in every Search API based search I encounter. You're basically storing the rendered HTML on the search server, then printing that as the result.
I can't tell if you are on Drupal 7 or 8. Note that the 8.x branch 'works' but may have some bugs. I have only been able to test simple setups and not use it on production like the 7.x branch.


What is the point of having async Main?

Question: As we know, C#7 allows to make Main() function asynchronous.
What advantages it gives? For what purpose may you use async Main instead of a normal one?
Comment: async does not compose very well, if you want to await something properly then you have to make your method async as well.  Turtles all the way up, bummer if that is the Main() method.
Answer: It's actually C# 7.1 that introduces async main.
The purpose of it is for situations where you Main method calls one or more async methods directly. Prior to C# 7.1, you had to introduce a degree of ceremony to that main method, such as having to invoke those async methods via SomeAsyncMethod().GetAwaiter().GetResult().
By being able to mark Main as async simplifies that ceremony, eg:
static void Main(string[] args) => MainAsync(args).GetAwaiter().GetResult();

static async Task MainAsync(string[] args)
{
    await ...
}

becomes:
static async Task Main(string[] args)
{
    await ...
}

For a good write-up on using this feature, see C# 7 Series, Part 2: Async Main.
Comment: The internal implementation of the "async main" is just a synchronous wrapper that does .Wait().
Comment: it seems they changed their mind multiple times. https://stackoverflow.com/a/9212343/4767498 it was allowed, then disallowed, then allowed again hmm. would be interesting to know the reason behind it.
Comment: @David - What I can't understand is, given that control yields to the caller upon on await, why despite the async main that the console app doesn't just exit before any execution can finish...?
Comment: @Salgat good point! I looked at the IL produced by a .NET Core 2.2 console app using latest C# language features and it did have a void Main method in there calling GetAwiater().GetResult() on the async Main. But I still appreciate not having to write that myself :-)

What is the point of having async Main?


Node reference + i18n - How to display only referenced nodes for the current language?

Question: I have two content types with multilingual content (French/English), Publications and Profils.
I have set up a node reference on Publication content type to link any Publication with the concerned Profil.
Unfortunately all Profils appear in listing, which is very confusing for the user. I would like to only display french Profiles when editing/creating a french Publication (and same for english content).

I just discovered the module i18n node reference synch (https://www.drupal.org/project/i18n_node_reference), but unfortunately this module doens't provide this kind of feature.
Answer: If it would be an option for you to switch from using node reference to entity reference, then you could try to use the Translated Entity Reference module. From its project page:

... brings better i18n support to Entity Reference field selection widget.


API mais adequada - OpenGL ES 2.0 x Canvas x Drawable

Question: Bom dia,
Gostaria de fazer um aplicativo para Android para fazer o seguinte: exibir a planta de uma casa no celular, e ao usuário tocar em um cômodo na tela, a cor do cômodo mudar.
Eu estou familizarizado com OpenGL ES 2.0, e acho que é uma ferramenta excelente para gráficos, mas nunca mexi ainda com o Canvas e Drawable.
Qual é a API mais indicada para eu utilizar em meu aplicativo?
Obrigado,
Answer: OpenGL x Canvas
OpenGL lhe dará controle total sobre os gráficos que você está usando. Você não vai ter muitas limitações a longo prazo sobre o que você gostaria de fazer. Você pode fazer um bom projeto em 3D em um Android usando OpenGL, como você pode processar grandes quantidades de polígonos e sobrepor gráficos 2D em cima de qualquer coisa. É uma grande quantidade de trabalho, no entanto.
A principal diferença é que o OpenGL é muito mais rápido em comparação com Canvas (Gráficos 2D Android desenho de superfície). Embora a aceleração de hardware está habilitado para Canvas, é um pouco difícil de usá-lo de forma eficaz.
Canvas faz a vida mais fácil. É fácil de usar e simples de entender, mesmo para alguém novo para a Computação Gráfica.
No final, vai depender do que você precisa fazer. Se você precisar de coisas extravagantes como Geometria, iluminação etc, então você deve definitivamente ir para OpenGL. Além disso, se você precisa, em seguida, OpenGL 3D é a sua única opção, uma vez Canvas só suporta gráficos 2D.
Drawble: Uma maneira simples de adicionar gráficos a sua aplicação fazendo referência a um arquivo de imagem a partir de seus recursos do projeto. Tipos de arquivos suportados são PNG (preferencial), JPG (aceitável) e GIF (desanimado). Esta técnica seria obviamente preferido para ícones de aplicação, logos ou outros gráficos, tais como os utilizados em um jogo.
Fonte: http://developer.android.com/guide/topics/graphics/2d-graphics.html
Fonte: http://developer.android.com/training/graphics/opengl/index.html


How do I prove a bound on the sum of volumes of disjoint rectangles in an oblique rectangle?

Question:
Before I start, let's not assume anything about volume, since it is not precise unless Lebesgue measure is defined.

Let $\mathscr{B}=\{\prod_{i=1}^n [a_i,b_i)\subset \mathbb{R}^n:a_i\le b_i\}$ (That is, it is the set of half-open rectanges.)
Let's say $\mu(\prod_{i=1}^n [a_i,b_i))=\prod_{i=1}^n |b_i - a_i|$ for all element in $\mathscr{B}$.
Let $T:\mathbb{R}^n\rightarrow \mathbb{R}^n$ be an orthogonal operator.
Let $A\in \mathscr{B}$ and $\{A_k\}_{1≦k≦m}$ be a mutually disjoint finite sequence in $\mathscr{B}$.
Let's assume $\bigcup_{1≦k≦m} A_k \subset T(A)$.

How do I prove that $\mu(\bigcup_{1≦k≦m} A_k) \le \mu(A)$?
Comment: Moreover, if this cannot be proven in short, please please recommend me a good text which treats this *precisely*
Comment: Maybe consult "A concise introduction to the Theory of Integration" by Daniel Stroock.
Answer: This would be used to show that Lebesgue measure is invariant under orthogonal transformation.  So (as Mario noted) this is in the textbooks.
Probably I would prove a more general thing first, for linear transformation $T$ not necessarily orthogonal,
$$
\mu(T(A)) \le |\det T|\;\mu(A)
\tag{1}$$
and then for orthogonal $T$ observe that $|\det T| = 1$.  And for (1), first do it in case $T$ is an elementary row operation, since Gaussian reduction shows that general $T$ can be written as a finite composition of these.  But even that requires some work.


android studio: need to load random image and on top random text and then save them as jpeg to share with other apps

Question: Which is the best way to achieve this. image view or canvas?
1)load random image from resources
2)on top the image load random text from strings
3)then save them as jpeg to share with other apps
i have tried with text view with image background, but saving image is not possible.
<code> <CustomView
            android:id="@+id/view"`enter code here`
            android:layout_width="match_parent"
            android:layout_height="512dp" />
</code>
Answer: you can convert your displayed view to bitmap using
<code>public static Bitmap loadBitmapFromView(View v) {
    Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
    v.draw(c);
    return b;
}
</code>
Now you can share this bitmap.
check more details here
Converting a view to Bitmap without displaying it in Android?


Moving around a differential

Question: Suppose $f(x)$ is a real-valued differential univariate function.
Consider a measure of sensitivity of this function with respect to a point $x$ in the domain.
$$s(x)=\frac{x\frac{df(x)}{dx}}{f(x)}.$$
My questions #1: Why is it legal to move around the differential in the following form?
$$\frac{\frac{df(x)}{f(x)}}{\frac{dx}{x}}.$$
My question #2: When is it illegal to do this?
My question #3: Why is the second form an expression of a percent change in $f(x)$ in the numerator and a percent change in $x$ in the denominator?
Answer: Notice that $$s_f(x)=x\left(\frac1{f}\frac{\mathrm{d}f}{\mathrm{d}x}\right)(x)=x\left(\frac{\mathrm{d}\ln\circ{f}}{\mathrm{d}x}\right)(x)=x\left(\frac{\mathrm{d}\ln\circ{f}}{\mathrm{d}\ln}\frac{\mathrm{d}\ln}{\mathrm{d}x}\right)(x)=x\left(\frac{\mathrm{d}\ln\circ{f}}{\mathrm{d}\ln}\right)(x)\left(\frac{\mathrm{d}\ln}{\mathrm{d}x}\right)(x)=x\left(\frac{\mathrm{d}\ln\circ{f}}{\mathrm{d}\ln}\right)(x)\frac1{x}=\left(\frac{\mathrm{d}\ln\circ{f}}{\mathrm{d}\ln}\right)(x).$$ So far, this is all valid, and it includes merely using the chain rule. $$s_f(x)=\left(\frac{\mathrm{d}\ln\circ{f}}{\mathrm{d}\ln}\right)(x)=\frac{(\mathrm{d}\ln\circ{f})(x)}{(\mathrm{d}\ln)(x)}=\frac{\left(\frac{\mathrm{d}f}{f}\right)(x)}{\left(\frac{\mathrm{d}x}{x}\right)(x)}=\frac{\frac{\mathrm{d}f(x)}{f(x)}}{\frac{\mathrm{d}x}{x}}.$$
Every step in this derivation is valid, except for one step, and one step only. The problematic step is $$\left(\frac{\mathrm{d}\ln\circ{f}}{\mathrm{d}\ln}\right)(x)=\frac{(\mathrm{d}\ln\circ{f})(x)}{(\mathrm{d}\ln)(x)}.$$ You cannot treat a derivative operator as a fraction of differential forms, because differential forms are not multiplicatively invertible. Nonetheless, this invalid step does "accidentally" result in the correct answer, and it smoothly allows you to go from $$x\left(\frac1{f}\frac{\mathrm{d}f}{\mathrm{d}x}\right)(x)$$ to $$\left(\frac{\mathrm{d}\ln\circ{f}}{\mathrm{d}\ln}\right)(x).$$ The reason behind these illegal manipulations giving the correct result is because although you cannot actually divide differential forms, it turns out that there is a bijection that maps the differential form $df$ to the derivative of $f.$ This bijection occurs because differential forms carry a vector space, and so, for the coordinate basis $\{\mathrm{d}x\},$ the coefficients with respect to that basis for any given vector $df.$ This stays true in higher dimensions.
Comment: Thanks! it clears up a lot!
Comment: Angle, thanks for the response. Is the circle for the composition or chain rule? Just a point of clarification.
Comment: The circle is composition. It means $(\ln\circ{f})(x)=\ln[f(x)],$ and so $(\ln\circ{f})'(x)=\frac1{f(x)}f'(x).$

Moving around a differential


Laravel HTTP 500 Error after a while

Question: I have problem with laravel in shared hosting. I deployed it on cPanel and was successfully running. After 4 or 5 hours I got HTTP 500 error. I checked error log and I figured out that some vendor files are removed given the following stacktrace:

Uncaught class: Illumination\FileSystem\FileSystem.php

I placed my project folder before public_html and even edited index.php.
UPDATE
I ran composer install on localhost then uploaded files again. I gets back after some time. I think there is something wrong with server. Does anyone know?
Comment: Remove vendor folder and run "composer install" again.
Comment: I gussed the problem K Arun Singh said. Thanks!
Comment: It is a permission issue. Give full access to a folder then it will solve the issue.
Comment: Folders are all 755 and files are 644
Comment: Unfortunatly its on shared hosting. I've done that and it gets back after some time.
Comment: You can do it in your local then you can upload vendor folder.
Comment: As you said, it was working fine for a while.. Security features of some web hosting might be responsible for this issue, file might be flagged as malware and might be deleted by hosting, you can contact your hosting provider to help resolve this issue.
Answer: As you said, it was working fine for a while.. Security features of some web hosting might be responsible for this issue, file might be flagged as malware and might be deleted by hosting, you can contact your hosting provider to help resolve this issue.
Comment: Thanks the problem was hosting
Comment: welcome @Martin ZD, you can give me a thumbs up, if it saved your time :)

Laravel HTTP 500 Error after a while


PyGTK, Glade, Changing the window view and threads

Question: Forgive me if this seems like a stupid question, just so far no where on the internet can I find someone offering a solution to this and I just wanted to get some feedback from someone with more experience than myself (I've only been using python, pyGTK and Glade for 2 days now).
I have a UI window displaying and it updates with messages from a thread that is handling a bluetooth connection.
This is fine and I have the application closing and running quite reliably, the problem is, after a bluetooth connection is made I wish to maintain the bluetooth thread (i.e. keep the connection going) but completely change the UI of the main window.
Now the impression I am getting from pyGTK applications made from glade, is that the easiest thing to do is just open a new window. Is this really the best option? Can I cut the tree of widgets off at the root, maintaining the window widget but add on a new set of widgets from a separate glade file?
If opening a new window is the best option, am I right in assuming that the bluetooth thread can be kept alive during this transition, providing I update any callbacks?
Any help or pointers would be great.
Cheers,
Matt
Answer: If i well understand the connection is strictly coupled with the window. This seems like a good example of aggregation and composition. Simple decouple the window from the connection. Without code or more information is impossible to be more accurate. After this you can use both the solution you proposed: create a new window with a reference of the connection thread or "detach" the whole widgets tree and attach a brand new one, simple use gtk.Container.remove and gtk.Container.add (gtk.Window derive from gtk.Container).
If this is not enough modify your questions and add some info and code.
Answer: I think you already know, but GTK (PyGtk) is thread aware and not thread safe, so, modifying the UI from another thread that is not the one that holds gtk's main loop will probably make your program to crash.
You can make use of the .glade files several times, you can use just one widget (and its children) if you want and ignore everything else, that's why gtk.glade.XML accepts a root parameter. This root is where your widget tree will start.
<code>gladeobject = gtk.glade.XML(path_to_glade_file, root='widgetname')
</code>
You can safely hide the windows and keep it updated, and avoid the "new window" solution.


How to get data of 2 tables with groupBy and orderBy id & get last inserted data

Question: I'm trying to get the data from 2 different tables by using join method. I have done creating a Eloquent procedure to achieve that which is working perfectly with orderBy() method as well.
Now I just wanted to group the data based on a column with the same Eloquent methods is not returning me the latest/last inserted data.
My query for your reference below,
$def_reminders = Invoice::from('invoices AS inv')
->join('reminders_calendar AS remcal', 'remcal.invoice_id', '=', 'inv.id')
->where([
    'inv.user_id' => 1,
    'inv.is_deleted' => '0',
])
->where('inv.reminder_status', '!=', 'Enabled')
->whereDate('remcal.date_when', '2024-01-03')
->whereIn('remcal.reminder_type', ['InProgress', 'Waiting'])
// ->whereRaw('remcal.id = (select max(`id`) from reminders_calendar)')
->selectRaw('MAX(remcal.id) as remcal_id, remcal.invoice_id AS remcal_invoice_id, remcal.*, inv.*')
->groupBy('remcal.invoice_id')
->orderBy('remcal.id', 'desc')
->get();

Whenever I commented the groupBy('remcal.invoice_id') method returns me all data with order of latest/ last data to previous data correctly.
I'm bit confused to get the data from 2 tables when with the groupBy() and orderBy() method in the join query.
Answer: Finally got a solution to make it work. When am use groupBy, it groups the rows that have the same values in specified columns into aggregated data. In my case, it's grouping by remcal.invoice_id. And, when I use orderBy('remcal.id', 'desc'), it's trying to order by the id of remcal in descending order. But because of the groupBy, it might not be the latest id that gets selected in the group, hence am not getting the latest inserted data.
My working code as follows,
$sub = DB::table('reminders_calendar')
->select('invoice_id', DB::raw('MAX(id) as max_id'))
->groupBy('invoice_id');

$def_reminders = DB::table('invoices AS inv')
->joinSub($sub, 'max_remcal', function ($join) {
    $join->on('inv.id', '=', 'max_remcal.invoice_id');
})
->join('reminders_calendar AS remcal', function ($join) {
    $join->on('inv.id', '=', 'remcal.invoice_id')
         ->on('remcal.id', '=', 'max_remcal.max_id');
})
->where([
    'inv.user_id' => 1,
    'inv.is_deleted' => '0',
])
->where('inv.reminder_status', '!=', 'Enabled')
->whereDate('remcal.date_when', '2024-01-03')
->whereIn('remcal.reminder_type', ['InProgress', 'Waiting'])
->select('remcal.*', 'inv.*')
->orderBy('remcal.id', 'desc')
->get();


android development architecture (android vs java web app)

Question: I'm a Java webapp developer who is new to Android development.  In general, my web apps have a DB layer, a POJO layer, a UI layer, and a BusinessProcess layer.  In my research of Android applications, I have not come across the BusinessProcess layer.  I have implemented my app with one, but I find it clunky, having to pass in either the DB object or the ApplicationContext in order to access the DB but there are times when I find that I have redundant code.  I'd rather have an extra layer handle the logic than copy-and-paste it three times in an Activity.  In general, what do other people do?  What do you recommend?
Answer: A service http://developer.android.com/guide/components/services.html such as IntentService http://developer.android.com/reference/android/app/IntentService.html would act as your business process layer, yet most mobile applications are not generally thick clients but thin clients than user a remote web server as the content and business process authority, at which point the service (or sometimes ContentProvider http://developer.android.com/guide/topics/providers/content-providers.html) would interact with the remote server and cache results in a database.
See http://mobile.tutsplus.com/tutorials/android/android-fundamentals-intentservice-basics/
Edit: A bound service would suit your purposes well, depending if you need the work done synchronously instead of asynchronously.


formulario auto-populado com os restantes dados de um dos campos selecionados

Question: Queria ter um formulário dinâmico em que a única coisa que se pede é a seleção de um utilizador u de uma lista de utilizadores passada para do model apartir de um controlador, os campos email e estado devem ser automaticamente exibidos dependendo do utilizador que esteja selecionado.
o objeto utilizador tem a seguinte classe:
public class Utilizador{
  private String perfil;
  private String email;
  private string estado;

  ...
}

os elementos do formulário estao organizados da seguinte forma:

perfil:

     <select class="form-control" th:field="*{hhFrom}">
        <option th:each=" u : ${utilizadores}" th:value=""
             th:text="${u.perfil}">Options
        </option>
     </select>

email:

estado:

estou ciente que th:text="${u.email} e th:text="${u.estado} estão a apontar p um objeto do tipo utilizador que não é visivel no lugar onde se encontram, mas o meu objetivo era que se possa contornar de alguma forma este problema.
Answer: Você pode passar o {$utilizadores} para um array (caso não estiver) e então trabalhar com o INDEX como se fosse um ID utilizando <option value="index">Nome do perfil</option> e então chamar a alteração com $('selector').change(function() {...})
Ficaria assim:

$('document').ready(function () {
  // Apenas para o exemplo
  class Utilizador {
    constructor(perfil, email, estado) {
      this.perfil = perfil;
      this.email = email;
      this.estado = estado;
    }
  }

  var utilizadores = Array(2); // Array com os utilizadores
  utilizadores[0] = new Utilizador("Fulano", "firstname.lastname@example.com", "SP");
  utilizadores[1] = new Utilizador("Ciclano", "email@example.com", "RJ");
  // Apenas para o exemplo

//Loop no array para criar um option com value=(INDEX do array) e com texto=(Perfil)
  for (var i = 0; i < utilizadores.length; i++) {
    $('#perfil').append("<option value=" + i + ">" + utilizadores[i].perfil + "</option>");
  }

//Buscar o utilizador pelo INDEX do array
  function updateFields(i) {
    if (i == -1) {
      $('#email').text("");
      $('#estado').text("");
    } else {
      $('#email').text(utilizadores[i].email);
      $('#estado').text(utilizadores[i].estado);
    }
  }

  $('#perfil').change(function () {
    var i = $(this).find(":selected").val(); // i = value do option selectionado
    updateFields(i);
  });
});

perfil:

     <select class="form-control" th:field="*{hhFrom}" id="perfil">
  <option value="-1">Selecione um perfil</option>
     </select>

email:

estado:


Prove that $\log(1 + \sqrt{1+x^2})$ is uniformly continuous?

Question:
Problem  Prove that  $$\log(1 + \sqrt{1+x^2})$$ is uniformly continuous.

My idea is to consider $|x - y| < \delta$, then show that
$$|\log(1 + \sqrt{1+x^2}) - \log(1 + \sqrt{1+y^2})|
= \bigg|\log\bigg(\dfrac{1 + \sqrt{1+x^2}}{1 + \sqrt{1+y^2}}\bigg)\bigg| < \epsilon$$
But I couldn't find a choice for $x, y$ that could implies the above expression is true. Completing the square doesn't seem to help at all. Any idea?
Comment: Uniform continuity only makes sense over a given domain. Since this function is continuous, continuity is trivial over any compact set. Are you asked to show this over $\mathbb R$?
Comment: @PatrickDaSilva: Yes, I want to show this function is uniformly continuous over $\mathbb{R}$.
Answer: The derivative of $f(x)=\log(1 + \sqrt{1+x^2})$ is $\frac{x}{1 + x^2 + \sqrt{1 + x^2}}$, which is bounded in the whole real line since it is continuous and tends to $0$ as $x\to\pm\infty$. By the Mean Value Theorem, $f$ is Lipschitz and so uniformly continuous.
Comment: Since $1+x^2\geq 1$ and $\sqrt{1+x^2}\geq |x|$ for all $x$, it follows that $|f'(x)|\leq \dfrac{|x|}{1+|x|}< 1$ for all $x$, giving more specifically $|f(x)-f(y)|<|x-y|$ for all $x$ and $y$ (although the best Lipschitz constant is smaller than $1$).
Comment: The best Lipschitz constant is $0.300283\cdots$.
Comment: Or $\frac{\sqrt{2 \left(-1+\sqrt{5}\right)}}{2+\sqrt{2 \left(3+\sqrt{5}\right)}}$?
Comment: @JonasMeyer, WA says it's $(\sqrt5-2) \sqrt{1/2 (1+\sqrt5)}$.
Comment: They're the same, I just didn't get as pretty a form initially using Mathematica.  Also $\sqrt{\frac{1}{2} \left(-11+5 \sqrt{5}\right)}$.
Comment: @lhf: Very neat proof. Thanks.
Answer: Note that $t\mapsto \log t$ is uniformly continuous on $[1,\infty)$ (proven below). Note also that $t\mapsto 1+\sqrt{1+t^2}$ is uniformly continuous on $\mathbb R$ (also proven below). As the composition of uniformly continuous functions is uniformly continuous, the result follows.
To see that $\log$ is uniformly continuous on $[1,\infty)$, fix $\varepsilon>0$. Assume that $1\leq x<y$, $y-x<\delta$. Then $y/x<1+\delta/x\leq1+\delta$, and so
$$
\log y-\log x=\log \frac y x\leq\log(1+\delta);
$$
if we choose $\delta$ small enough so that $\log(1+\delta)<\varepsilon$, we are done.
For the uniform continuity of $g:t\mapsto 1+\sqrt{1+t^2}$, fix $\varepsilon>0$. Choose $x_0$ such that $\sqrt{1+x^2}>3/\varepsilon$ if $|x|\geq x_0$. Since $g$ is continuous on the compact set $[-x_0-1,x_0+1]$, it is uniformly continuous there. So there exists $\delta_1>0$ such that $x,y\in[-x_0,y_0]$ with $|y-x|<\delta_1$ implies $|g(y)-g(x)|<\varepsilon$.
Now let $\delta=\min\{\delta_1,\varepsilon/3,1\}$. Suppose that $|x-y|<\delta$. If both $|x|<x_0$, then $|y|<x_0+1$ and so $|g(y)-g(x)|<\varepsilon$ by the uniform continuity on the compact set. If $|x|\geq|x_0$, then
$$
|g(y)-g(x)|=|\sqrt{1+y^2}-\sqrt{1+x^2}|\leq|\sqrt{1+y^2}-|y||+||y|-|x||+||x|-\sqrt{1+x^2}|\\
\leq\frac1{|y|+\sqrt{1+y^2}}+|y-x|+\frac1{|x|+\sqrt{1+x^2}}<\frac1{\sqrt{1+y^2}}+\frac1{\sqrt{1+x^2}}+\frac\varepsilon3\\
<\frac\varepsilon3+\frac\varepsilon3+\frac\varepsilon3=\varepsilon.
$$


Create Page When Category created/added programatically

Question: I need to create wordpress page whenever a new category is added/created. I need to do it programatically, is there any hook/filter in wordpress to achieve such functionlaity, like save_post filter for posts.
Thank You.
Answer: Yes, you have the action hook created_$taxonomy. For the taxonomy Category:
add_action( 'created_category', function( $term_id, $tt_id )
{
    // The new category ID is $term_id
    // Use it to do your thing
}, 10, 2 );


How to cast ItemsPanelRoot to SwapChainPanel

Question: I was using HelixToolkit on UWP platform. Recently I am trying to change some of its features so I wrote a new viewport, imitating one in the HelixToolkit. Here is a problem I encountered that did not happen in HelixToolkit.
To create a SwapChainPanel in the Viewport(a class derived from ItemsControl class) , HelixToolkit directly convert ItemsPanelRoot into SwapChainPanel.
this.d3dTarget = new SwapChainTarget((SwapChainPanel)this.ItemsPanelRoot, this);

However, when my code come to this line, the runtime pops an exception:

System.InvalidCastException: Unable to cast object of type
  'Windows.UI.Xaml.Controls.StackPanel' to type
  'Windows.UI.Xaml.Controls.SwapChainPanel'.

Pausing right before the casting, I see

Why is it showing StackPanel?
And if I pause before the HelixToolkit one, it shows a bunch of internal exceptions.
What could be the cause between these two differences? And is there an alternative way to create a swapchain in a wrapped up way to contain other items?
Answer: The line you quoted doesn't create the SwapChainPanel, it simply retrieves the SwapChainPanel that was put in the ItemsPanelTemplate.
This is happening here: https://github.com/helix-toolkit/helix-toolkit/blob/d386c9e1313ae1bbb1c179a17007e9b59ae221a6/Source/HelixToolkit.UWP/Themes/Generic.xaml

If you want to reproduce the same behavior, make sure the ItemsPanelTemplate of your ItemsPanel is set accordingly.
Comment: I see, there is indeed a Xaml file that I have overlooked, I'll have a try right away.


Links to Online Videos of Good-Quality Lectures by Mathematicians

Question: I am not trying to do anything new here, but I would like to start an activity that has been going on at Math Overflow. Hopefully, people here at the Math StackExchange can also enjoy the good stuff.
If you know of any online videos of good-quality lectures by mathematicians, whether they are about some seminal topic, an introduction to some new exciting idea, a re-exploration of a well-known area, or simply about how they do mathematics (like Paul Halmos), please post a link here with a brief description of the contents of the video.
Hopefully, we can start a video bank here! Thank you very much for your contribution!
Comment: could you provide the link to Math Overflow to this question?
Comment: @MaoYiyi I think he is refering to http://mathoverflow.net/questions/54430/video-lectures-of-mathematics-courses-available-online-for-free
Answer: The audio isn't great but Serre's "Writing Mathematics Badly" is classic. It's a discussion of what is and what is not good mathematics notation, style, etc. It also has quite a bit of humor mixed in:
Part 1
Part 2
Part 3
Answer: Let me contribute by posting the following links:
Part 1
Part 2
Part 3
Part 4
Part 5
Part 6
It is a talk by Paul Cohen about his work on the Continuum Hypothesis and his interactions with Kurt Gödel. This talk took place at the Gödel Centennial conference in Vienna in 2006.
Comment: Haha... People tremble in the presence of greatness. That explains the shaking.
Comment: That's also the reason why the title says 'videos of good-quality lectures' and not 'good-quality videos of lectures'.
Comment: Nice. Both of our videos are excellent content, but shoddy camerawork--go figure.
Answer: Here is another video (high-quality video this time!):
Benoit Mandelbrot: Fractals and the art of roughness.
The title pretty much explains itself, I think. It is intended to explain fractals and chaos to the lay audience.


Moving MYSQL database Cache issue?

Question: I moved a mysql (myisam) database using rsync to aother server, I realized after doing this that I forgot to run 'flush tables' before moving the files so not all changes were written to disk I guess.
I did this out of hours but I was wondering how consistent the data will actually be after the move? Does mysql keep data in cache and also on disk or is everything that was in cache prior to the move lost?
Let me know if that doesnt make sense!
Thanks
Answer: To reliably copy database tables, the database has to be stopped (not just flushed). If it is not, a consistent copy is not guaranteed, but is it impossible to say if and what data might be lost.
That said, if the database was not active and some time passed since the last write operation before you started the copy, it's likely the cache has been committed to the disk and if MySQL doesn't complain about damaged files during startup, you might be lucky.

Moving MYSQL database Cache issue?


What are pros and cons of logrotate vs rotatelogs with Apache?

Question: Apache provides a tool called rotatelogs which has the benefit of not restarting apache when rotating logs which happens with logrotate.  I do not have enough experience to speak if this is enough criteria to use rotatelogs over logrotate.
My questions is does anyone have real life experience using either or of these two tools and what were your input would be?
What would you recommend and why?
Answer: I would recommend logrotate for most people since that is what will be rotating all the other logs (KISS: Keep it Simple Stupid).  Logrotate doesn't restart all of Apache, rather it just sends it a signal that tells it to reopen all of it's log files and restart children.  This signal can be SIGHUP, which causes the children to restart right away (which will interrupt downloads), or SIGUSR1, which does a graceful restart.  With SIGUSR1, you have to delay the log processing until you think all the children would have died naturally.  Either way, you probably want to analyze your logs, and time it for the lowest traffic period in the day or week.
Piped logs seems like it is the more powerful solution.  A big advantage being that it will allow you to use a centralized logging system and take load of the web server itself.  The manual itself says:

As with conditional logging, piped
  logs are a very powerful tool, but
  they should not be used where a
  simpler solution like off-line
  post-processing is available.

So apparently, don't use piped logging if you don't need it.  I have used piped loging in the past as a hacky way to filter logs, and had no problem.
Comment: The postrotate script with Apache's logrotate files is to send a SIGHUP, which causes Apache to terminate all children and restart.  Any active connections at the time are terminated.
Comment: I read a comment somewhere that said graceful restart does not work very well with servers carrying a heavy load.  But I really do not think there is much of an alternative.
Comment: logrotate with SIGHUP is pretty standard.  I wouldn't worry about it.
Answer: I've used both before. I found that using rotatelogs is a very useful tool in managing access logs and if you don't want apache downtime. On a high volume site I would recommend this, the only Issue I found was that if you want to manage the logs you will need to have a separate script cron'd to either clean up or move the logs to a backup server, obviously this depends on the requirement. With logrotate you do have more options with how logfiles are handled, the only issue is when logrotate runs as explained in the previous answer, you will need to restart apache.
Basically it all comes down to choice, if you need apache to running without interruptions then rotatelogs with a external cron script to manage, else logrotate will suffice. Just be sure to setup the logrotate cron not to rotate the logs when you have high traffic.
Lastly if you want to have apache log to your syslog you can always use the logger command which is on Redhat Based linuxes.


Prevent FONT Tag in execCommand

Question: How can I somehow "configure" in execCommand, so that I do not see the next element?
Font Tag

Well, the problem is that I am creating a simple editor for a project and I can not create the CSS correctly, I could do it with CSS, but that tag does not help me, is there any way to solve this?
The other problem is that I have no possibility to do something like this

    Lorem ipsum dolor sit amet.

    Lorem ipsum dolor sit amet.

Because it puts me like this

    Lorem ipsum dolor sit amet.

As I mentioned, it is an editor with execCommand and an IFRAME
Answer: Got the exact same problem and I solved it by removing font tags when I manage the list.
Just wrote something like that :
$("font").contents().unwrap();

Hope it can help you.

Prevent FONT Tag in execCommand


Docker Private Registry - Deleted all images, but still showing in catalog

Question: Following the official documentation (https://docs.docker.com/registry/spec/api/#deleting-an-image) I have been able to successfully delete an image. As expected, after deleting, the image can no longer be pulled nor its manifest called via API.
I feel like I've got the hard part done, however the problem is that the repo is still listed under /v2/_catalog after the deletion is finished. I'm trying to fully purge the registry.
Here is my registry compose file:
registry:
  image: registry:2.5.2
  container_name: registry-test
  ports:
    - 5007:5000
  environment:
    REGISTRY_STORAGE: s3
    REGISTRY_HTTP_TLS_CERTIFICATE: /etc/cert.crt
    REGISTRY_HTTP_TLS_KEY: /etc/cert.key
    REGISTRY_STORAGE_S3_ACCESSKEY: ******
    REGISTRY_STORAGE_S3_SECRETKEY: ******
    REGISTRY_STORAGE_S3_REGION: us-west-1
    REGISTRY_STORAGE_S3_BUCKET: ******
    REGISTRY_STORAGE_S3_SECURE: "true"
    REGISTRY_STORAGE_DELETE_ENABLED: "true"
  volumes:
    - /dockerdata/volumes/registry-test/etc/cert.crt:/etc/cert.crt
    - /dockerdata/volumes/registry-test/etc/cert.key:/etc/cert.key
  restart: unless-stopped

Here is the high-level method on what I did to delete the image:

Gather image digest:
HEAD https://myprivateregistry:5001/v2/myimage/manifests/mytag with "Accept: application/vnd.docker.distribution.manifest.v2+json" added to the header on the call
The call returns header key Docker-Content-Digest with a value such as sha256:b57z31xyz0f616e65f106b424f4ef29185fbd80833255d79dabc73b8eb873bd
Using that value from step 2, run the delete call: DELETE https://myprivateregistry:5001/v2/myimage/manifests/sha256:b57z31xyz0f616e65f106b424f4ef29185fbd80833255d79dabc73b8eb873bd
Registry API returns 202 Accepted
Run garbage collection manually: registry garbage-collect /etc/docker/registry/config.yml
Garbage collector deletes the associated blobs from disk (log omitted here, but it successfully deletes the blobs)

At this point I can confirm the blobs are completely deleted from disk and I can no longer call image details (like in step 1 above) so I thought I was done.
However, when running: /v2/_catalog my associated repo still lists (even though there are no images within it)! Obviously it cannot pull or be used, but how can I fully remove that repo from that list now that it has no images associated with it?

I don't see anywhere how to properly remove this on the API documentation page.
  Perhaps I'm missing it somewhere?

EDIT -
I wanted to add some more info on how the registry looks before and after the above deletion takes place.
Before the Delete Operation Above:
docker/registry/v2/repositories/myimage/_manifests/revisions/...
docker/registry/v2/repositories/myimage/_manifests/tags/...
docker/registry/v2/repositories/myimage/_layers/sha256/... (5 layers listed)
docker/registry/v2/blobs/sha256/...

After the Delete Operation Above:
docker/registry/v2/repositories/myimage/_layers/sha256/... (5 layers listed)

So the only thing left over is the _layers directory with the same 5x layers listed. This seems to be the reason why it's still listed on _catalog
When I delete the myimage folder (from docker/registry/v2/repositories/myimage) then the repository is no longer shown in the _catalog
This seems to be a method to purge it from the _catalog listing. However - what if an image has 2x tags, yet only 1 is deleted - is there a reason to delete anything from _layers in that case? How would that be handled with multiple versions of an image? Obviously I can't just clobber the _layers directory as the final method since, in the real world, there will be many tagged versions of an image. So this needs to be done intelligently.

I am simply finding it hard to find any documentation on the maintenance/upkeep of the Docker registry nor the schema for the _layers subdirectory and why the garbage collector doesn't clean up that directory the same it does with manifests and blobs.
Answer: After much research, there is no current method to remove the catalog entries fully via API only.

The v2 registry doesn't allow deleting only certain tags from an image

This means that the entire image is deleted. Deletion of tags is in an open PR for a future version of the Registry (https://github.com/docker/distribution/pull/2169)
What this means in regards to this question is that the proper method is to delete the image from the repo list is exactly as you assumed. Remove it from disk. (Such as rm -r v2/repositories/myimage where myimage is the image name that you deleted via API.)
It will then be removed from the repo list in _catalog and you're finished with your deletion process. There is no need to restart anything like another answer mentioned.
When the ability to delete specific tags from the registry is added, then this procedure will change. For now it's all or nothing.
Reference:
https://forums.docker.com/t/delete-repository-from-v2-private-registry/16767/5
https://github.com/docker/distribution/pull/2169
https://docs.docker.com/registry/spec/api/


Making chat server (Chat server's .NET service and Chat client's iOS applications) with Window service or WCF

Question: I want to build a chat server but i don't know i should use Window service or WCF? Numbers of client of my chat service not a lot, it's about 30 to 40 (Exactly, it's not a chat server, it just a server use to send/recieve data to/from client in local network). Should i use Window service or WCF?
Answer: WCF is your choice.


java.lang.ClassCastException while running new `runnableThread` in `Service` Class

Question: I have an application , contains a broadcastReceiver which listens to all new received SMS
. If any new SMS received this BroadcastReceiver starts a background Service which runs GPS and return the coordinates , this coordinate retrieving needs a new thread to be run , in the Service class there is no getApplicationContext() so I used 'getContentBase()' for starting the new thread this is the code
((Activity)getBaseContext()).runOnUiThread(new Runnable() {
                ((Activity)getBaseContext()).runOnUiThread(new Runnable() {

                        @Override
                    public void run() {
                        // TODO Auto-generated method stub

                        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                        LocationListener locationListener = new MyLocationListener();
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER, 5000, 10,
                                locationListener);
                    }
                }

and I am getting this exception
 E/AndroidRuntime(24700): java.lang.ClassCastException: android.app.ContextImpl cannot be cast to android.app.Activity

this is how the receiver defined in the manifest
    <receiver
        android:name=".BroadCastReceiver"
        android:exported="true" >
        <intent-filter android:priority="1000" >
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

and here is how the Service started in the BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    context.startService(new Intent(con,
            MyService.class));

    }

and the exception is at this line
                ((Activity)getBaseContext()).runOnUiThread(new Runnable()

I've searched a lot through the stack and the google as well , non of the answers solved my issue and tried to send the context from the BroadCastReceiver to the Service class , again there was the same Exception , any help??
Answer: First of all, Service extends ContextWrapper and is therefore a Context. If you need a reference to a Context you can simply reference your Service. You cannot cast a Service's base Context to an Activity.
If you want to work on the UI Thread from a Service, have a look at creating a Handler with Looper.getMainLooper().
...
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
            @Override
            public void run() {
                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                LocationListener locationListener = new MyLocationListener();

                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
            });
...

The Android documentation offers good information on communicating to the UI thread. Have a look here:
http://developer.android.com/training/multiple-threads/communicate-ui.html
Comment: thank youuuuuuuuuuuuuuuuu , you saved my life , you are an angle that god has sent you to me . I dont know how to express my happiness because you know , i will earn like 20000$ after fixing this error and finishing the app


Blues harmonica to start

Question: I want to start harmonica. I got some advice from a teacher who told me : "if you want to start harmonica you should start with Tremolo harmonica". But honestly I love blues harmonica.
is it right if I want to play blues harmonica the best way is to start with tremolo or I can start with Blues harmonica instantly ?
thanks
Answer: The Wiki article for tremolo claims it's the most popular style, especially in Europe and Asia.  Yet when I was researching harmonicas last year, most of the discussion I saw was for 10 hole diatonics, with chromatics a distant second.
On https://www.harptabs.com/ there are many more contributions for the diatonic than the tremolo.  Most of the tremolo tabs are from one poster.
http://www.harmonicaacademy.com/categories/20101027

The tremolo harmonica is different. No bending is required. In fact, bending is difficult with the double reeds, and rarely done.
The tremolo is therefore easier for tunes than the 10 hole, because note bending is not needed. All the notes are there. The tremolo is not so good for blues, as note bending is a big part of the blues harmonica sound.

Bending, if I recall correctly, was developed by blues players to produce notes that aren't normally played on the 20 reeds.
The first challenge for a beginning player is to blow or draw one note at a time.  With a wider separation, that is probably easier on the tremolo.  Bending is a more advanced skill, but essential to a blues sound.
Answer: I started on blues harp and never really went much past it. Not to say I didn't spend a lot of time learning and practicing harmonica. There's lots to be learned on the humble blues harp!
I really don't know why a tremolo harmonica would be any easier, but I've never played one.
If music is meant to be fun, then you'd better go for and fight for the thing you want to do because you think it will be fun.
Answer: If you want to start to play harmonica for blues, you must use a diatonic harmonica, specially in the key of C.
The key of C is used to start to play harmonica because this key is in mid-octave range, not too low tune and not too high tune.
To start to play harmonica, I recommend you use a hohner special 20...
Comment: False. You don't have to have a diatonic harp to play blues (although I agree that it helps a lot) and you **definitely** don't have to start in the key of C. I'm pretty sure my first blues harp was in G, and then I picked up a Bb harp. In fact, of my five blues harps I'm pretty sure *none* are in the key of C.
Comment: I've seen a seems-to-know-his-stuff guy on YouTube say that for blues you need a harmonica that's offset 4 steps from the rythm - e.g. for a blues in G, you'll want t harp in C. If the blues rythm is in another key your C harp will sound off. If you're playing by yourself / on your own, the key makes no difference.

Blues harmonica to start


When was the last time a kicker was released after making two 60+ yard field goals during the season?

Question: In 2019, Brett Maher made a 62 and 63 yard field goals during the season. However, he was released on 9 Dec 2019.
When was the last time a kicker was released after making two (or more) 60+ yard field goals during the season? Please state the kicker's name, team, yards of field goals he made over 60 yards, and his date of release.
Answer:  is an image of the data you request.  The rest is left as an exercise to the reader.
It would seem I cannot view this by clicking.
This information is readily available at Football Reference dot com.
additional info: only three kickers have made more than 1 60+ yard FG in their career.
Maher has made 3 (two this season), Greg Zuerlein has made 2 (three seasons apart), and Sebastian Janikowski has made 2 (two seasons apart).
In other words, it has never happened otherwise.


c# struct with no reference types

Question: Consider a struct which does not contain any reference fields (only basic types and other structs).
Consider this struct will be used in collections and I want it to behave like a value type (ie int).

do I need to override operator== and operator!=?
do I need to override Equals?
do I need a copy constructor?
do I need to worry about assignment?
do I need to override GetHashCode?
Answer:
Depends on you, by default == and != will redirect to the default Equals implementation but it's considered better practice to use Equals directly instead of == or !=
You should, by default Equals performs bitwise comparison on value types and reference equality on reference types, so if your struct contains fields that are reference types, you will need to override Equals to perform a proper comparison on them. Besides that, MSDN recommends to override Equals anyway, for performance benefits as well.

Particularly if your value type contains fields that are reference
  types, you should override the Equals(Object) method. This can improve
  performance and enable you to more closely represent the meaning of
  equality for the type.

Structs are copied by default when passed between variables/methods, so there is no need to write a copy constructor. The only case I can think of is if your structs contains fields that are reference types and you want to create a copy constructor that performs deep copy on them, up to you.
What do you mean worry about assignment?
Yes. If you're going to use your struct as a member of HashSet or as a key in a Dictionary, you would want to provide a custom implementation of GetHashCode.

It is best to implement IEquatable to avoid boxing (default Equals accepts an object type, so your struct will have to undergo boxing to fit that type).
Collections (Arrays, Dictionaries, etc...) will usually check if their members implement IEquatable, and will use IEquatable.Equals, so it's best to implement it.
It is also recommended to implement the default Equals (from System.Object) and direct to to the IEquatable.Equals implementation.
Example:
<code>struct MyStruct : IEquatable<MyStruct>
{
    public int A { get; set; }

    public int B { get; set; }

    public bool Equals(MyStruct other)
    {
        return A == other.A && B == other.B;
    }

    public override bool Equals(object obj)
    {
        if (!(obj is MyStruct)) return false;
        return ((MyStruct)obj).Equals(this);
    }

    public override int GetHashCode()
    {
        return (A, B).GetHashCode();
    }
}
</code>
I also provided an example of how to implement GetHashCode, best way is to use the implementation of Tuple.
Again, implementing == and != is up to you
The standard library (System, System.Collections, etc...) uses System.Equals or IEquatable.Equals to do comparison, and you should too.
So no, implementing == and != is not necessary.
Comment: My question _particularly_ asks about the case where no reference types are included. Please edit your answer accordingly
Comment: @kofifus Sorry, didn't catch if at first. If there are no reference types, my answer still holds, I just elaborated more on cases where you do have references types in the struct. I still advise to provide your own implementation of Equals, it would prove useful if you every change something - add reference types, would like to ignore a certain field.
Comment: so I can do without ==, != and Equals in this case ?
Comment: @kofifus Yes, Equals is enough, methods that act on members/keys of arrays/dictionaries call to .Equals for comparison, they don't use the == and != operators. I forgot to mention it but it's also best to implement IEquatable because then you can avoid the unboxing (allocating the struct to memory) that happens when you call the default Equals(object)
Comment: I don't understand, what happens if I don't override ==, != and Equals ?

c# struct with no reference types


Imagem está sendo cortada quando o elemento CSS "max-width" é usado

Question: No rodapé deste site Wordpress há várias imagens de logotipo.

Estas imagens são inseridas pelo próprio usuário administrador do site
  dentro de uma tabela Pods, portanto eu não tenho controle individual
  para cada imagem, apenas preciso aplicar um padrão para todas as
  imagens.

As dimensões originais das imagens são muito diferentes, então eu preciso restringir seus tamanhos usando max-width e max-height, os quais eu coloquei na classe wp-image-490:

Mas ao fazer isso, se eu reduzo o tamanho da tela (para testar a responsividade), a primeira imagem está sendo cortada:

E ao mesmo tempo, tentei corrigir isto inserindo width: 100% nesta mesma classe, mas ao fazer isso, a segunda imagem fica distorcida:

Alguém poderia ajudar?
Comment: Coloca na tag da imagem object-fit: contain e object-position: 50% 50%; se resolver me fala que posto como resposta :)
Comment: Cara, tu é fera mesmo hein! Apenas inserindo "object-fit: contain" junto com o atual "width: 100%" já resolveu o problema. Pode colocar isso como resposta. Obrigado!
Comment: Tá respondido, valeu a força :)
Answer: Então, esses problemas vc pode contorna limitando a imagem dentro do próprio container de renderização usando object-fit: contain. O que quero dize é que a imagem vai renderiza de forma que caiba proporcionalmente dentro do width e height que vc determinou.
Essa documentação vai te ajudar: https://developer.mozilla.org/pt-BR/docs/Web/CSS/object-fit
E essa imagem vai ajudar vc a entender melhor


How to use drush with a specific PHP Instance

Question: What drush command can I use to tell drush to use php 5.6 instead of 7.1 which my  site is currently running on.
A million thanks in anticipation.
Answer: Drush is just a PHP script at heart so all you need is this:
<code>/path/to/my/php /path/to/my/drush  ...
</code>
Comment: Thanks @Alfred. Though I did not really know how you wanted the path implemented. However, I must admit that my question was also vague without stating the environment I am working in. My project is to build the open social using IIS7 and a MySQL server57. I installed composer in windows 10 and thereafter installed the cgr tool which I used to install Drush. Somehow, cgr was no longer in my system. Drush stopped working  after I made php5.6 the default php using the System path. I have had to uninstall drush and  I am reinstalling evreything to get a better environment. Thanks for the help
Comment: Thanks @ Alfred and leymannx. I was able to make some progress with both answers even though my problem arose from an ill configured environment which I am addressing and after that if I should be able to ask the right question that needs to be asked to sort the malfunction in my open social project


Definition of real projective line

Question: On  $\mathbb R^2-(0,0)$ we define the following equivalence relation:
Two points $(x,y)$ and $(x_0,y_0)$ in $\mathbb R^2-(0,0)$ are equivalent if there exists $a\in \mathbb R^*$ such that
$$x=ax_0,\; y=ay_0$$
Let $D_{x_0y_0}$ be the line passing through the points $(0,0)$ and $(x_0,y_0)$.
Then the equivalence class of $(x_0,y_0)\in \mathbb R^2-(0,0)$ is the set $D_{x_0y_0}-(0,0)$.
My question: I read that $\mathbb RP^1$ is the set of equivalence classes of points $(x,y)\in \mathbb R^2-(0,0)$ and this we just showed is the set of subsets $D_{xy}-(0,0)$. My question is why we say that  $\mathbb RP^1$ is the set of lines $D_{xy}$ through the origin instead of saying the set of subsets $D_{xy}-(0,0)$ ?
Answer: There are many definition of $\mathbb{R}P^1$.
The definition you gave above is not the one where $\mathbb{R}P^1$ is the set of lines through the origin. The definition you provide above defined $\mathbb{R}P^1$ as the set of equivalence classes of $\mathbb{R}^2 - \{(0,0)\}$ under the equivalence relation you wrote.
However, your definition and the line-through-origin definition are the same in a very geometric sense. Let $\mathbb{R}P^1$ denote your eqivalence relation definition. Let $L$ denote the line through the origin definition. Let $\Phi : \mathbb{R}P^1 \rightarrow L$ be defined by $[x] \mapsto \mathbb{R} x$, where $\mathbb{R}[x] = \{\alpha x : \alpha \in \mathbb{R}\}$. It is easy to check that $\Phi$ is well-defined and a bijection.
So the equivalence class definition and the lines through the origin definition are equivalent by a bijection. (In fact if you put some topological structure on the two spaces you even get bijection preserving structure.)
However you are correct, the definition you provided, equivalence classes are not lines. But up to various structure preserving bijection, the two definitions are the same.
Comment: Dear William, i'm not sure i'm following : in the first paragraph you say they are not the same and in the second you say that they are the same in a very geometric sense!!! I'm confused
Answer: Your definition actually gives $\mathbb{R}P^1 \cup \{ (0,0) \}$, where $(0,0) \notin \mathbb{R}P^1$ but $(0,0)$ cannot be separated from the points of $\mathbb{R}P^1$.  Every open set containing $(0,0)$ contains points in common with every line $D_{x_0y_0}$.  This "bad behavior" of the point $(0,0)$ is not desirable (it makes the space non-Hausdorff) and so we typically throw out the origin when defining projective spaces in the way you mentioned (equivalence classes of points under scalar multiplication).
To answer your question about "lines".  Well we don't include $(0,0)$ as one of the lines because it isn't a line!  Think of each line as a mathematical object (not as a set of points).  Then it doesn't so much matter that $(0,0)$ is contained in each line.  What matters is that each line is basically regarded as a point in $\mathbb{R}P^1$.
Hope this helps!
Comment: I edited my question so that my problem would be clearer. Thank you!!

Definition of real projective line


Modal / script não aparece a box. e

Question: Alguém poderia me ajudar o que falta pro meu modal da certo?
Só falta a css ou falta algo no codigo?
code:
    <!doctype html>

<meta charset="utf-8">
<title>Documento sem título</title>

ATENÇÃO

1212312312412563463463463473473451351.

                <button class="btn btn-danger i-refuse">SAIR DO SITE</button>
                <button class="btn btn-success i-agree">ESTOU CIENTE E CONCORDO</button>

Comment: posso te mostrar um exemplo de como criar modais utilizando bootstrap?
Comment: pode sim irmão logico.
Comment: Mas eu queria um desse jeito q o fundo do site apareça.
Answer: Um exemplo de modal funcional:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

    <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
      Exemplo
    </button>

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

           // Felipe aqui você irá colocar os códigos html que vão preencher o corpo do seu modal

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>

Para o css utilizei o bootstrap pois ja contem classes prontas, mas você pode usar qualquer outra classe para stilos.

Com esse modal o fundo do seu site vai aparecer

Modal / script não aparece a box. e


Why are some CKEditor configurations working and not others?

Question: I am using CKEditor 4 in Drupal 7 using the CKEditor module. I have the following configuration at /admin/config/content/ckeditor/edit/[profile]:
config.stylesCombo_stylesSet = 'my_styles:/sites/all/libraries/ckeditor-styles.js';
config.stylesSet = 'my_styles:/sites/all/libraries/ckeditor-styles.js';
config.fillEmptyBlocks = false; // Prevent filler nodes
config.language_list = [ "en:English", "es:Spanish", "zh:Chinese", "ar:Arabic:rtl", "fil:Filipino", "fr:French", "ja:Japanese", "ko:Korean", "ru:Russian", "th:Thai", "vi:Vietnamese" ];
CKEDITOR.on('instanceReady', function(ev) {
  ev.editor.on('paste', function(evt) {
    evt.data.dataValue = evt.data.dataValue.replace(/ /g,' ');
     evt.data.dataValue = evt.data.dataValue.replace(/
 *<\/p>/g,'');
    console.log(evt.data.dataValue);
  }, null, null, 9);
});

The fillEmptyBlocks configuration is working. Extra returns are removed on save and on paste from Word.
However, the dropdown for the language icon only contains the CKEditor default of Arabic, French, and Spanish, not the list of 11 languages that I've supplied.
And pasting A[tab]B[tab]C[tab]D[tab]E from Word, which converts the tabs to a series of non-breaking spaces, retains the non-breaking spaces.
Any ideas why these configurations are being overlooked and how to make them work?
Comment: Please make your title more specific so that your post attracts people who know the CKEditor module.
Answer: There was an error in my code. The config statments needed to be surrounded by:
CKEDITOR.editorConfig = function(config) {

and
}

which I discovered by looking at ckeditor.config.js in the CKEditor module.


Como mudar a cor da seleção de texto no VS Code?

Question: Na imagem, o texto selecionado está com a cor preta, eu quero colocar uma cor mais clara.
Comment: @Costamilam jovem tem como mudar sim, está na própria especificação do VS Code, depois se te interessar da uma olhada nessa lista. https://code.visualstudio.com/api/references/theme-color#editor-colors Normalmente tudo que começa com `editor.` é referente a área onde digitamos o código.
Comment: Mude o tema para um que te agrade. Acho que não tem como mudar só uma cor, talvez com alguma extensão
Answer: Vc pode customizar isso entrando nos seus Setting e colocando isso
"editor.selectionBackground": "#666",
"editor.selectionHighlightBackground": "#666",

#666 é a cor, vc pode testar uma cor mais clara que te agrade...

Vc entra nas Configs aqui