text:
Q: Como esconder um texto sendo ele maior que minha Div O objetivo do exercício esta voltado para estudo , estou criando um blog que possui matérias sobre dublagem e um dos objetivos é esconder o texto, que é bem maior que minha Div, assim ao clicar no post a pessoa seja redirecionada a uma página com a matéria completa.
Código HTML
    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>dublaBlog</title>
    <link rel="stylesheet" href="css/folhaDeEstilos.css">

dublaBlog

Home

Anime

Cartoons

Filmes

Entrevista com Wendel Bezerra

            Postado por Rafael Boeno

Maecenas in placerat urna. Proin velit ipsum, imperdiet sit amet lorem id, malesuada pellentesque
                        risus. Duis porttitor justo sit amet malesuada varius. Nulla dignissim eros nec lectus suscipit
                        imperdiet. Vivamus tristique quis odio sed tempor. Sed pulvinar, urna a tempor sodales, purus m
                        etus mollis lectus, in congue enim nisl ut dui. Suspendisse interdum urna nec elit tincidunt por
                        ta. Duis venenatis risus in semper sodales. Praesent feugiat rutrum fermentum. Nullam luctus aug
                        ue sit amet ultrices cursus. Curabitur tristique ex at ante pharetra, quis scelerisque eros rutr
                        um. Donec commodo nibh ligula, ut elementum risus ullamcorper quis. Nunc ut nunc sem. Mauris ut
                        varius lorem, a tempor nibh. Donec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis
                        rhoncus lorem orciDonec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis dois tres
                        rhoncus lorem orc Donec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis teste um
                        rhoncus lorem orc.
                        Maecenas in placerat urna. Proin velit ipsum, imperdiet sit amet lorem id, malesuada pellentesque
                        risus. Duis porttitor justo sit amet malesuada varius. Nulla dignissim eros nec lectus suscipit
                        imperdiet. Vivamus tristique quis odio sed tempor. Sed pulvinar, urna a tempor sodales, purus m
                        etus mollis lectus, in congue enim nisl ut dui. Suspendisse interdum urna nec elit tincidunt por
                        ta. Duis venenatis risus in semper sodales. Praesent feugiat rutrum fermentum. Nullam luctus aug
                        ue sit amet ultrices cursus. Curabitur tristique ex at ante pharetra, quis scelerisque eros rutr
                        um. Donec commodo nibh ligula, ut elementum risus ullamcorper quis. Nunc ut nunc sem. Mauris ut
                        varius lorem, a tempor nibh. Donec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis
                        rhoncus lorem orciDonec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis dois tres
                        rhoncus lorem orc Donec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis teste um
                        rhoncus lorem orc.

Folha de Estilo CSS3
body{
    background-color: #CCC5CD;
}

header{
    background-color: white;
    width: auto;
    height: 50px;
    margin: auto 200px;
    border-bottom:  1px solid;
}
a{
    text-decoration: none;
    color: inherit;
}

header h1{
    display: inline;
    position: absolute;
    margin-left: 20px;
    width: 141px;
    margin-top: 7px;
}

nav.menuDaPagina{
    float: right;
    position: relative;
}

ul.listaMenu{
    position: relative;
    list-style: none;
}

li.itemMenu{
    position: relative;
    display: inline-block;
    padding: 7px;
    margin-top: -15px;
    margin-right: 30px;
}

li:hover{
    background-color: red;
    color: white;
    padding: 15px;
}

article{
    margin: auto 200px;
    padding-top: 10px;
}

section.postagem{
    width: 600px;
    height: 275px;
    background-color: white;
    position: relative;
}

section h4{
    display: inline;
}

figure{
    margin: 0px;
}

figure img{
    float: left;
    margin-right: 5px;
    margin-bottom: 5px;
}

figcaption p{
    text-align: justify;
    overflow: inherit;
    text-overflow: ellipsis;
}

A: Você pode colocar ... ao final do texto usando text-overflow: ellipsis;.
Exemplo:

div {
  width: 150px;
  height: 50px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco

A: Uma solução é mudar os estilos do
 e section.postagem. Setar no primeiro um overflow: hidden; e um height fixo; e no segundo apenas um overflow: hidden;. Isso irá delimitar o conteúdo interno à área do elemento. O que ultrapassar essa área não será visível.

text-overflow: ellipsis; neste seu caso não funciona porque o texto
  tem múltiplas linhas.

Veja funcionando:

 <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>dublaBlog</title>

dublaBlog

Home

Anime

Cartoons

Filmes

Entrevista com Wendel Bezerra

            Postado por Rafael Boeno

Maecenas in placerat urna. Proin velit ipsum, imperdiet sit amet lorem id, malesuada pellentesque
                        risus. Duis porttitor justo sit amet malesuada varius. Nulla dignissim eros nec lectus suscipit
                        imperdiet. Vivamus tristique quis odio sed tempor. Sed pulvinar, urna a tempor sodales, purus m
                        etus mollis lectus, in congue enim nisl ut dui. Suspendisse interdum urna nec elit tincidunt por
                        ta. Duis venenatis risus in semper sodales. Praesent feugiat rutrum fermentum. Nullam luctus aug
                        ue sit amet ultrices cursus. Curabitur tristique ex at ante pharetra, quis scelerisque eros rutr
                        um. Donec commodo nibh ligula, ut elementum risus ullamcorper quis. Nunc ut nunc sem. Mauris ut
                        varius lorem, a tempor nibh. Donec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis
                        rhoncus lorem orciDonec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis dois tres
                        rhoncus lorem orc Donec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis teste um
                        rhoncus lorem orc.
                        Maecenas in placerat urna. Proin velit ipsum, imperdiet sit amet lorem id, malesuada pellentesque
                        risus. Duis porttitor justo sit amet malesuada varius. Nulla dignissim eros nec lectus suscipit
                        imperdiet. Vivamus tristique quis odio sed tempor. Sed pulvinar, urna a tempor sodales, purus m
                        etus mollis lectus, in congue enim nisl ut dui. Suspendisse interdum urna nec elit tincidunt por
                        ta. Duis venenatis risus in semper sodales. Praesent feugiat rutrum fermentum. Nullam luctus aug
                        ue sit amet ultrices cursus. Curabitur tristique ex at ante pharetra, quis scelerisque eros rutr
                        um. Donec commodo nibh ligula, ut elementum risus ullamcorper quis. Nunc ut nunc sem. Mauris ut
                        varius lorem, a tempor nibh. Donec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis
                        rhoncus lorem orciDonec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis dois tres
                        rhoncus lorem orc Donec iaculis aliquet est, vitae feugiat turpis porttitor vel. Duis teste um
                        rhoncus lorem orc.

A: Usar text-overflow: ellipsis; e white-space: nowrap; vai limitar o seu texto a apenas uma linha.
Para múltiplas linhas não vai funcionar. Se vc quiser osar os 3 pontinhos em textos com mais de uma linha veja como fazer.
Modelo com o Ellipsis para dentro do TextBox. (essa opção pode depender de ajuste fino no Padding para ficar ao seu gosto e não cortar um caractere no meio por exemplo)

/* Modelo da caixa de texto */
.block-with-text {
    overflow: hidden;
    position: relative;
    line-height: 1.2em;
    max-height: 6em; /* aqui vc controla a altura da caixa de texto */
    text-align: justify;
}
.block-with-text:before {
    content: '...';
    position: absolute;
    right: 0px;
    bottom: 0;
    background-color: #ffffff;
    padding: 0 0px 0 0.25em;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Possimus, veniam! Officiis assumenda iusto ad corrupti fuga nobis earum laborum alias quam rerum quae molestias ipsum soluta eveniet quos ut illo necessitatibus unde quidem consequatur dolorem, nemo minus! Fugiat, asperiores vel. Possimus rerum enim facilis aspernatur iure doloribus ut commodi cumque nam omnis porro quibusdam voluptatibus, alias eum! Hic modi provident assumenda mollitia sunt non culpa, sapiente est officia a, quis illum quos nesciunt. Enim aliquid eaque a adipisci ullam, minus dolor accusantium corrupti dolore soluta voluptate ipsa harum pariatur vel ut cupiditate dolorem velit ab ex ratione est assumenda ipsum!

Opção com o Ellipsis para fora da caixa do texto. Assim não vai cortar caractere.

html, body {
    width: 70%;
    height: 100%;
    margin: 0 auto;
}
/* Modelo da caixa de texto */
.block-with-text {
  overflow: hidden;
  position: relative;
  line-height: 1.2em;
  max-height: 6em; /* aqui vc controla a altura da caixa de texto */
  text-align: justify;
  margin-right: -1em;
  padding-right: 1em;
}
.block-with-text:before {
  content: '...';
  position: absolute;
  right: 0;
  bottom: 0;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Possimus, veniam! Officiis assumenda iusto ad corrupti fuga nobis earum laborum alias quam rerum quae molestias ipsum soluta eveniet quos ut illo necessitatibus unde quidem consequatur dolorem, nemo minus! Fugiat, asperiores vel. Possimus rerum enim facilis aspernatur iure doloribus ut commodi cumque nam omnis porro quibusdam voluptatibus, alias eum! Hic modi provident assumenda mollitia sunt non culpa, sapiente est officia a, quis illum quos nesciunt. Enim aliquid eaque a adipisci ullam, minus dolor accusantium corrupti dolore soluta voluptate ipsa harum pariatur vel ut cupiditate dolorem velit ab ex ratione est assumenda ipsum!


text:
Q: Change the reference in a Java List I somehow feel stupid to ask this question, BUT
Why is it not possible to change the reference to an object in a List by hand using the EnhancedForStatement?
private static List<String> list = new ArrayList<String>();

public static void main(String[] args) {
    list.add("AAA");
    list.add("BBB");
    list.add("CCC");

    for(String s : list){
        if(s.equals("BBB")) s = "QQQ";
    }

    System.out.println(list);
}

Will print [AAA, BBB, CCC] because the reference to the second element wasn't changed, as one could expect.
But why am I not allowed (or is List the wrong type?) to manually change the reference of the list entry? String in this example could be any complex type, this question is about the changing of references in a List.
edit: OK, maybe it is clear why it works the way it works, but how can I accomplish the reference change? I can't believe there is no way for any subtype of List to change the reference of any element.
edit2: so it is not possible to change the reference when using the EnhancedForStatement?

A: s is a String variable, and assigning to it doesn't affect the list.
In order to change the list, call list.set(1,"QQQ");, which would put a new String as the second element of the list.

A: Let's dig a bit into how the enhanced for loop works on the background.
for (String s : list) { .. }

is actually translated to:
for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
    String s = iter.next();
    ..
    s = "QQQ";
}

As you can see, passing a new reference to the s variable, just changes it for the scope of the loop, which doesn't have any effect on the list entry.
If you need to modify the current element that's being handled by the iterator, working with ListIterator makes it very easy:
for (ListIterator<String> iter = list.listIterator(); iter.hasNext();) {
    String s = iter.next();
    ..
    iter.set("QQQ");
}

Note that before iter.set(...), we need to call iter.next().

A: You could make a temporary list.
private static List<String> list = new ArrayList<String>();

public static void main(String[] args) {
    list.add("AAA");
    list.add("BBB");
    list.add("CCC");

    List<String> templist = new ArrayList<String>();

    for(String s : list){
       if(s.equals("BBB")) s = "QQQ";

       templist.add(s);
    }
    list = templist;

    System.out.println(list);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting null values from include('1.php?id='.$id) file, PHP included a php file for inserting values into table. script inserting values but all null.
if(isset($_GET['id']))
{
$id=$_GET['id'];
include_once ('1.php?id='.$id);

$sql = "insert into table ( ... ) values (variables from 1.php?id='.$id)";

insert query is fine but submitting null values.. what is wrong ?

A: You can't pass variables to files while including like query strings. If the variables are set then they will already be available on those files you are including after that. Do -
if(isset($_GET['id']))
{
$id=$_GET['id'];
include_once ('1.php');

$sql = "insert into table ( name ) values ('$name')";

1.php
Something like -
if(!empty($id)) { // Check if the variable is present
    // Genarate the variables
    $name = 'xyz';
}

A: Please consider the following code snippet:
if(!empty($_GET['id'])) {
    $id = mysql_real_escape_string($_GET['id']);
    include_once("1.php?id={$id}");
    $sql = "INSRET INTO your_table (your_columns)  VALUES (variables from 1.php?id={$id})";
    mysql_query($sql);
}


text:
Q: R - Repeating function to multiple "anchor points" Sorry if this is a poorly phrased question, I'm confused on the best way to organize my data in R. Here is the data frame:
 Experiment Treatment              Inhibitor      pAKT Loading Control
          1      None                   DMSO  7075.426       16051.376
          1 Carbachol                   DMSO 18368.962       14826.962
          1 Carbachol          10-8 M BYL179 14949.184       10911.477
          1 Carbachol          10-7 M BYL179 11972.477       10993.305
          1 Carbachol          10-6 M BYL179 14874.841       12610.841
          1 Carbachol          10-8 M Cal101 11433.598       12305.891
          1 Carbachol          10-7 M Cal101 10297.719       13175.012
          1 Carbachol          10-6 M Cal101  2835.891       11609.598
          1 Carbachol 10-8 M BYL179 + Cal101  8749.134       12024.012
          1 Carbachol 10-7 M BYL179 + Cal101  4490.841       13088.598
          1 Carbachol 10-6 M BYL179 + Cal101   598.012       10929.134
          2      None                   DMSO 11904.225       30755.104
          2 Carbachol                   DMSO 27637.518       27536.912
          2 Carbachol          10-8 M BYL179 13970.619       24052.326
          2 Carbachol          10-7 M BYL179  7567.326       21889.154
          2 Carbachol          10-6 M BYL179  8421.326       13446.033
          2 Carbachol          10-8 M Cal101  4754.497        7333.912
          2 Carbachol          10-7 M Cal101  3614.497        3566.376
          2 Carbachol          10-6 M Cal101  1426.598        1331.326
          2 Carbachol 10-8 M BYL179 + Cal101  7401.175        6010.447
          2 Carbachol 10-7 M BYL179 + Cal101  3159.740        5280.154
          2 Carbachol 10-6 M BYL179 + Cal101  2114.376        9793.347
          3      None                   DMSO  4528.690       20969.347
          3 Carbachol                   DMSO 27218.104       23433.912
          3 Carbachol          10-8 M BYL179 12507.619       21712.033
          3 Carbachol          10-7 M BYL179  4673.790       13934.154
          3 Carbachol          10-6 M BYL179  6699.033        8018.497
          3 Carbachol          10-8 M Cal101 10108.861       17364.861
          3 Carbachol          10-7 M Cal101 10728.326       25307.447
          3 Carbachol          10-6 M Cal101  7418.083       20826.012
          3 Carbachol 10-8 M BYL179 + Cal101 17169.104       23850.255
          3 Carbachol 10-7 M BYL179 + Cal101 14890.811       36585.368
          3 Carbachol 10-6 M BYL179 + Cal101  5889.497       19609.033
          4      None                   DMSO  5029.841       14217.083
          4       EGF                   DMSO 17963.719       16883.255
          4       EGF          10-8 M BYL179 18191.719       15706.719
          4       EGF          10-7 M BYL179 17430.719       16327.891
          4       EGF          10-6 M BYL179 15350.305       14828.134
          4       EGF          10-8 M Cal101 15847.891       14122.598
          4       EGF          10-7 M Cal101 17678.426       16659.719
          4       EGF          10-6 M Cal101 14236.477       15380.012
          4       EGF 10-8 M BYL179 + Cal101 14281.891       15367.012
          4       EGF 10-7 M BYL179 + Cal101 13918.012       13796.062
          4       EGF 10-6 M BYL179 + Cal101  4702.062       12578.012
          5      None                   DMSO 14192.004       40446.196
          5       EGF                   DMSO 43425.246       46626.125
          5       EGF          10-8 M BYL179 43465.004       45206.832
          5       EGF          10-7 M BYL179 34098.882       36853.175
          5       EGF          10-6 M BYL179 33415.882       37637.539
          5       EGF          10-8 M Cal101 32413.175       31047.054
          5       EGF          10-7 M Cal101 32359.882       35967.004
          5       EGF          10-6 M Cal101 27089.761       33929.125
          5       EGF 10-8 M BYL179 + Cal101 30945.882       29804.882
          5       EGF 10-7 M BYL179 + Cal101 32511.711       37228.832
          5       EGF 10-6 M BYL179 + Cal101 10176.832       36218.024
          6      None                   DMSO 17417.004       47193.439
          6       EGF                   DMSO 49204.075       55932.489
          6       EGF          10-8 M BYL179 45682.832       52486.125
          6       EGF          10-7 M BYL179 37131.711       41015.004
          6       EGF          10-6 M BYL179 32859.761       33375.933
          6       EGF          10-8 M Cal101 39127.711       33037.004
          6       EGF          10-7 M Cal101 35535.589       33514.539
          6       EGF          10-6 M Cal101 25455.175       28547.882
          6       EGF 10-8 M BYL179 + Cal101 21374.589       24441.296
          6       EGF 10-7 M BYL179 + Cal101 19590.125       22268.660
          6       EGF 10-6 M BYL179 + Cal101  5347.782       21943.317

I want to create a new column titled "Correction Factor", generated by dividing the Loading Control value for a specific entry by the entry with Treatment "None" and Inhibitor "DMSO" for that experiment. So for example the first entry for Experiment 1 would be 16051.376/16051.376 = 1, the second would be 14826.962/16051.376 = 0.9237, the third would be 10911.477/16051.376 = 0.6798, and so on. For Experiment 2 I would divide by the Experiment 2 None + DMSO entry, 30755.104. How do I repeat this action for every experiment?

A: While this can certainly be done in base R, Hadley Wickham's tools provide a nice way to do this (split data frame by some criterion, apply a transformation on the subsets, and stick them back together - "split-apply-combine" for short).
(These are untested but I think they should work ...)
library(plyr)
library(dplyr) ## load dplyr *second!*

plyr (Hadleyverse/tidyverse 1)
ddply(my_data,"Experiment",
     mutate,
         Correction.Factor=Loading.Control/
           Loading.Control[Treatment=="None" & Inhibitor=="DMSO"])

dplyr (Hadleyverse/tidyverse 2)
my_data %>% group_by(Experiment) %>%
     mutate(Correction.Factor=Loading.Control/
           Loading.Control[Treatment=="None" & Inhibitor=="DMSO"])

Another (base-R-friendly) approach would be to subset out the baseline (None/DMSO) cases, retain only the Experiment and Loading.Control columns (but renaming the latter),  and then merge the result back with the original data set - then all you have to do is divide one column by another ...


text:
Q: Visual C++ 2010 Redistributable not found when attempting to install MySQL-python via pip I have Microsoft Visual C++ 2010 x(86|64) Redistributable - 10.0.40219 yet while I'm trying to install the Pip package MySQL-python via Visual Studio 2015 Community, I come up with the error error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat). Am I missing something?

A: I'd say you've not got the appropriate path variable for vc set, so your python is trying to call vcvarsall.bat, but can't find such an animal.  Have a look at Cannot find vcvarsall.bat when running a Python script for this exact same question (and some answers).


text:
Q: removing the extra space when setting the height of xap object in aspx page I am hosting the silverlight xap object in aspx page. The aspx page contains two <div>.
In the first <div> i am having the html menu and in the second <div> i am having the xap. I gave height=95%; for xap object, so that the content is occupying the exact browser space but the scroll bar appears with height of some 30px more area(html area) at bottom region. How to remove the scroll bar and the extra area?
Thanx in advance

A: You need the <html> tag to have the style "height:100%;overflow:hidden" and the <body> tag to have the style "height:100%;overflow:hidden;margin:0px".  This assumes your two divs a direct children of the body.  The <object> tag of the silverlight plugin should have height:100% as well.
The two divs should have height 5% and 95% respectively and both ought to have overflow:hidden as well.


text:
Q: Deduce that $\Gamma(p)^{1/p}$ diverges as $p\rightarrow +\infty$. I was able to prove that if $f\in \bigcap_{p\ge 1}\textit{L}^p([0,1]) \setminus \textit{L}^{\infty}([0,1])$, then $||f||_p$ diverges as a function of $p$, said better: if we set $F(P):=||f||_p \longrightarrow +\infty$ as $p\rightarrow +\infty$.
Somebody suggested me that a nice application of this is: deduce that $\Gamma(p)^{1/p}$ diverges as $p\rightarrow +\infty$. Just to make it easyer if someone isnt sure about it, recall:
$$\Gamma(p)=\int_0^{+\infty}x^{p-1}e^{-x}dx \mbox{, when }p>0\mbox.$$
My attempt consisted in making substitutions to make sure we are on $[0,1]$ with the Gamma integral, and such that i could than overestimate the integral with the integral of a function $g$ in the set mentioned at the beninning so that the proof would finish with something like this:
$$\Gamma(P)^{1/p}\ge ||g||_p \longrightarrow \infty \mbox{, as } p\rightarrow +\infty\mbox,$$
thanks to the "lemma" at the beginning.
I'm hoping someone could give me some insight on what i could do better.


text:
Q: manipulate a StringBuilder in a StringBuilder array in java So I have this piece of code:
StringBuilder[] a = new StringBuilder[5];
        Arrays.fill(a, new StringBuilder("asdfg"));
        a[0].deleteCharAt(0);
        for (StringBuilder s : a) {
            System.out.println(s);
        }

and the output
sdfg
sdfg
sdfg
sdfg
sdfg

It seems that all element in the array is a reference to the same StringBuilder object, I guess it because of Arrays.fill(). Why does this happen and how can I fix this ?
p.s: I don't want to use a loop because fill() only behaves differently with StringBuilder[] and I want to understand why.

A: The behaviour you see is expected.
Quoting the javadoc of Arrays.fill():

Assigns the specified Object reference to each element of the specified array of Objects.

Emphasis mine.
The reference here is val in the prototype (recall: public static void fill(Object[] a, Object val), which is your new StringBuilder("asdfg").
If you want to fill each element of the array with different elements, you need to cycle through the array indices and fill with a new object each time. For instance (using Java 8):
IntStream.range(O, a.length).foreach(index -> a[index] = new StringBuilder("asdfg"));

As a side note, you could have used an IntStream directly to build your array, although I'm not sure the code is really legible. Stream API abuse warning!
final StringBuilder[] a = IntStream.range(0, 5)
    .mapToObj(ignored -> new StringBuilder("asdfg"))
    .toArray(StringBuilder[]::new);

A: From the API, Arrays.fill...

Assigns the specified Object reference to each element of the specified array of Objects.

So yes, it is the same reference, and unfortunately you will need some form of iteration to assign a different StringBuilder to all elements.

A: I'm sure the reason for saying "fill() only behaves differently with StringBuidler[]" is because you've only tried with other immutable objects, and StringBuilder is not. Try
List<String> list[] = new List[5];
Arrays.fill(list, new ArrayList<String>());
list[0].add("hello");
for (List l : list) {
    System.out.println(l);
}

Immutable means that calling methods on an instance will not change it's state (like in StringBuilder's case, the accumulated String, or in List's, the contained entries.


text:
Q: GMail API - Getting certain message headers or fields I have successfully connected GMail API via G Suite account and service account.  I can get a message list and I can retrieve messages by IDs.  I'm working with PHP.
What I'm having problems with is to get for example the FROM or TO headers, SUBJECT or the snippet field.
$optParam = array('format' => 'metadata', 'metadataHeaders'=>['subject','from'], 'fields'=>['snippet','labelIds']);
$fullMessage = $service->users_messages->get($user, $id, $optParam);

This will return the snippet, but not the subject or from or the labelIds.
If I use the GMail "Try this API" and use the id of the message and use "snippet" in the "fields" entry, I just get the snippet back as:
{
 "snippet": "Short snippet of the message"
}

If I use:
$optParam = array('format' => 'metadata', 'metadataHeaders'=>['subject','from','to']);

I do get the 3 headers, but I also get a lot more information, including the labels and snippet - about 3K for each message.
I just can't seem to be able to specify a small subset of the data.  All I need is to show messages as a list with the subject, date/time, from/to.
I don't care so much about the amount of data, but it takes on average about 3.5 seconds to retrieve the data for just 14 message!
Is there a way to restrict this so I don't get all the "extra" data or speed the retrieval up somehow?

A: Sending the request would involve specifying the metadata keys as well as the parameter names of the fields you want to obtain. You can use an HTTP GET request with the URI to get the 'to', 'from', 'subject' and 'snippet' with https://www.googleapis.com/gmail/v1/users/me/messages/<MESSAGE_ID>?format=metadata&metadataHeaders=to&metadataHeaders=from&metadataHeaders=subject&fields=snippet%2C+payload%2Fheaders, which will also limit the headers you obtain.
In PHP you can use this:
$optParam = array('format' => 'metadata', 'metadataHeaders'=>['subject', 'from', 'to'], 'fields'=>'payload/headers,snippet');

Note that the fields parameter needs to be sent as a string and not an array.
Also be aware there is a known issue with the Gmail API where using the https://www.googleapis.com/auth/gmail.metadata scope will not return the snippet.
You'll need to use https://www.googleapis.com/auth/gmail.readonly instead.
You can also make a batch of requests in one network call which will help speed up overall execution time as documented here.


text:
Q: Does the order of unhiding and loading a webview affect performance? In my app I have a loading view with a progress bar so the user can watch a PDF's download progress. When the download completes I unhide the webview and then call loadRequest. I was just wondering if there is any difference between:

[self.webView setHidden:NO];
[self.webView loadRequest:[NSURLRequest requestWithURL:localURL]];

Versus

[self.webView loadRequest:[NSURLRequest requestWithURL:localURL]];
[self.webView setHidden:NO];

I ask because I assumed loadRequest happens in its own queue, so I thought there couldn't be any visible differences.

A: I don't think they have differences between them.
Because loadRequest is asynchronous, it won't block the main thread.


text:
Q: CodeIgniter and Authorize.net CIM library I'm trying to use the authorize.net library for CI2.0 from https://github.com/cloudmanic/codeignitor-authorizenet-cim-library
When running fulltest() which is the first function in the controller I get:
Creating Customer Profile - create_customer_profile()

Error: The element
  'createCustomerProfileRequest' in
  namespace
  'AnetApi/xml/v1/schema/AnetApiSchema.xsd'
  has invalid child element
  'createCustomerProfileRequest' in
  namespace
  'AnetApi/xml/v1/schema/AnetApiSchema.xsd'.
  List of possible elements expected:
  'validationMode' in namespace
  'AnetApi/xml/v1/schema/AnetApiSchema.xsd'.

A: That error means one of the XML nodes is in the wrong place. Authorize.Net's API is very picky about the format of any XML sent to it. It's hard to say for sure exactly what the error is without seeing the XML generated but it probably has to do with the validationMode element being placed incorrectly.
You can see what a valid XML format looks like in the CIM Guide on page 26.


text:
Q: Can we make cypher field query Case-Insensitive It may seem duplicate of this but it is not. Can we make cypher query case insensitive based on fields. I know we can use regex for values but we need it based on fields.
e.g.
MATCH (c:customer) WHERE c.CUSTOMERNUMBER = '1088' RETURN c

Above query returns a result, but following does not
MATCH (c:Customer) WHERE c.CustomerNumber = '1088' RETURN c

Here lable Customer and property CustomerNumber are having different cases.

A: You can use PROPERTIES to get a map representation of a node, and then use KEYS so that you can iterate over them. Because "Name", "NAME", and "Prop1" are all equally unique property names, and they can all or none exist, as far as the DB is concerned. You will have to iterate every property of the node to find a field that matches your criteria.
MATCH (n)
WHERE ANY(key in KEYS(n) WHERE lower(key)="name" AND n[key]="Neo")
RETURN n

This is more flexible than simple case insensitivity, but it is also expensive.


text:
Q: Is it possible to use CPP code with compile setting USE_CUDNN := 1? In caffe, I must choose the setting USE_CUDNN := 1 when compile. I will write a new layer with .hpp and .cpp code (without .cu). Can I still use my layer if I did not write cuda code (.cu)? For example, I will setup the layer with engine=CAFFE

A: You may have layers that have only CPU implementation. See development page for instruction on what changes are required to make your layer a "CPU only".
However, note that when forwarding/backprop-ing through your net, data will be copied form GPU to CPU memory every time data is passed through your layer. This back and forth memory sync can take significant amount of time and significantly stall your computations. In most cases it is worth while making an effort and implementing a GPU version for the layer as well.


text:
Q: Dynatable and checkbox. Is it possible to refresh a table when I select a checkbox? The question is short. Is there a way to use a DynaTable http://www.dynatable.com , and to filter the results when check-box is selected?
For example, if there is a check box "males", then I would like for the page to list all the males. I don't have a code example as this is the only functionality I need and didn't find in the documentation.

A:
Disclaimer: This is definitely not an answer, as I am pasting some parts that can give a hint, but please do update the answer if you
  find a better explanation.

This is possible to do, not sure what part of the code made this affect, but please check some of the code below, it might give you a hint.
$('#persons-table').dynatable
  features:
    paginate: true
    perPageSelect: true
    search: false

  dataset:
    perPageDefault: 50
    perPageOptions: [50,100, 250, 500]
  inputs:
    queries: $('#person-type')
  readers:
    _rowReader: (index, tr, record) ->

And if we have additional code like this:
  $('#persons-table').bind 'dynatable:init', (e, dynatable) ->
    self.dynatable = dynatable
    dynatable.queries.functions['person-type'] = (record, queryValue) ->
      if (queryValue== 'male')
        return record.person_type == 'male'
      else
        return false


text:
Q: Is there a way to use a Scanner object to search a text document for specific data? I am making a program that reads data from a formatted text document:

Planetary Data
Planet       Diameter (km)      Mass (kg)      g (m/s^2)

*

*Mercury           4880         3.30E+23           3.70

*Venus            12104         4.87E+24           8.87

*Earth            12756         5.97E+24           9.79

*Mars              6794         6.24E+23           3.61

*Jupiter         142984         1.90E+27          24.80

*Saturn          120536         5.68E+26          10.43

*Uranus           51118         8.68E+25           8.86

*Neptune          49352         1.02E+26          11.17

In a text file it's a little more pretty but basically it is a four column document with info one number falling into each column. I am using the scanner class to try to read only the last column of numbers, but can't find an easy way to do it with out using a ton of nextLine() calls. Is there a better way to search just for those doubles, and pull them into an array with a scanner?
This code will compile but I get a mismatch error as soon as I run it.
public static double [] getGravity()throws IOException{
    Scanner inFile = new Scanner(new File("PlanetaryData.txt"));
    double [] getGrav = new double[8];
    for(int i = 0; i < 8; i++){
        getGrav[i] = inFile.nextDouble();
        getGrav[i] /= 10;
        System.out.println(getGrav[i]);
    }
    return getGrav;
}

A: Assuming your text file structure as below:
Mercury 4880 3.30E+23 3.70
Venus 12104 4.87E+24 8.87
Earth 12756 5.97E+24 9.79
Mars 6794 6.24E+23 3.61
Jupiter 142984 1.90E+27 24.80
Saturn 120536 5.68E+26 10.43
Uranus 51118 8.68E+25 8.86
Neptune 49352 1.02E+26 11.17

You may try this:
public static double [] getGravity()throws IOException{
    Scanner inFile = new Scanner(new File("PlanetaryData.txt"));
    double [] getGrav = new double[8];
    for(int i = 0; i < 8; i++){
        getGrav[i] = inFile.nextLine().split("\\s+")[3];
        System.out.println(getGrav[i]);
    }
    return getGrav;
}

A: One possibility is using a List of doubles to store your read graivty values with something like,
List<Double> al = new ArrayList<>();
Scanner scanner = null;
try {
  scanner = new Scanner(new File("file.txt"));
  while (scanner.hasNextLine()) {
    String str = scanner.nextLine();
    if (str == null) {
      continue;
    }
    double gravity = Double.parseDouble(
        str.substring(1 + str.lastIndexOf(' ')).trim());
    al.add(gravity);
  }
} catch (Exception e) {
  e.printStackTrace();
} finally {
  if (scanner != null) {
    scanner.close();
  }
}
System.out.println(al);

However, then you have no direct link between planet name and value. Another option is using a Map<String, Double> to associate the planet name and value like,
Map<String, Double> map = new HashMap<>();
Scanner scanner = null;
try {
  scanner = new Scanner(new File("file.txt"));
  while (scanner.hasNextLine()) {
    String str = scanner.nextLine();
    if (str == null) {
      continue;
    }
    String planet = str.substring(0, str.indexOf(' '));
    double gravity = Double.parseDouble(
        str.substring(1 + str.lastIndexOf(' ')).trim());
    map.put(planet, gravity);
  }
} catch (Exception e) {
  e.printStackTrace();
} finally {
  if (scanner != null) {
    scanner.close();
  }
}
System.out.println(map);


text:
Q: R: Read in double-quote delimited CSV with extra double quote used instead of inch I have a double-quote delimited CSV file that has an extra double quote in it, quotes.csv
ID,Page,Category,Comments1
"6203168",26,"A","test, line 1"
"6205809",26,"B","test, line 2"
"6205410",16,"C","test, 3" line 3"
"6205410",16,"D","test, line 4"

I read a lot of SO and google links, but still cannot read the file correctly.
Basic code:
DataFrame = read.csv("quotes.csv",colClasses=c("character","integer","character","character"),header=TRUE,sep=",")
View(DataFrame)

I tried quote="\"", tried read.table with variations of quote - nothing helped. Note: It is not possible to manually edit the CSV file to correct that double quote. Looking for output like this:
    ID  Page    Category    Comments1
1   6203168 26  A   test, line 1
2   6205809 26  B   test, line 2
3   6205410 16  C   test, 3" line 3
4   6205410 16  D   test, line 4

Thanks!

A: Based on this Stack Overflow post, read.csv does not seem to be able to handle escaped double quotes.  But the link gives a possible workaround.  Most solutions I found involve removing the double quotes before calling read.csv.
In Linux, to remove all double quotes from a file called input.csv, use the sed command:
sed 's/\"//g' input.csv output.csv

Where output.csv is your csv file with all quotes having been stripped.
In Windows, removing quotes from a file is a bit hairier, and you would have to write a batch file.  However, there is an alternative.  When I was working with large csv files to do data modeling, I would just open the files in a program like Textpad or Notepad++ and just do a global replace of all quotes.  You probably don't want this option if you are dealing with csv very often, but this alternative is just fine for occasional use.  Also note that when you open the csv file in an editor, you run the risk that the editor will save and/or strip special characters.


text:
Q: Message: Object required error when querying XML in JavaScript test[_nObjectives].pool[j].feedbackCorrect =
oQuestions[j].getElementsByTagName("feedbackCorrect")[0].firstChild.data;

and the XML in this case contains this:
  <feedbackCorrect>
  </feedbackCorrect>

When executing that line of code the following error occurs: Message: Object required
I don't get it. The tag is there, if it is empty the error occurs and even has spaces chars it doesn't work.

A: you are getting the error because
oQuestions[j].getElementsByTagName("feedbackCorrect")[0]

is returning that tag, and the .firstChild is returning null, because it has no children...
Are you sure you dont want
oQuestions[j].getElementsByTagName("feedbackCorrect")[0].data

?

A: but why it is working when the xml is like this:
<feedbackCorrect>any value</feedbackCorrect>

?


text:
Q: Getting value from Session I have created a Login where the ID is stored in a $_SESSION['login_user'].
After authentication, the user is redirected to his home page. I wanna get the value from the session and use it in a query to retrieve all attributes from the database, corresponding with this userID. This is the code I have tried.
session_start();
..........
..........
..........
$uid= $_SESSION['login_user'];
$result = mysqli_query($db,"SELECT * FROM users UID ='".$uid."'");

It is supposed to get all the values stored in the database of table 'users', but the problem is, sometimes it works, sometimes it doesn't. Most of the time, it doesn't work.
I would appreciate some help with this one
I have also checked whether the Session is empty or not , before going through this step.
This is the part of login when setting the Session:
$result=mysqli_query($db,"SELECT uid FROM users WHERE username='$username' and
password='$password'");
$count=mysqli_num_rows($result);

$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION['login_user']=$row['uid'];

A: Have you tried using correct SQL syntax like SELECT * FROM {table} WHERE something=someval? Like:
$result = mysqli_query($db,"SELECT * FROM users WHERE UID ='".$uid."'");


text:
Q: Артефакты на ui iOS Столкнулся с такой проблемой. При переключении платформы на iOS на кнопках появляются следующие артефакты

Если изменить платформу на другую, артефактов нет
С чем это можетбыть связано?

A: Посмотрите настройки текстур в Unity (каждой конкретной, которая у вас побилась), вкладку для iOS, скорее всего у стоит сжатие текстур в формат PVRTC - из-за этого и появляются артефакты. Попробуйте поставить другой формат (не PVRTC, например ASTC). Также проверьте, что в настройках импорта выключена галочка Generate Mip Maps - это может вызывать то, что для текстур генерируются mip map и выбирается вариант меньшего размера, чем нужно.


text:
Q: Unable to rename VPN connection because Save button is gray I was wishing to rename my VPN connection, but was unable, because Save button is gray.

When running from command line it says:
$ nm-connection-editor
Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged.
** Message: Cannot save connection due to error: Editor initializing...
** Message: Cannot save connection due to error: Invalid setting VPN: cert-pass

How to overcome?


text:
Q: Is it good practice to store NSString data in CFTreeRef using CFTreeContext info object I'm trying to create a tree from DB to create custom table. What i'm doing is fetching data from DB and creating tree structure. To create child nodes i'm storing values in Cftree using info object. Its working fine for me. Anyone could you please let me know will this approach have any performance issues. Because i'm storing a NSString in a info object of each node of a tree. If its having performance issues what's the best way of doing this.
I'm using below code block to create Tree.
static CFTreeRef CreateMyTree(CFTypeRef rootObject) {
CFTreeContext ctx;
ctx.version = 0;
ctx.info = rootObject;
ctx.retain = CFRetain;
ctx.release = CFRelease;
ctx.copyDescription = CFCopyDescription;
return CFTreeCreate(NULL, &ctx);
}

A: There's no problem with using NSStrings as the data of a CFTree. It's treated much the same as any other data. NSString is toll-free bridged to CFString, so using CFRetain, CFRelease, and CFCopyDescription for the callbacks is appropriate.
If you're using ARC, you will need to use a (__bridge CFStringRef) cast to get the pointer.
Note that the tree and your callbacks don't make a copy of the string. So, if you put a reference to an NSMutableString into the tree and subsequently mutate it, that will change the data of the tree. That may or may not be what you want. Considering making a copy before adding it to the tree.
If you are having performance issues, you'll need to explain the nature of those performance issues and why you suspect the use of NSString in a CFTree as the cause. If you merely suspect performance issues, then don't. Until you've measured a performance issue, you're wasting your time.


text:
Q: If closure of a set $D = \mathbb R^p$, then every element of $\mathbb R^p$ is a cluster point of $D$ Using the definition of closure of a set $A$ as the intersection of all closed sets in $\mathbb R^p$ containing $A$ , prove that If closure of a set $D = \mathbb R^p$, then every element of $\mathbb R^p$ is a cluster point of $D$.
Attempt: Suppose $clos D = $ Intersection of all closed sets in $\mathbb R^p$ containing $D$.
Then : $clos D = \mathbb R^p$
Suppose $\exists x \in \mathbb R^p $ such that there exists a neighborhood of $x$ which contains no element of $D$.
Now, we need to show a contradiction by showing that this is not possible.
And thus, every neighborhood of $x$ contains an element of $D$.
How do I show this contradiction?
Thank you for your help.

A: Suppose for some $x \in \mathbb{R}^p$ that we can find an open set $U \subset \mathbb{R}^p$ such that $x \in U$ and $D \cap [U-\{ x\}]= \emptyset$. This means $x$ is not a cluster point of $D$, so $x \notin \overline D$. Since $x \in \mathbb{R}^p$ and $x \notin \overline D$ we deduce that $\mathbb{R}^p \neq \overline D$. This is our contradiction.

A: If $x\in\mathbb{R}^p$ is not a cluster point, then there is an open ball $V$ centered at $x$ such that $V\cap D=\varnothing$. Then, $\mathbb{R}^p\setminus V$ is closed and contains all the $D$.


text:
Q: Where'd the SlimDX NuGet package go? I've been working on a SlimDX project from a couple of different machines lately.  Today I went to pull down my code from SVN, and went through the dance of re-installing all the nuget packages referenced in the project, and I search for slimDX in Nuget, and nothing comes up.
Where'd the package go, and why was it taken down?  It's not that rough to install the SDK instead, but NuGet is more convenient.

A: You can always just install the redistributable of slimdx, you don't need the entire sdk.


text:
Q: AVFoundation camera zoom I use AVFoundation framework to display video from camera.
The code how i use it is usual:
session = [[AVCaptureSession alloc] init] ;
...
captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
...
[cameraView.layer addSublayer:captureVideoPreviewLayer];
...

So i want to add zoom function to camera.
I have found 2 solutions how to implement zoom.
First : is to use CGAffineTransform:
cameraView.transform = CGAffineTransformMakeScale(x,y);
Second :  is to put cameraView in the scroll view ,set up max and min scrolling and set this view as zooming view.
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return cameraView;
}

What is the best way to make zooming better performance and quality? Are there any else solutions to make zoom? Maybe i missed some AVFoundation methods for zooming.
Thank you.

A: Well there is actually a GCFloat called setVideoScaleandCropFactor.
You can find the documentation here.
I'm not sure if this is just for still image output but I've been working on it and it does well if you set it to a gesture or a slider and let that control the float.
You can find a demo of it here.
Good stuff. Im trying to loop it so I can create a barcode scanner with a zoom. What im doing is rough though haha.


text:
Q: Type mismatch error while using a coroutine I have the following in my viewModel
fun getUsernamePassword(inputUserName:String, inputPassword:String):List<User> = viewModelScope.launch(Dispatchers.IO) {
        return repository.getUsernamePassword(inputUserName, inputPassword)
    }

However, I am getting an error saying Type mismatch. Required: List<User> Found:Job What can I do to solve this error. The ultimate goal is to have the function run on a non-black thread operate and a part from the MAIN THREAD to avoid conflict and errors.

A: viewModelScope.launch returns a background Job where you perform your actual repo operation. In this case, you may need an Observable or LiveData to store the list of users in which your UI needs to act upon.
You can do something like this in your ViewModel:
val userList = MutableLiveData<List<User>>()

fun getUsernamePassword(inputUserName:String, inputPassword:String) = viewModelScope.launch(Dispatchers.IO) {
    val list = repository.getUsernamePassword(inputUserName, inputPassword)
    userList.postValue(list)
}

In your view, you need to observe to changes to the userList of the ViewModel by:
viewModel.userList.observe(viewLifecycleOwner, {
    // Place UI changes here
})


text:
Q: Error with referencing a variable before assignment python I have a for loop as part of a larger function:
for table in tables_list:
   if table["file"] == file:
      table_name = table["table_name"]
      break
log.info(f"table: {table_name}")

I am getting an error saying the variable is being referenced before assignment UnboundLocalError: local variable 'table_name' referenced before assignment". Not sure why this is the case because isn't the variable table_name assigned when the condition is met in the loop and then the loop stops?

A: You need to declare the table_name before the loop there might be a chance for unsatisfied this condition table["file"] == file so table_name will be undeclared at that moment.
table_name = None # declare here
for table in tables_list:
   if table["file"] == file:
      table_name = table["table_name"]
      break
log.info(f"table: {table_name}")


text:
Q: How to compile C# application with C++ static library? I turned my C++ Dynamic link library into Static library just to acquire more knowledge.
My question is how can I use the .obj file to compile both projects with C# express/MS visual studio?

A: "Static library" means that the library is going to be merged with your final application.  This concept doesn't exist in .net. .net supports DLLs only.

A: No, you can't access static libraries directly from C#. You have to use a DLL.

A: The way to "use" a static library in C# is to first create a Managed C++ wrapper that will provide a facade for the rest of the managed world.  As everyone else has already commented, C# only supports DLLs for P/Invoke.

A: No way to do that.
Only call DLL functions in runtime or create a COM object from your library


text:
Q: Wildfly Maven deploy ClassNotFoundException but it's there I'm facing a very weird scenario where a particular java file within my project is somehow not being seen by wildfly when deploying.
This is the actual error
2017-02-21 15:30:25,069 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.deployment.unit.obby.POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit.obby.POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of deployment "obby"

The following is the the causing problem
    Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException: bd.domain.repository.VehicleEAO from [Module \"deployment.obby:main\" from Service Module Loader]

That particular class bd.domain.repository.VehicleEAO is in a package within my web project. The deployment works fine in the local wildly on my machine but when i'm doing remote deployment to another machine within my office network i get this error. I have clean and rebuilt the project several times to no avail. What could possibly be the issue? both machines are running the same Java version 1.8.0_121, same wildfly 9.0.2.Final version using same wildfly-maven-plugin 1.0.2.Final


text:
Q: ¿Por qué el array cambia de valor y no sucede lo mismo con la variable int? Quiero saber porque el array cambia de valor y no sucede lo mismo con la variable int.
Ejemplo:
   public static void Main(String[] args)
    {
        Otraclase objeto1 = new Otraclase();
        int[] arr = new int[] { 10 };
        int variable = 10;

        objeto1.Metodo(arr,variable);

        Console.WriteLine(arr[0]);
        Console.WriteLine(variable);

    }
}

class Otraclase
{
   public void Metodo(int[]arra, int vari)
    {
        arra[0] = 20;
        vari = 20;

Resultado:
Array: 20
Variable int: 10

A:

Porque el array cambia de valor y no sucede lo mismo con la variable int?

Al invocarse este método:
objeto1.Metodo(arr,variable);

Suceden dos cosas:

*

*Al primer parámetro se le está pasando la dirección de memoria al que apunte la variable arr. Sin embargo, aquí se pasó por valor, es decir, lo que tendrá el parámetro es una copia del contenido de arr. Por esa razón, durante la ejecución del método, no podemos modificar el contenido de la variable arr, pero si podemos alterar el contenido del objeto original (por esa razón puedes hacer esto: arra[0] = 20) al que apuntaba arr y esto se debe, porque justamente esa copia es la dirección base de un objeto.

*El segundo parámetro también se pasa por valor, debido a que, el parámetro tendrá una copia del contenido de la variable. Así que al asignar un 20 al parámetro, nunca alterará el contenido de la variable original.
Para pasar por referencia, debemos usar el operador ref.
Ejemplo:
class Program
{
    public static void Main(String[] args)
    {
        Otraclase objeto1 = new Otraclase();
        int[] arr = new int[] { 10 };
        int variable = 10;

        objeto1.Metodo(ref arr, ref variable);

        Console.WriteLine(arr[0]);
        Console.WriteLine(variable);
        //Resultado por pantalla: 11 y 20.
    }
}

class Otraclase
{
    public void Metodo(ref int[]arra, ref int vari)
    {
        arra = new int[]{11};
        vari = 20;
    }
}

Al ejecutarse el método, se le está pasando al parámetro arra la dirección de memoria donde esté alojado la variable arr, por lo tanto, durante la ejecución del método, podemos alterar el contenido de la variable original y también el contenido al que apunte arr. El argumento que se le pasa al parámetro vari también se pasa por referencia. Esta es la razón del porque se puede alterar las variables arr y variable.

A: Porque no estas modificando los valores que tu crees, al llamar la clase "Metodo" los cambios se quedan dentro de esta, no los has aplicado en tu clase principal, lo que deberías hacer es que ese metodo te retorne algo y entonces asignarselo a la variable que quieres modificar, ejemplo:
arr[0] = objeto1.modificar(20);
variable = objeto1.modificar(20);


text:
Q: Springboot : Controller class is not getting triggered For a learning purpose, i have started with a simple spring boot application in eclipse. I was able to run it successfully at http://localhost:8080. Next I added a controller. But i saw that the controller never gets triggered. Any help will be appreciated. The URL I use to access my controller is : http://localhost:8080/conference/greeting
My project structure:

pom.xml dependencies:
    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>

Source Code:
    @SpringBootApplication
    public class ConferenceApplication extends SpringBootServletInitializer {

        public static void main(String[] args) {
            SpringApplication.run(ConferenceApplication.class, args);
        }

    }
    @Controller
    public class GreetingController {

        @GetMapping("greeting")
        public String greeting (Map<String, Object> model) {
            model.put("message", "Hello Lok");
            return "greeting";
        }
    }

application.properties
    spring.mvc.view.prefix=/WEB-INF/jsp/
    spring.mvc.view.suffix=.jsp

greeting.jsp:
    <!DOCTYPE html>
    <html lang="en">
       <head>
           <meta charset="UTF-8">
           <title>Greeting</title>
       </head>
       <body>
           <h1>${message}</h1>
       </body>
    </html>

A: Set server.servlet.context-path=/conference in application.properties or put the controller class annotation @RequestMapping("conference")


text:
Q: On the Haar measure of Grassmanians How can one write down the Haar measure of complex Grassmanians in terms of Plucker coordinates? Is there any way to define a Kahlarian measure like $d\mu\propto \det(g)dp_{ij}dp^{*}_{ij}$ where $g$ stands for the Grassmanian metric and $p_{ij}$ are the Plucker coordinates?
Thanks in advance
AB


text:
Q: Angularjs handling leaving a template in various ways? I am trying to implement a function in my angular module that will fire an event that saves the changes on the page. The different ways a user can leave the page is:

*

*Clicking a link that loads a new template.

*Clicking the back button

*Closing the tab/window

My implementation handles #1 using this code:
.directive('confirmOnExit', function() {
    return {
        link: function($scope, elem, attrs) {
            window.onbeforeunload = function(){
                    return "If you leave this page, you will exit the practice session. You will be able to view your score report for the completed session but will have to start a new one if you want to continue practicing.";
            }
            $scope.$on('$locationChangeStart', function(event, next, current) {
                    if($scope.$dirty & confirm("Are you sure you want to leave this practice session?")) {
                        console.log("Will end session!");
                        end_session();
                    }
            });
        }
    };
});

However, when #2 or #3 occur, the pop up dialog shows up but it seems like it is not triggering the end_session() function.
Any insights into how to deal with the back button and closing the tab/window would be appreciated?

A: Sounds to me like a race condition. end_session() might not be firing before the browser successfully unloads the page, but without more code I can't really help, since I'm not sure what end_session() does.
What you could do is capture the locationChangeStart and defer it until after all of your unload tasks are complete.
A quick note, directly referencing window is an Angular "anti-pattern" of sorts:
https://docs.angularjs.org/api/ng/service/$window


text:
Q: Why doesn't my image embed in an HTML email? I'm trying to run code in VBA that will send out HTML emails and am trying to embed an image within the email. I have the following code to do so:
Sub EmailImage()

Dim oApp As Outlook.Application
Dim oEmail As MailItem
Dim colAttach As Outlook.Attachments
Dim oAttach As Outlook.Attachment

Set oApp = CreateObject("Outlook.Application")
Set oEmail = oApp.CreateItem(olMailItem)
Set colAttach = oEmail.Attachments
Set oAttach = colAttach.Add("C:\Users\User1\Documents\thumbs-up.jpg")
oEmail.Close olSave
oEmail.To = "abc@abc123.com"
oEmail.HTMLBody = " "
oEmail.Send
Set oEmail = Nothing
Set colAttach = Nothing
Set oAttach = Nothing
Set oApp = Nothing

End Sub

But what happens is that the image gets attached but there's a box with a red cross in it where the image should be, as is shown in the below image:

I have tried the following adapton to the code:
Sub EmailImage()
Dim oApp As Outlook.Application
Dim oEmail As MailItem
Dim colAttach As Outlook.Attachments
Dim oAttach As Outlook.Attachment

Set oApp = CreateObject("Outlook.Application")
Set oEmail = oApp.CreateItem(olMailItem)
Set colAttach = oEmail.Attachments
Set oAttach = colAttach.Add("C:\Users\User1\Documents\thumbs-up.jpg")

oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyCid")

oEmail.Close olSave
oEmail.To = "abc@abc123.com"
oEmail.HTMLBody = " "
oEmail.Send
Set oEmail = Nothing
Set colAttach = Nothing
Set oAttach = Nothing
Set oApp = Nothing
End Sub

But this gives me the error "Compile error: expected =" on the line oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyCid") so I tried to take out the , "MyCid") and changed the code in the email to just oEmail.HTMLBody = " " again, so that it looks like this:
Sub EmailImage()

Dim oApp As Outlook.Application
Dim oEmail As MailItem
Dim colAttach As Outlook.Attachments
Dim oAttach As Outlook.Attachment

Set oApp = CreateObject("Outlook.Application")
Set oEmail = oApp.CreateItem(olMailItem)
Set colAttach = oEmail.Attachments
Set oAttach = colAttach.Add("C:\Users\User1\Documents\thumbs-up.jpg")
oAttach.PropertyAccessor.SetProperty ("http://schemas.microsoft.com/mapi/proptag/0x3712001F")

oEmail.Close olSave
oEmail.To = "abc@abc123.com"
oEmail.HTMLBody = " "
oEmail.Send
Set oEmail = Nothing
Set colAttach = Nothing
Set oAttach = Nothing
Set oApp = Nothing

End Sub

But I now get the error Compile error: argument not optional with it pointing at the .SetProperty part of the line oAttach.PropertyAccessor.SetProperty ("http://schemas.microsoft.com/mapi/proptag/0x3712001F").
Please note that I am using Windows 7, Microsoft Excel 2010 and Microsoft Outlook 2010.

A: Ok, after Googling the error message "Compile error: expected =", the changing the line:
oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyCid")

To:
Call oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyCid")

Worked.
I found this out from http://answers.microsoft.com/en-us/office/forum/office_2010-access/vba-compile-error-expect-in-sub-call/a47c752f-3034-41a6-a77c-b3ddaa34b24c?auth=1
Thank you for all your comments and answers.

A: VBA does not like parenthesis when calling a sub - try to get rid  of ():
    oAttach.PropertyAccessor.SetProperty "http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyCid"


text:
Q: SwiftUI onCommit doesnt move cursor to next textfield - MacOS app I have two TextFields that use onCommit. Pressing enter saves the value. However, this does not automatically move the cursor to the next TextField. I want it to work like the tab button which moves the cursor to next TextField but this doesn't save the value (due to onCommit requiring enter/return to be pressed). The best solution I have found is using a button but that results in poor usability as I would be using a ForLoop over this view.
struct ModuleDetailView: View {
    @Binding var subjectDetails: [Subjects]
    @State private var subject = ""
    @State private var grade = ""
    var body: some View {
        VStack {
            TextField("Subject", text: $subject, onCommit: appendData)
            TextField("Grade", text: $grade, onCommit: appendData)
            VStack {
                Text("Output")
                ForEach(subjectDetails) { subject in
                    HStack {
                        Text(subject.name)
                        Text(subject.grade)
                    }
                }
            }
        }
    }

    func appendData() {
        if subject != "" && grade != "" {
            let module = Subjects(name: subject, grade: grade)
            subjectDetails.append(module)
        }
    }
}

The preview code:
struct ModuleDetailView_Previews: PreviewProvider {
    static var previews: some View {
        PreviewWrapper()
    }
    struct PreviewWrapper: View {
        @State var modules = [Subjects]()
        var body: some View {
            ModuleDetailView(subjectDetails: $modules)
        }
    }
}

both textfields are visible at the same time. What happens is that after I press enter from the first textField the cursor just vanishes, which works differently from when we press TAB - simply moves to the next. And I want it to work similar to how it behaves when TAB is pressed. Therefore, in this case using a firstResponder might not be a good option
Subjects struct:
struct Subjects: Identifiable {
    let id = UUID()
    var name: String
    var grade: String
}


text:
Q: The SDK 'Microsoft.NET.Sdk.Web' specified could not be found in VSCode OmniSharp extension I've installed dotnet core 3 sdk and OmniSharp 1.18 extension on VSCode
but OmniSharp has an error:
Microsoft.Build.Exceptions.InvalidProjectFileException: The SDK 'Microsoft.NET.Sdk.Web' specified could not be found.

A: The answer by Evgy will work specifically with .NET Core Preview 3, but if you want the fix to work with the released version of .NET Core 3.0 or higher, then you can add the following line to your .bashrc file (supposing you are on Linux):
export MSBuildSDKsPath="/usr/share/dotnet/sdk/$(dotnet --version)/Sdks"

A: I have this problem and none of the above answers worked for me, I don't know why this happens
but I found a little trick to fix this problem.
open your terminal and go to your project directory and execute this command
code .

yes! opening vscode from terminal fix this problem for me

A: I had this problem with DotNet Core 3.0 and VS Code. The intellisense was not working for me.
I had an installation of Visual Studio 2019 which caused Omnisharp to get MsBuild from the following location:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin

Following some answers on Omnisharp GitHub, I installed Visual Studio Build Tools 2019 from the following link:
https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools&rel=16
To prevent Omnisharp from getting MsBuild from the former path, I renamed MsBuild folder to MsBuild.disabled so that the path becomes:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild.disabled\Current\Bin

Now, when I restard VS Code, Omnisharp gets MsBuild from the path C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin instead of the former path. The error is gone and intellisense works fine now.

A: Try the workaround solution bellow:
Add a file called omnisharp.json to your project folder with following content
{
    "MsBuild": {
        "UseLegacySdkResolver": true
    }
}

Then restart the Visual Studio Code

A: You need to install ".Net Core build tools" from the Visual Studio installer, as described here - https://github.com/OmniSharp/omnisharp-roslyn/issues/1311#issuecomment-428361674
Can also be installed with chocolatey:
choco install visualstudio2017-workload-netcorebuildtools

A: If you're on Linux or Mac, add the path to your sdk folder in your .bashrc (or wherever else you want):
export MSBuildSDKsPath=$HOME/soft/dev/dotnet/sdk/3.0.100-preview3-010431/Sdks

The same behavior can also be solved with this command: dotnet nuget locals all -c

A: *

*It should be v1.18.0-beta7 at this time: https://github.com/OmniSharp/omnisharp-vscode/releases

*Also if you are just using your old projects, try to add an appropriate global.json file to their root, by issuing dotnet new globaljson --sdk-version 2.2.100 command. Otherwise they will use the .NET Core 3x SDK by default. If you do have a global.json, check its content and make sure you are using a correct version. You can find the installed versions using the dotnet --list-sdks command.

*It's better to report your issue here so they can fix it for the next beta version.

A: Neits solution for Ubuntu [20.04] Snap users.
echo 'export MSBuildSDKsPath="/snap/dotnet-sdk/current/sdk/$(dotnet --version)/Sdks"' >> ~/.bashrc
source ~/.bashrc
echo $MSBuildSDKsPath

A: on the global.json file inside the project make sure that the sdk version is the same as the one you have installed on the system.

A: that might be extremely stupid but after a couple hours of googling this problem I gave up and just coded my own build task to call dotnet build instead of msbuild into tasks.json:
        {
            "label": "build",
            "type": "shell",
            "command": "dotnet",
            "args": [
                "build",
            ],
            "group": "build",
            "presentation": {
                "reveal": "silent"
            },
            "problemMatcher": "$msCompile"
        }

and here is my launch config from launch.json:
        {
            "name": ".NET Core Launch (console)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            "program": "${workspaceFolder}/bin/Debug/net5.0/${workspaceFolderBasename}.dll",
            "args": [],
            "cwd": "${workspaceFolder}",
            "console": "integratedTerminal",
            "stopAtEntry": false
        }

It might not be a correct way to do this but it lets me run my code and use all the functions of the debugger, so I guess it's good enough.

A: The only thing that worked for me was quitting VSCode (I'm on a Mac) and reinstalling the .NET SDK.


text:
Q: nginx rewrite not working (with passenger on Mac OS X) I have nginx with rewriting working correctly on my server in production.
But when I tried to set the same rule on my local development machine (mac) the rewrite doesn't seem to be working.
I want "universitytutor.local" to redirect to "www.universitytutor.local"
Here is the relevant part of my nginx.conf
    server{
            listen 80;
            server_name universitytutor.local;
            rewrite ^/(.*) http://www.universitytutor.local/$1 permanent;
    }

    server {
          listen 80;
          server_name www.universitytutor.local *.universitytutor.local;
          root /Users/barmstrong/NetBeansProjects/universitytutor/public;   # <--- be sure to point to 'public'!
          passenger_enabled on;
                rails_env development;
    }

The page loads correctly whether I type "universitytutor.local" or "www.universitytutor.local" and it does not redirect.
I have the *.universitytutor.local in there because I use subdomains for different cities so I need this, but I want a blank subdomain to redirect to "www".
Any ideas?

A: Found the solution for this.  I was not restarting Nginx correctly so it was not picking up the changes.  Doh!
You can restart like this
sudo kill `cat /opt/nginx/logs/nginx.pid `
sudo /opt/nginx/sbin/nginx

or add this to your .bashrc for easier use
alias nginx_restart='nginx_stop; nginx_start'
alias nginx_start='sudo /opt/nginx/sbin/nginx'
alias nginx_stop='sudo kill `cat /opt/nginx/logs/nginx.pid `'


text:
Q: Tell jQuery to ignore clicks during an animation sequence I'm in the midst of writing a slide show app (click a button, and you slide through a list of images) for jQuery, but I've run into a little bug where it will respond to the click() request even while an animation is happening. I'm using the animate() function already, so that isn't staving off the additional animation requests.
Any way to program around this?

A: You can check whether the animation is in progress in the click handler:
if ($(this).is(':animated')) return false;

Alternatively, you can use the live or delegate functions to only bind the handler to non-animated elements:
$('something:not(:animated)').live('click', function() { ... });


text:
Q: Accessibility issue in ng-select For accessibility testing I am using axe tool where I am getting below error.
Required ARIA child role not present: option
This is my code where I am using angular ng-select:
<ng-select [items]="rolesList" bindLabel="roleName" placeholder="Select Role" [(ngModel)]="role" aria-label="role" id="rolesList" tabindex="0">
</ng-select>

A: ng-select uses their custom bindLabel Input in order to automatically populate the aria accessibility. aria-label isn't used, instead aria-role is used to describe that it is an option or group as expected. You can add a parent div with aria-label if you feel it is a necessity to have a screen reader describe the select in further detail, but aria-own and aria-activedescendent tags are added. Please see this merged PR for more information on the source of how these tags are used: https://github.com/ng-select/ng-select/pull/433/files
Note: There are also known issues with specific screen readers (such as aXe) as described here: https://github.com/ng-select/ng-select/pull/1026. There has been some custom work to enhance the usage but it was never merged.


text:
Q: Getting past entity framework BeginTransaction I am trying to make sense of mocking in unit testing and to integrate the unit testing process to my project. So I have been walking thru several tutorials and refactoring my code to support mocking, anyway, I am unable to pass the tests, because the DB method I am trying to test is using a transaction, but when creating a transaction, I get

The underlying provider failed on Open.

Without transaction everything works just fine.
The code I currently have is:
[TestMethod]
public void Test1()
{
    var mockSet = GetDbMock();
    var mockContext = new Mock<DataContext>();
    mockContext.Setup(m => m.Repository).Returns(mockSet.Object);

    var service = new MyService(mockContext.Object);
    service.SaveRepository(GetRepositoryData().First());
    mockSet.Verify(m => m.Remove(It.IsAny<Repository>()), Times.Once());
    mockSet.Verify(m => m.Add(It.IsAny<Repository>()), Times.Once());
    mockContext.Verify(m => m.SaveChanges(), Times.Once());
}

// gets the DbSet mock with one existing item
private Mock<DbSet<Repository>> GetDbMock()
{
    var data = GetRepositoryData();
    var mockSet = new Mock<DbSet<Repository>>();

    mockSet.As<IQueryable<Repository>>().Setup(m => m.Provider).Returns(data.Provider);
    // skipped for brevity
    return mockSet;
}

Code under test:
private readonly DataContext _context;
public MyService(DataContext ctx)
{
    _context = ctx;
}

public void SaveRepositories(Repository repo)
{
    using (_context)
    {
        // Here the transaction creation fails
        using (var transaction = _context.Database.BeginTransaction())
        {
            DeleteExistingEntries(repo.Id);
            AddRepositories(repo);
            _context.SaveChanges();
            transaction.Commit();
        }
    }
}

I was trying to mock the transaction part as well:
var mockTransaction = new Mock<DbContextTransaction>();
mockContext.Setup(x => x.Database.BeginTransaction()).Returns(mockTransaction.Object);

but this is not working, failing with:

Invalid setup on a non-virtual (overridable in VB) member: conn =>
  conn.Database.BeginTransaction()

Any ideas how to solve this?

A: As the second error message says, Moq can't mock non-virtual methods or properties, so this approach won't work. I suggest using the Adapter pattern to work around this. The idea is to create an adapter (a wrapper class that implements some interface) that interacts with the DataContext, and to perform all database activity through that interface. Then, you can mock the interface instead.
public interface IDataContext {
    DbSet<Repository> Repository { get; }
    DbContextTransaction BeginTransaction();
}

public class DataContextAdapter {
    private readonly DataContext _dataContext;

    public DataContextAdapter(DataContext dataContext) {
        _dataContext = dataContext;
    }

    public DbSet<Repository> Repository { get { return _dataContext.Repository; } }

    public DbContextTransaction BeginTransaction() {
        return _dataContext.Database.BeginTransaction();
    }
}

All of your code that previously used the DataContext directly should now use an IDataContext, which should be a DataContextAdapter when the program is running, but in a test, you can easily mock IDataContext. This should make the mocking way simpler too because you can design IDataContext and DataContextAdapter to hide some of the complexities of the actual DataContext.

A: I've tried the wrapper/adapter approach, but came up against the problem that when you then go to test the code:
using (var transaction = _myAdaptor.BeginTransaction())

Your mock/fake still needs to return something so the line transaction.Commit();
can still execute.
Normally I'd set the fake of my adapter to return an interface from BeginTransaction() at that point (so I can fake that returned object too), but the DbContextTransaction returned by BeginTransaction() only implements IDisposable so there was no interface that could give me access to the Rollback and Commit methods of DbContextTransaction.
Furthermore, DbContextTransaction has no public constructor, so I couldn't just new up an instance of it to return either (and even if I could, it wouldn't be ideal as I couldn't then check for calls to commit or rollback the transaction).
So, in the end I took a slightly different approach and created a separate class altogether to manage the transaction:
using System;
using System.Data.Entity;

public interface IEfTransactionService
{
    IManagedEfTransaction GetManagedEfTransaction();
}

public class EfTransactionService : IEfTransactionService
{
    private readonly IFMDContext _context;

    public EfTransactionService(IFMDContext context)
    {
        _context = context;
    }

    public IManagedEfTransaction GetManagedEfTransaction()
    {
        return new ManagedEfTransaction(_context);
    }
}

public interface IManagedEfTransaction : IDisposable
{
    DbContextTransaction BeginEfTransaction();
    void CommitEfTransaction();
    void RollbackEfTransaction();
}

public class ManagedEfTransaction : IManagedEfTransaction
{
    private readonly IDataContext  _context;
    private DbContextTransaction _transaction;

    public ManagedEfTransaction(IDataContext  context)
    {
        _context = context;
    }

    /// <summary>
    /// Not returning the transaction here because we want to avoid any
    /// external references to it stopping it from being disposed by
    /// the using statement
    /// </summary>
    public void BeginEfTransaction()
    {
        _transaction = _context.Database.BeginTransaction();
    }

    public void CommitEfTransaction()
    {
        if (_transaction == null) throw new Exception("No transaction");

        _transaction.Commit();
        _transaction = null;
    }

    public void RollbackEfTransaction()
    {
        if (_transaction == null) throw new Exception("No transaction");

        _transaction.Rollback();
        _transaction = null;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // free managed resources
            if (_transaction != null)
            {
                _transaction.Dispose();
                _transaction = null;
            }
        }
    }
}

I then inject that service class into whatever classes need to use a transaction.  For example, using the code from the original question:
private readonly DataContext _context;
private readonly IEfTransactionManager _transactionManager;

public MyService(DataContext ctx, IEfTransactionManager transactionManager)
{
    _context = ctx;
    _transactionManager = transactionManager;
}

public void SaveRepositories(Repository repo)
{
    using (_context)
    {
        // Here the transaction creation fails
        using (var managedEfTransaction = _transactionManager.GetManagedEfTransaction())
        {
            try
            {
                managedEfTransaction.BeginEfTransaction();

                DeleteExistingEntries(repo.Id);
                AddRepositories(repo);
                _context.SaveChanges();

                managedEfTransaction.CommitEfTransaction();
            }
            catch (Exception)
            {
                managedEfTransaction.RollbackEfTransaction();
                throw;
            }
        }
    }
}

A: You can find a pretty good solution here.
In short, you need to create proxy class for DbContextTransaction and use it instead of an original one. So that you can mock your proxy and test your method with BeginTransaction().
PS. In article which I linked above, author forgot about the virtual keyword for BeginTransaction() method placed in dbContext class:
// <summary>
/// When we call begin transaction. Our proxy creates new Database.BeginTransaction and gives DbContextTransaction's control to proxy.
/// We do this for unit test.
/// </summary>
/// <returns>Proxy which controls DbContextTransaction(Ef transaction class)</returns>
public virtual IDbContextTransactionProxy BeginTransaction()
{
   return new DbContextTransactionProxy(this);
}


text:
Q: Get LocalStorage file for app's browser in the Java code I have a Cordova android application, which is basically an in-app browser window, that has a local storage file somewhere, where I save data from the app. I want to access this local storage file from the Java code now, but I don't know how. How can I do that?

*

*Searched in Google before asking.

*No code to show, because there is
nothing relevant to show.

A: See
Cordova file plugin
and
Exploring file APIs

A: Cordova is just a container to let you get access to device APIs with html, css, and javascript. When you use something like localStorage, it gets stored in whatever browser the phone uses (iOS would be Safari, Android varies).
Use localStorage.getItem(idOfTheItemYouStored) to get access to whatever file you are looking for. If you don't know what you named it, you can use a for loop to loop through and log each item as so:
for(var i in localStorage) {
    console.log(localStorage[i]);
}


text:
Q: top 10 counts from csv using ggplot2 in R I have csv "celebrity deaths" and column "cause of death". I would like to make in ggplot2 chart, when I have count of top 10 death causes.
I do not how to count in R when I'm using date from csv.
I got csv which looks like:
https://i.imgur.com/WFTpzDE.png
And I think that I will need vector will all causes. But I do not have idea how to group them in top 10.

A: Im going to try to produce something as best I can with what you provided with base R and ggplot2.
library(ggplot2)

celeb <- c("Kim Kardashian", "The chubby kid from stand by me", "The bassist from the local Clash cover band", "One of L. Ron Hubbard's polyps", "Frank Zappa", "Dweezil Zappa", "Moonunit Zappa", "Scott Evil")

death <- c("Gored by rhino", "Eaten by Compies", "Choked on funyun", "Gored by rhino", "Gored by rhino", "Eaten by Compies", "Gored by rhino", "Failed to meet dad's expectations")

df <- cbind(celeb, death)
df <- as.data.frame(df)

So, my sense is that you just want to rank causes of death and then barplot them or something. This is overly complicated, but I figured I would just show you a step by step way of doing it.
    #first get counts of deaths
deathcounts <- as.data.frame(table(df$death))

#next put them in decreasing order
topfour <- deathcounts[order(deathcounts$Freq, decreasing=T)[1:4],]

#cool, so rhinos are dangerous mofos. Let's plot these results
deathplot <- ggplot(topfour, aes(x=Var1, y=Freq)) + geom_bar(stat="identity")

Your no frills, plain result is:


text:
Q: Jquery .load function. Passing a php variable to .load() Im trying to pass a PHP variable, ($name) through the .load function. Every time i try to call similar.php, instead of search for whatever is in $name, its searching for

Heres my java code;
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("similar.php?search="+"&name");
  });
});
</script>

Ive also tried, orginally:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("#div1").load("similar.php?search=<?php $name ?>);
      });
    });
    </script>

Any tips?

A: You forgot the last quote and to echo the $name, change this :
$("#div1").load("similar.php?search=<?php $name ?>);

to:
$("#div1").load("similar.php?search=<?php echo urlencode($name) ?>");

And use the DOM inspector to view the code and see that the PHP is outputted properly.


text:
Q: Using BitmapRegionDecoder to tile a large image I'm currently attempting set a large image (1800x1800) as an overlay on a Google MapView. I've figured out how to tile it, but I'm not quite certain as to how to place each tile in the proper place. I'm using BitmapRegionDecoder to chop the larger image into several 100x100 tiles. I'm assuming that I'll use a larger Rect object as the frame for the larger image, but I'm not quite certain as to how to place each smaller image in its proper place inside the frame.
Rect outerFrame = new Rect(0, 0, 1800, 1800);
            try {
                asset = this.getResources().getAssets().open("foo.png");
                decoder = BitmapRegionDecoder.newInstance(asset, false);

                for (int y = 0; y < 1800; y += 100)
                {
                    for (int x = 0; x < 1800; x += 100)
                    {
                        Rect innerTile = new Rect(x, y, x + 100, y + 100);
                        Bitmap region = decoder.decodeRegion(innerTile, null);
                        // Need something here
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


text:
Q: Python azure-servicebus throws circular import error for ServiceBusClient and ServiceBusMessage After installing azure servicebus from pypl( azure-servicebus 7.3.4 ) using pip, i am trying those provided sample code from https://pypi.org/project/azure-servicebus/.
It gives error:
from azure.servicebus import ServiceBusClient
ImportError: cannot import name 'ServiceBusClient' from partially initialized module 'azure.servicebus' (most likely due to a circular import) (C:\python\lib\site-packages\azure\servicebus_init_.py)
I am using windows10.
other azure services like FaceAPI and CustomVision libraries are working fine.
Just this ServiceBus is throwing error.
I am new to azure in python. Any kind help of help is highly appreciable.

A: Make sure you don't have any of your working .py file named  like ServiceBusClient.py or ServiceBusMessage.py or azure_servicebus.py which can conflict with Python/ServiceBus package installed files.
If you are using Python 3.8.9, you can try installing the lower version of azure-servicbus as answered by Frank Gong
pip install azure-servicebus==7.0.0

You can refer to ImportError: cannot import name '...' from partially initialized module '...' (most likely due to a circular import), Circular Import Error while importing create_engine in Sqlalchemy,  and  ImportError: cannot import name 'ServiceBusClient' from 'azure.servicebus'
You can refer to the available Azure Service Bus libraries for Python


text:
Q: How share some f:event of f:metadata between selected XHTML with managed bean interface as parameter Noting that from JSF view metadata demystified:

Since this tag is about current view metadata it doesn't participate
  in XHTML templates (the page author must ensure that the
  element does not appear on a template or included page; it can be in a
  template client) and it is direct child of <f:view>.

I have multiple <f:viewParam> and <f:event> that repeat in many XHTML pages, which are in turn clients of a template.xhtml. Each f:event depends on a given managed bean, where the managed bean is different for each XHTML page (but respects a common interface, i.e., the same operations for the listeners exist for every relevant managed bean):
<f:view>
    <f:metadata>

        <!-- I want to share this across many XHTML parametrised by the bean -->
        <f:viewParam name="id" value="#{particularBean.id}"/>
        <f:event type="preRenderView" listener="#{particularBean.opCommon1}"/>
        <f:event type="preRenderView" listener="#{particularBean.opCommon2}"/>
        <!-- END SHARED PORTION -->

        <f:event type="preRenderView" listener="#{particularBean.onlyForMe}"/>

    </f:metadata>
</f:view>

<ui:composition template="/template.xhtml">

Q: How can I encapsulate the shared <f:viewParam> and <f:event> portion so that it can be "included" and treated as a common policy fragment, with particular managed beans (meeting the common interface) passed in for each XHTML page ?

A: I found the answer in one of my own older projects (as I posted I recalled vaguely I had investigated this already at some stage years ago). This works:
In /include/shared.xhtml:
<ui:composition
 xmlns="http://www.w3.org/1999/xhtml"
 xmlns:f="http://xmlns.jcp.org/jsf/core"
 xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
 >
    <f:viewParam name="id" value="#{particularBean.id}"/>
    <f:event type="preRenderView" listener="#{compatibleBean.opCommon1}"/>
    <f:event type="preRenderView" listener="#{compatibleBean.opCommon2}"/>
</ui:composition>

And in any client:
<f:view>
 <f:metadata>

  <ui:include src="/included/shared.xhtml">
    <ui:param name="compatibleBean" value="#{particularBean}"/>
  </ui:include>

  <f:event type="preRenderView" listener="#{particularBean.onlyForMe}"/>

 </f:metadata>
</f:view>


text:
Q: Start a concurrent async task from within another async task I have an I/O-bound task implemented with an async-await function.
At some point in this function, I receive some information which allows me to start a concurrent task, which is also I/O-bound (and so it is also implemented with an async-await function). My original task is not bound by this new task - I just need to set it going in the background.
If I do the following, I get warned that I'm not awaiting the call. I don't want to await the call! I want it to happen in the background!
async Task AnotherAsyncThing()
{
    // ...
}

async Task SomeAsyncThing()
{
    // ...

    // run concurrently - warning raised here
    Task.Run(async () => await AnotherAsyncThing());

    // ...
}

Am I missing something horribly obvious here? It feels like I am!

A: You can do something like this:
_ = AnotherAsyncThing()

This is the discards feature added in C# 7.0 and is a way of communicating the fact you're not interested in the return value to the compiler.

A: Yes and no :)
so often bugs occur when people forget to wait for tasks and it is considered a risk in APIs for instance to keep spinning up non awaited tasks because you can sometimes do so rapidly with bad performing client code and if that can steal many resources ... we'll i'm sure You can imagine.
But to signify that You know what You're doing and assume full responsibility, You can use the TPL like this and get rid of the warnings
_ = Task.Run(
        () => _ = AnotherAsyncThing()
    );

But each time this code is passed it will continue immediately and start something which will also continue to run. So Say your API gets a post, which accidentally happens every 10th millisecond instead of every 10th second as intended ... there is a danger in making the use of these things a standard.
It is a tool for a specific purpose, not the new white for walls, but yea You may have missed that we now should tell by using the nevermind underscore, that we know what we're doing this time and the compiler should back out from helping.


text:
Q: How to plot images of different size at the same resolution? A collection of images are plotted as follow:
figure(num=None, figsize=(16, 14), dpi=300)
k=1
for i in range(1,10):
    for j in range(1,6):
        subplot(9,5,k,xticks=[],yticks=[])
        imshow(rgb_chromosomes[k-1],interpolation='nearest')
        k=k+1

It is visible that from a image to an other, pixels are not the same size.
How to fix that issue?

A: Use interpolation= 'bilinear' and subsample the result with regular spacing (say take every other four pixel, this depends on the final pixel size you want) and form a tiny image. Then magnify this tiny image with 'nearest' interpolation.
You can also keep the 'nearest' setting for the first interpolation, but the result will look ugly.

A: so, from image to image are the pixels different sizes? From context, I am guessing that these are all snippets from the same image/imaging conditions and you want the scale to be the same in all of them.
Something like:
fig, ax_lst = plt.subplots(9, 6)  # better way to set up your axes
for k, ax in enumerate(ax_lst.ravel()):
    ax.imshow(rgb_chromosomes[k], interpolation='none')
    ax.set_xlim([0, max_image_width])
    ax.set_ylim([0, max_image_height])
    ax.set_frame_on(False)


text:
Q: Java Time Delay I am having trouble with the following bit of code.
//Send Creation email
ListServDAO.sendCreateEmail(orgId, full, request.getSession().getServletContext());
//Force a 1 minute pause
       Timer timer = new Timer();
       timer.schedule(new TimerTask() {
            public void run() {
                //Send add members email
                ListServDAO.sendAddMembersEmail(orgId, request.getSession().getServletContext());
                }
            }, 0, 60 * 1000);

The sendAddMembersEmail function does not wait 1 minute to send after the sendCreateEmail function call.  I am not sure why it is not waiting even after reading the java API. I do not wish to use the Thread.sleep method because I want the user to be able to use the application while waiting for the emails to send.

A: are you intending to repeatedly send emails?  if not, why are you using the method which takes 2 longs (i.e. "repeatedly run this task every <period> milliseconds")?  use the schedule(task, delay) method (and use a non-zero delay).

A: 2nd parameter is the initial delay which you are passing as 0 hence it it executing it right then and there, pass 60000 second for it to wait for a minute and then send.
Since you just want it to send only once use, call Timer.schedule(TimerTask task, long delay)
Off-topic:
You should consider using ScheduledExecutorService instead of Timer. See Oracle Tutorial.

A: You have an extra zero.
What you are calling is Delayed with a Fixed-Delay Repeat Execution and what you want is a Single Delay Non Repeat execution.

A: You have the order of the params wrong:
    schedule(TimerTask task, long delay, long period)
      Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.

Swap the 0 and 60*1000.


text:
Q: Specify copy constructor to not be used as copy constructor I have a class A. In this class it contains a pointer to another A.
class A
{
    A* sub = NULL;
};

I want to have an empty constructor that defaults this pointer to NULL, and another constructor that passes a pointer/reference. This second constructor would copy the parameter into a new A() object, and transfer sub from the parameter, to itself.
the class now:
class A
{
    A* sub = NULL
    A(A* source)
    {
        this->sub = new A(*source);//copy the source 'A'

        // we now have a copy of "source" and all of its children
        // but to prevent the "source" from deleting our new
        // children (destructor deletes children recursively),
        // "source"s children are disconnected from "source"
        source->sub = NULL;

        // this invalidates sub, but that is desired for my class
    }
}

There is no issue with this so far. Instead the issue is that I wanted to have the "source" variable be a reference. This is now an issue, because that would make the constructor have the signature of the copy constructor.
Is there a way to tell the compiler that this shouldn't be considered the copy constructor? If this is possible should it even be done?

A: What you are trying to achieve is called a move constructor. In particular, this exact behavior is achieved by using std::unique_ptr.


text:
Q: WildFly Galleon: Web application as a feature-pack Does Galleon customize only the application server (WildFly) itself or allows to embed pre-deployed applications into it?
Can a web application be placed to WildFly as a feature pack?

A: Yes it can but currently this is a manual process to create such a feature pack.
You can take a look at https://github.com/wildfly-extras/wildfly-datasources-galleon-pack which creates postgresql datasource.
Not sure there is an application example currently available.


text:
Q: Lower bounds on dimensions of faithful representations of braid groups Let $B_n$ be the braid group on $n$ strands.  It's a theorem of Daan Krammer and Stephen Bigelow that there is a a faithful representation
$$B_n \to GL_{n \choose 2} \mathbb Z[t^{\pm}, q^{\pm}] $$
i.e. the range is the group of invertible matrices of rank $n \choose 2$ whose entries are from a Laurent polynomial ring over the integers.
My question for the community is, what kind of lower bounds are known on $k$ for there to be a faithful representation
$$B_n \to GL_k \mathbb C$$
Also, are there any analogous bounds for the same question but for mapping class groups?
I have a vague recollection that there are some good answers to this question but I forget who they're due to.  I also strongly suspect if you restrict to unitary representations there are some stronger results, maybe due to Stoimenow or Marin?
edit: Marin has a lower bound $k \geq n+1$ provided $n$ is sufficiently large.
edit2: Korkmaz has a theorem that says no representation from the genus $g$ mapping class group to $GL_n \mathbb C$ can be faithful, provided $n \leq 3g-3$. http://arxiv.org/abs/1108.3241

A: Slightly improving a theorem of Franks and Handel, Korkmaz proved that any representation from the genus $g$ mapping class group to $\text{GL}_n(\mathbb{C})$ is trivial if $n \leq 2g-1$.  This bound is sharp because of the standard symplectic representation.  See http://arxiv.org/abs/1104.4816.


text:
Q: MutableLiveData wrong value when accessing directly I have ViewModel:
class SharedViewModel : ViewModel() {
var connected = MutableLiveData(false)

fun setConnected(value: Boolean) {
    connected.postValue(value)
 }
}

When setting value:
viewModel.setConnected(true)

And then observing it like so:
viewModel.connected.observe(viewLifecycleOwner, {
Log.d(RTAG, "Connected: $it")
})

It works as expected. But sometimes I need acess the value directly and not observing the change like so:
 viewModel.setConnected(true)
 Log.d(RTAG, "Res: "+viewModel.connected.value) //printed old result, why?

Then I get old result, why is that?

A: postValue method doesn't change the value immediately. It should be used in a background thread. Try using setValue which should be invoked only on main thread and sets the value immediately.