text:
Q: wp_tag_cloud как удалить лишние ссылки категории Нужно убрать лишные ссылки категории. Откуда они вышли - непонятно.
Вообще, не должны были выходит ссылки категории.

По идее, хотел простой список тегов в виде:

tags-1

tags-2

tags-3

tags-4

tags-5

Версия WordPress 4.7.5 ru

A: Все, уже нашел ошибку, в одном месте забыл поставить знак =

сам создал ошибку по невнимательности
когда переопределял HTML разметку  в списках категории, если кому интересно код ниже
function wptuts_widgets_init() {
    register_sidebar( array(
        'name'          => __( 'Main Sidebar', 'wptuts' ),
        'id'            => 'sidebar-1',
        'description'   => __( 'Виджет в этой форме будет выводится во всех постах и на всех страницах.', 'wptuts' ),
        'before_widget' => '
',
        'after_widget'  => '
',
        'before_title'  => '

',
        'after_title'   => '

',
    ) );
}
add_action( 'widgets_init', 'wptuts_widgets_init' );

function wptuts_widgets_categories($args)
{
  $walker = new Walker_Categories_Wptuts();
  $args = array_merge($args, array ('walker' => $walker ) );
  return $args;
}

add_filter('widget_categories_args', 'wptuts_widgets_categories' );

class Walker_Categories_Wptuts extends Walker_Category
{
 /**
   * Starts the list before the elements are added.
   *
   * @since 2.1.0
   * @access public
   *
   * @see Walker::start_lvl()
   *
   * @param string $output Used to append additional content. Passed by reference.
   * @param int    $depth  Optional. Depth of category. Used for tab indentation. Default 0.
   * @param array  $args   Optional. An array of arguments. Will only append content if style argument
   *                       value is 'list'. See wp_list_categories(). Default empty array.
   */
  public function start_lvl( &$output, $depth = 0, $args = array() ) {
     parent::start_lvl( $output, $depth, $args);
  }

  /**
   * Ends the list of after the elements are added.
   *
   * @since 2.1.0
   * @access public
   *
   * @see Walker::end_lvl()
   *
   * @param string $output Used to append additional content. Passed by reference.
   * @param int    $depth  Optional. Depth of category. Used for tab indentation. Default 0.
   * @param array  $args   Optional. An array of arguments. Will only append content if style argument
   *                       value is 'list'. See wp_list_categories(). Default empty array.
   */
  public function end_lvl( &$output, $depth = 0, $args = array() ) {
    parent::end_lvl( $output, $depth, $args);
  }

  /**
   * Starts the element output.
   *
   * @since 2.1.0
   * @access public
   *
   * @see Walker::start_el()
   *
   * @param string $output   Passed by reference. Used to append additional content.
   * @param object $category Category data object.
   * @param int    $depth    Optional. Depth of category in reference to parents. Default 0.
   * @param array  $args     Optional. An array of arguments. See wp_list_categories(). Default empty array.
   * @param int    $id       Optional. ID of the current category. Default 0.
   */
  public function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
    /** This filter is documented in wp-includes/category-template.php */
    $cat_name = apply_filters(
      'list_cats',
      esc_attr( $category->name ),
      $category
    );

    // Don't generate an element if the category name is empty.
    if ( ! $cat_name ) {
      return;
    }

    $link = 'description ) ) {
      /**
       * Filters the category description for display.
       *
       * @since 1.2.0
       *
       * @param string $description Category description.
       * @param object $category    Category object.
       */
      $link .= 'title="' . esc_attr( strip_tags( apply_filters( 'category_description', $category->description, $category ) ) ) . '"';
    }

    $link .= '>';
    $link .= $cat_name;
    if ( ! empty( $args['show_count'] ) ) {
      $link .= ' ' . number_format_i18n( $category->count ) . '';
    }
    $link .= '';

    if ( ! empty( $args['feed_image'] ) || ! empty( $args['feed'] ) ) {
      $link .= ' ';

      if ( empty( $args['feed_image'] ) ) {
        $link .= '(';
      }

      $link .= 'term_id, $category->taxonomy, $args['feed_type'] ) ) . '"';

      if ( empty( $args['feed'] ) ) {
        $alt = ' alt="' . sprintf(__( 'Feed for all posts filed under %s' ), $cat_name ) . '"';
      } else {
        $alt = ' alt="' . $args['feed'] . '"';
        $name = $args['feed'];
        $link .= empty( $args['title'] ) ? '' : $args['title'];
      }

      $link .= '>';

      if ( empty( $args['feed_image'] ) ) {
        $link .= $name;
      } else {
        $link .= "';
      }
      $link .= '';

      if ( empty( $args['feed_image'] ) ) {
        $link .= ')';
      }
    }

    if ( 'list' == $args['style'] ) {
      $output .= "\t
term_id,
      );

      if ( ! empty( $args['current_category'] ) ) {
        // 'current_category' can be an array, so we use `get_terms()`.
        $_current_terms = get_terms( $category->taxonomy, array(
          'include' => $args['current_category'],
          'hide_empty' => false,
        ) );

        foreach ( $_current_terms as $_current_term ) {
          if ( $category->term_id == $_current_term->term_id ) {
            $css_classes[] = 'current-cat';
          } elseif ( $category->term_id == $_current_term->parent ) {
            $css_classes[] = 'current-cat-parent';
          }
          while ( $_current_term->parent ) {
            if ( $category->term_id == $_current_term->parent ) {
              $css_classes[] =  'current-cat-ancestor';
              break;
            }
            $_current_term = get_term( $_current_term->parent, $category->taxonomy );
          }
        }
      }

      /**
       * Filters the list of CSS classes to include with each category in the list.
       *
       * @since 4.2.0
       *
       * @see wp_list_categories()
       *
       * @param array  $css_classes An array of CSS classes to be applied to each list item.
       * @param object $category    Category data object.
       * @param int    $depth       Depth of page, used for padding.
       * @param array  $args        An array of wp_list_categories() arguments.
       */
      $css_classes = implode( ' ', apply_filters( 'category_css_class', $css_classes, $category, $depth, $args ) );

      $output .=  ' class="' . $css_classes . '"';
      $output .= ">$link\n";
    } elseif ( isset( $args['separator'] ) ) {
      $output .= "\t$link" . $args['separator'] . "\n";
    } else {
      $output .= "\t$link
\n";
    }
  }

  /**
   * Ends the element output, if needed.
   *
   * @since 2.1.0
   * @access public
   *
   * @see Walker::end_el()
   *
   * @param string $output Passed by reference. Used to append additional content.
   * @param object $page   Not used.
   * @param int    $depth  Optional. Depth of category. Not used.
   * @param array  $args   Optional. An array of arguments. Only uses 'list' for whether should append
   *                       to output. See wp_list_categories(). Default empty array.
   */
  public function end_el( &$output, $page, $depth = 0, $args = array() ) {
    parent::end_el( $output, $page, $depth, $args );
  }

}


text:
Q: Doing an array formula lookup I have a list of data like this:
Name   |    Number
Bob    |   300
Joe    |   200
Jane   |   400
Sisqo  |   450
Jill   |   500

There's about 62 rows of this, all numbers which can be different, some repeated. My goal is to basically add a column which contains all the list of people who are at 400 or above. So that it looks like this:
Name
Jane
Sisqo
Jill

What I have is:
{=iferror(INDEX($A$2:$B$6, SMALL(IF($B$2:$B$6 >= 400, $B$2:$B$6,), ROW(1:1)), 1), "")}

What I imagine this is doing:
1) The small function is looking in range b2:b6, and because this is an array formula, looks at each cell in B2:B6 to see if its greater or equal to 400.
2) I don't know exactly how, but I hope that the row function is finding the array of b2:b6 only if the value in the cell under consideration is greater than or equal to 400. If it doesn't find anything, nothing happens.
3) Then it runs the comparison small(b2:b6, 1) for the lowest value in that range. Then when copied down, because I'm using the row() function, it will be small(b2:b6, 2), small(b2:b6, 3) and so on.
At this point the row of the lowest number at 400 or below should be found.
So then the index function should read
index(a2:b6, 3, 1)

for the first one.Except I'm only getting
Name
Bob
Bob
So where is the error?

A: I prefer to use MATCH in an Array form:
=IFERROR(INDEX($A$2:$A$6,MATCH(1,(COUNTIFS($E$1:E1,$A$2:$A$6)=0)*($B$2:$B$6>=400),0)),"")

Being an array formula it must be confirmed with Ctrl-shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Single Linked List search in Python I want to search a value/character in a linked list and return the number of times the value/character is in the linked list. Also would it be easier if I just used recursion instead of tail recursion?
class MyList():
    __slots__=('head','size')

class Empty():
    __slots__=()

class NonEmpty():
    __slots__=('data','next')

def mkMyList():
    lst = MyList()
    lst.head = mkEmpty()
    lst.size = 0
    return lst

def mkEmpty():
    return Empty()

def mkNonEmpty(data,lst):
    node = NonEmpty()
    node.data  = data
    node.next = lst
    return node

def count(l, value, c = 0):
    l = mkMyList()
    if l.head != value:
        l.head = l.head.next
    if l.head == value:
        return count(l.head.next, value, c + 1)
    if l.size == 0:
        return c

When I try to test it, I get this:
count(s,'s',c= 0)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    count(s,'s',c= 0)
  File "C:\Users\Qasim\Desktop\Linked Lists.py", line 30, in count
    l.head = l.head.next
AttributeError: 'Empty' object has no attribute 'next'

\

A: Rather than use recursion, I would use the iterator pattern. Here is one way to do it in the context of your problem:
class LinkedList(object):

    class Node(object):
        __slots__ = ('prev', 'next', 'value')

        def __init__(self, prev=None, next=None, value=None):
            self.prev = prev
            self.next = next
            self.value = value

    def __init__(self, iterable=[]):
        self.head = LinkedList.Node() # dummy node
        self.tail = self.head
        self.size = 0
        for item in iterable:
            self.append(item)

    def __iter__(self):
        current = self.head
        while True:
            if current.next is not None:
                current = current.next
                yield current.value
            else:
                raise StopIteration

    def append(self, value):
        self.tail.next = LinkedList.Node(prev=self.tail, value=value)
        self.tail = self.tail.next
        self.size += 1

    def pop(self):
        if self.size > 0:
            value = self.tail.value
            self.tail = self.tail.prev
            self.tail.next = None
            self.size -= 1
            return value
        else:
            raise IndexError('pop from empty list')

    def count(self, value):
        cumsum = 0
        for item in self:
            if item == value:
                cumsum += 1
        return cumsum

By my defining a Python special method __iter__, one can sequentially access the elements of a LinkedList in the following manner:
l = LinkedList([1, 2, 3, 3, 3, 4, 5])
for value in l:
    print(value)

which then makes the desired method count straight-forward to implement.
Note that I have used the Python generator syntax to implement __iter__, you can read about generators and the yield statement here.

A: Tracing your code:
 l = mkMyList() # => head = Empty()
 if l.head != value: # True since head is Empty()
     l.head = l.head.next # Empty does not have a ".next" attribute

This is what the Traceback is telling you.
EDIT: Two more things: (1) I'm not sure why count is even calling mkMyList when it seems your intent is to pass it the list, l, in the function args.  (2) I'm guessing you want to put the size-check if statement at the top of this function:
if l.size == 0:
    return c

A: The issue I see is that the list in count is never initialized properly. In mkMyList(), the head element is set to and Empty, which has no next attribute. In count(), you only use mkMyList(). This means that l.head is an Empty, and there's no way it could have a next attribute. To fix this, I would recommend instantiating the list l using the given input.
With regards to the question about recursion: no, there is very little difference in terms of composing a tail recursive function versus a regularly recursive function.


text:
Q: Integration of $\iint_{\Sigma}(\vec{a}\cdot \vec{x})^2dS(x)$ Let $\Sigma\subset R^3$  be the sphere of radius $R>0$ centered at the origin and let $\vec{a}=a_1\vec{e_1}+a_2\vec{e_2}+a_3\vec{e_3}$. I have to compute these integrations :
$$\iint_{\Sigma}(\vec{a}\cdot \vec{x})^2dS(x),\qquad \iint_{\Sigma}e^{\vec{a}\cdot \vec{x}}dS(x)$$
After spending some time on this problem, I decided to look at the solution, and its states the following :

we can make a change of coordinate system from $\vec{e_1},\vec{e_2},\vec{e_3}$ to the system $\vec{\hat{e_1}},\vec{\hat{e_2}},\vec{\hat{e_3}}$ thanks to the transformation (Houseolder matrix) :
  $$\vec{a}=\mid a\mid \vec{\hat{e_3}}$$
  And then the integration becomes :
  $$\iint_{\Sigma}(\vec{a}\cdot \vec{x})^2dS(x)=R^2\int_{0}^{2\pi}\int_{0}^{\pi}(\mid \vec{a}\mid R \cos \phi )^2\sin \phi d\phi d\theta )$$

And I don't understand how is it possible to make such a coordinate change and why it leads to this ? It would be really nice if someone could explain me what happened and how to deal with the general case ?

A: This is due to the rotational invariance of the scalar product and the rotational symmetry of the sphere. The value of the integral depends only on the radius $R$ of $\Sigma$ and the length $|a|$ which is equal to the norm of the functional $x\mapsto a\cdot x$. For the calculation we may therefore assume right away that $a=|a|{\bf e}_3$ and then use spherical coordinates. No matrix computations are needed.


text:
Q: How to create bash alias on Ubunth WSL when username has space and apostrophe I'm trying to create the following alias in Ubuntu WSL:
alias windocs='cd /mnt/c/Users/Firstname L'astname/Documents/'

My username is unfortunately Firstname L'astname, including the space and apostrophe.
I've tried using backslashes:
alias windocs='cd /mnt/c/Users/Firstname\ L\'astname/Documents/'

But bash still interprets the apostrophe as the end of the string, resulting in the following error:
-bash: .bash_aliases: line 11: unexpected EOF while looking for matching `''
-bash: .bash_aliases: line 12: syntax error: unexpected end of file

I've also tried encapsulating the username in double-quotation marks:
alias windocs='cd /mnt/c/Users/"Firstname L'astname"/Documents/'

And I get the same error.
How can I write this alias so that it works? It's a pain having to cd all the way to the Documents folder every time.

A: Single quotes in a single-quoted string aren't escapable, but luckily, you can just use double quotes around the alias definition and then (escaped) double quotes around the directory name:
alias windocs="cd \"/mnt/c/Users/Firstname L'astname/Documents/\""

Alternatively, you could symlink that directory into your Linux home directory:
ln -s "/mnt/c/Users/Firstname L'astname/Documents/" ~/docs

And then, simply cd docs (or cd ~/docs, if you're not in your home dir) will take you there.

A: Well, I should have looked this up first.
I put the entire string in double-quotation marks as per this stackoverflow answer:
alias windocs="cd /mnt/c/Users/Firstname\ L\'astname/Documents/"

and it works now. This is because there is no escape mechanism from single-quote strings, but there is for double quote strings (as per the other answer).

A: For Windows Subsystem for Linux (WSL) only, Windows side environment variables can be mapped into $WSLENV environment variable in WSL side. For example, the /mnt/c/Users/username/ in Windows side is saved as %USERPROFILE% environment variable.
To do this, first add the variable in Windows by running this command as administrator in Command Prompt
setx WSLENV USERPROFILE

Then add the alias in .bashrc (or similar files). For example,
alias windocs='cd $(wslpath $USERPROFILE/Documents)'

Here wslpath translates Windows style path (backward slash) to *NIX style path (forward slash). In schematics,
   Windows        <--->      WSL
C:\Users\username <--->  /mnt/c/Users/username
USERPROFILE       <--->  WSLENV

Read Share Environment Vars between WSL and Windows blog for further information.


text:
Q: Extraer Coincidencias de 2 listas en base a 1 lista y crear una nueva lista Soy nuevo en python y estoy intentando crear un lista tipo string, en base a los ingresos de 3 listas de de la siguiente manera:

sin embargo al intentar imprimirlas no me muestra la salida como la de la imagen. Ya que en la lista Ganadora hay valores que se encuentran en la lista de Alejandro y Carolina, Debería Imprimirme cada coincidencia con una letra "E" de empate, pero mi código solo me muestra la última. ¿Alguien podría ayudarme diciéndome que debo corregir o que debo agregar? Muchas gracias.
# Declarar las escuderias favoritas de Alejandro y Carolina Respectivamente.
escuderias_fav_alejandro = "RAIFZ"
escuderias_fav_carolina = "UZEOF"

ingreso_esc_fav_alejandro = input("Ingrese la lista de escuderías favoritas de Alejandro:\n")

ingreso_esc_fav_carolina = input("Ingrese la lista de escuderías favortias de Carolina: \n")

ingreso_ganadores_tempo = input("Ingrese los ganadores de la temporada: ")
posibles_ganadoras = ingreso_ganadores_tempo

for i in ingreso_esc_fav_alejandro:
    for j in ingreso_ganadores_tempo:
        if(i==j):
            print("A", end="")
            break

for k in ingreso_esc_fav_carolina:
    for j in ingreso_ganadores_tempo:
        if(k==j) and i:
            print("C" , end="")
            break

for j in i and k:
    print("E", end="")
    break

A: Tu problema te dice que cada participante va a tener algunas letras que le darán puntos, si la letra esta solamente en un participante se le suma un punto al participante, si esta en ambos se le suma un punto a ambos, si no esta en ninguno no se le suma puntos a nadie, y luego se tiene que estar verificando en cada turno quien es el ganador. Tu utilizas innecesariamente 2 ciclos for pero en realidad solo se necesita 1, esto ya que tenemos la hermosa sintaxis de verificar si un elementos esta en otro con x in list se puede verificar si un elemento esta en una lista o también se puede verificar si un caracter esta en un string "A" in string, dado que siempre se tiene que estar verificando al ganador, crearé una función que se encargue de determinar al ganador de acuerdo al punta. También usare un diccionario como estructura de dato, esto para tener los datos mas ordenados dado que se tiene que almacenar el puntaje de ambos.
función para determinar ganador
def winner(puntos_a,puntos_c):
    #si los puntos de alejandro es mayor que los de carolina
    if puntos_a>puntos_c:
        return "A" #gana alejandro
    elif puntos_a==puntos_c: #si son iguales
        return "E" #empate
    else: #de lo contrario
        return "C" #gana carolina

diccionario con participantes
participantes = {"Alejandro":{"fav":"RAIFZ", "puntos":0}, "Carolina":{"fav":"UZEOF","puntos":0}}

#con inputs
#fav_alejandro = input("Ingrese las favoritas de alejandro: ")
#fav_carolina = input("Ingrese las favoritas de carolina: ")
#participantes = {"Alejandro":{"fav": fav_alejandro , "puntos":0}, "Carolina":{"fav": fav_carolina,"puntos":0}}

código principal
Como dije, solo utilizaremos un ciclo for para iterar en los ganadores de la carrera.
#ganadores_carrera  = input("Ingrese los ganadores de la carrera: ")
ganadores_carrera = "IHZOWFEI"

#accedemos a los participantes, esto para no escribir tanto
alejandro = participantes["Alejandro"]
carolina = participantes["Carolina"]

#accedemos a los favoritos del participante, igual para no escribir tanto
fav_alejandro = alejandro["fav"]
fav_carolina = carolina["fav"]

for g in ganadores_carrera:
    #si la letra solo esta en alejandro
    if g in fav_alejandro and g not in fav_carolina:
        alejandro["puntos"]+=1 #sumamos un punto
        #comprobamos ganador
        #agregamos end="" para que se muestre en horinzontal
        print(winner(alejandro["puntos"],carolina["puntos"]),end="") #le pasamos los puntos de ambos
    #si la letra solo esta en carolina
    elif g in fav_carolina and g not in fav_alejandro:
        carolina["puntos"]+=1 #sumamos un punto
        #verificamos al ganador
        print(winner(alejandro["puntos"],carolina["puntos"]),end="")
    #si esta en ambos
    elif g in fav_alejandro and g in fav_carolina:
        #sumamos un punto a cada uno
        carolina["puntos"]+=1
        alejandro["puntos"]+=1
        #comprobamos al ganador
        print(winner(alejandro["puntos"],carolina["puntos"]),end="")
    #si no esta en ninguno
    elif g not in fav_alejandro and g not in fav_carolina:
        #comprobamos al ganador
        print(winner(alejandro["puntos"],carolina["puntos"]),end="")

resultado
AAAEEECE

En caso lo quieras hacer con contadores, tendríamos que declara un contador para cada participante, para este caso hare el código sin usar un diccionario
#delcaramos las variables
fav_alejandro = "RAIFZ"
fav_carolina = "UZEOF"
ganadores_carrera = "IHZOWFEI"

#con inputs
# fav_alejandro = input("Ingrese las favoritas de alejandro: ")
# fav_carolina = input("Ingrese las favoritas de carolina: ")
# ganadores_carrera = input("Ingrese los ganadores")

La función para determinar al ganador se quedará igual. Ahora en vez de sumar 1 al valor del diccionario lo haremos al contador del participante, lo mismo para obtener el valor.
#iniciamos los puntos con 0
points_alejandro = 0
points_carolina = 0

for g in ganadores_carrera:
    #si la letra solo esta en alejandro
    if g in fav_alejandro and g not in fav_carolina:
        points_alejandro+=1
        #verifiacmos al ganador
        print(winner(points_alejandro,points_carolina),end="") #end="" para que se muestre horizontal
    #si la letra solo esta en carolina
    elif g in fav_carolina and g not in fav_alejandro:
        points_carolina+=1
        print(winner(points_alejandro,points_carolina),end="")
    #si esta en ambos
    elif g in fav_alejandro and g in fav_carolina:
        #sumamos el punto a ambos
        points_carolina+=1
        points_alejandro+=1
        #verifiacmos al ganador
        print(winner(points_alejandro,points_carolina),end="")
    #si no esta en ninguno
    elif g not in fav_alejandro and g not in fav_carolina:
        #verifiacmos al ganador
        print(winner(points_alejandro,points_carolina),end="")

utilicé contadores tal y como me pediste en los comentarios, si no deseas utilizar diccionarios y prefieres hacerlo de esta forma no hay problema, solo que esto también se puede resumir usando otra estructura de dato como listas [] o tuplas ()  o una mezcla de ambos, una lista de tuplas [(participante1,point),(participante2,points)]. Te dejo eso para que juegues y aprendas más :D


text:
Q: SQL Group By condition I have following SQL query for start:
SELECT CASE
           WHEN CAST(tDate as DATE) < CAST(GETDATE() as date) -- if older then Today
           THEN DATEADD(dd,-1,CAST(GETDATE() as date))        -- assgin yesterday's date
           ELSE CAST(tDate as date)                           -- use the date
       END as tDate,
       SUM(tDuration-ISNULL(tDone,0)) as tToDo FROM tTable

    WHERE .....conditions.....

    GROUP BY tDate
    ORDER BY tDate

I have two problems with that:
I tried to SUM() all of the past task's duration to yesterdays date, which I succeed, but GROUP BY wouldn't sum them into one date, it leaves them at separate lines. I don't know why, when I cast datetime input to date and they should have equal value.
I tried to use CONVERT instead of CAST and to separate the CASE processing into sub-query with no improvements.

A: Replace your query with this:
SELECT CASE
           WHEN CAST(tDate as DATE) < CAST(GETDATE() as date) -- if older then Today
           THEN DATEADD(dd,-1,CAST(GETDATE() as date))        -- assgin yesterday's date
           ELSE CAST(tDate as date)                           -- use the date
       END as tDate,
       SUM(tDuration-ISNULL(tDone,0)) as tToDo FROM tTable

    WHERE .....conditions.....

    GROUP BY CASE
           WHEN CAST(tDate as DATE) < CAST(GETDATE() as date) -- if older then Today
           THEN DATEADD(dd,-1,CAST(GETDATE() as date))        -- assgin yesterday's date
           ELSE CAST(tDate as date)                           -- use the date
       END
    ORDER BY tDate


text:
Q: Detect firebug opening and closing Does anybody have a way to detect Firebug opening and closing.
I know you can do the following:
if (window.console && window.console.firebug) {
  //Firebug is enabled
}

but this only detects the firebug console on page load. What I want to do is on a page where firebug is not open, detect the opening of the firebug console.
I've tried the following, but with no luck
setInterval(function(){
  if(window.console && window.console.firebug){
    ...
  else
    ...
}, 1000);

Any help greatly appreciated.
Matt

A: Simply.. You cant. The firebug window not just an another couple of div element on your page.

A: The Firebug window.console object is created just before the first Javascript in the page is executed but only if Firebug is active for the page before the first JS and if the user has the Firebug Console panel enabled.
In other words, from within the page you can only detect if the Console is enabled. But for your purposes that should be enough.
We should delete the console property if a user turns Firebug off for a page.  I don't know if we actually do that.

A: you can make it as
var t = setTimeout("CheckFireBug()",10000);
function CheckFireBug() {
    var t = setTimeout("CheckFireBug()",10000);
    if (window.console && window.console.firebug) {
        //Firebug is enabled
        console.debug('Firebug is enabled.');
    } else {
        //Firebug is not enabled
        console.debug('Firebug is not enabled.');
    }
}

A: Firebug overwrites the console property of window, so you may detect it like so:
var _console = window.console;
Object.defineProperty(window, 'console', {
    set: function (x) {
        if (x.exception) { // check if this is actually Firebug, and not the built-in console
            alert('Firebug on');
        }
        _console = x;
    },
    get: function () {
        return _console;
    }
});

The problem is that this object remains when Firebug is closed, so you can't detect that. Maybe there's some other way but I can't find it ATM.
Details:
It's not possible to access Firebug's execution context from document scripts, so we're limited to waiting for Firebug to access some of window's properties, which does not seem to happen when you close Firebug. Here's some of the events during shutdown, taken with FBTrace:

I've searched the stacktrace for "leaks" to window, but couldn't find any.

A: console.table() returns "_firebugIgnore" if firebug is running.
if( window.console && (console.firebug ||
   console.table && /firebug/i.test(console.table()) ))
{
    alert('Firebug is running');
}else{
    alert('Firebug is not found');
}

A: If you only want to detect Firebug opening/closing you can check window resize/blur events.


text:
Q: "Flash" an icon in an interface with React I am trying to emulate a behavior that is on YouTube. When switching between a "Playing" and a "Paused" state, it will flash an icon corresponding to the new state. Here is an example:

I find that there are a few "messy" ways to handle this. For example, using a setTimeout in componentDidUpdate
componentDidUpdate(props, { isPlaying }) {
  if (this.state.isPlaying !== isPlaying) {
    this.setState({ showIcon: true }, () => {
      setTimeout(() => {
        this.setState({ showIcon: false });
      }, 300);
    });
  }
}

This seems a little superfluous, in my opinion, and I am sure there is a better way to accomplish this.
How can you briefly show an element on the screen for some amount of time?


text:
Q: Transition Functions of the Weighted Projective Space $\mathbb{P}^{2}_{\{3,2,1\}}$. I am trying to find the transition functions of the weighted projective space $\mathbb{P}^{2}_{\{3,2,1\}}$. Bear with, I am very new to algebraic geometry.
To my understanding, $\mathbb{P}^{2}_{\{3,2,1\}}$ is defined as the quotient of $\mathbb{C}^{3}\setminus{\{0\}}$ by the equivalence relation:
$$
(z_{0},z_{1},z_{2})\sim(\lambda^{3}z_{0},\lambda^{2}z_{1},\lambda^{1}z_{2})
\text{ , with }\lambda\in\mathbb{C}^{*}\text{.}
$$
As far as I understand, instead of having charts as in differential geometry, in algebraic geometry we look at "coordinate patches". The obvious guess (which clearly covers $\mathbb{P}_{\{3,2,1\}}$), is:
\begin{align*}
&
U_{1}
=
\{
[1:z_{1}:z_{2}]
|
z_{1},z_{2}\in\mathbb{C}
\}
\\
&
U_{2}
=
\{
[z_{0}:1:z_{2}]
|
z_{0},z_{2}\in\mathbb{C}
\}
\\
&
U_{3}
=
\{
[z_{0}:z_{1}:1]
|
z_{0},z_{1}\in\mathbb{C}
\}
\\
\end{align*}
where we have used square brackets to denote equivalence classes.
Then as far as I understand, these patches are supposed to be isomorphic to (some quotient of?), affine $2$-space, in the same way we would expect homeomorphisms with $\mathbb{R}^{2}$ for manifolds.
The obvious isomorphisms are:
\begin{align*}
&
\phi_{1}:U_{1}\to\mathbb{A}^{2}
\text{ , }
[1:z_{1}:z_{2}]
\mapsto
(z_{1},z_{2})
\\
&
\phi_{2}:U_{2}\to\mathbb{A}^{2}
\text{ , }
[z_{0}:1:z_{2}]
\mapsto
(z_{0},z_{2})
\\
&
\phi_{3}:U_{3}\to\mathbb{A}^{2}
\text{ , }
[z_{0}:z_{1}:1]
\mapsto
(z_{0},z_{1})
\end{align*}
with inverses:
\begin{align*}
&
\phi_{1}^{-1}:\mathbb{A}^{2}\to U_{1}
\text{ , }
(x,y)\mapsto[1:x:y]
\\
&
\phi_{2}^{-1}:\mathbb{A}^{2}\to U_{2}
\text{ , }
(x,y)\mapsto[x:1:y]
\\
&
\phi_{2}^{-1}:\mathbb{A}^{2}\to U_{2}
\text{ , }
(x,y)\mapsto[x:y:1]
\\
\end{align*}
which are also locally given by polynomials.
The transition functions should then be given by $\tau_{ij}=\phi_{j}\circ\phi_{i}^{-1}$.
This means that:
$$
\tau_{12}(x,y)
=
(x^{-3/2},x^{-1/2}y)
\text{ , and }
\tau_{23}(x,y)
=
(y^{-3}x,y^{-2})
\text{.}
$$
If we now write the components as $\tau_{ij}(u_{i,1},u_{i,2})=(u_{j,1},u_{j,2})$, this says that:
\begin{align*}
&
u_{1,1}=u_{2,1}^{-2/3}
\text{ , }
u_{1,2}=u_{2,2}u_{2,1}^{-1/3}
\\
&
u_{2,2}=u_{3,2}^{-1/2}
\text{ , }
u_{2,1}=u_{3,1}u_{3,2}^{-3/2}
\end{align*}
This seems fine to me, but the answer given in the paper I'm reading is:
\begin{align*}
&
u_{1,1}=u_{2,1}^{-1}
\text{ , }
u_{1,2}^{3}=u_{2,2}u_{2,1}^{-2}
\\
&
u_{2,2}=u_{3,2}^{-1}
\text{ , }
u_{2,1}^{2}=u_{3,1}^{3}u_{3,2}^{-1}
\end{align*}
I have gone over my workings several times and can't find any issues, so I am probably misunderstanding something fundamental. Any help would be much appreciated.
EDIT:
Thanks to reuns' comment, I have realised that $U_{1}$ and $U_{2}$ are not simply affine space. To see this, note that for $\zeta_{n}$ an n'th root of unity, $[1:z_{1}:z_{2}]=[1:\zeta_{3}^{2}z_{1}:\zeta_{3}z_{2}]$. This means that for the map $\phi_{1}$ to be well defined we must take the quoitent by $\mathbb{Z}_{3}$ with this action. This gives:
\begin{align*}
&
U_{1}\cong\mathbb{A}^{2}/(z_{1},z_{2})\sim(\zeta_{3}^{2}z_{1},\zeta_{3}z_{2})
\\
&
U_{2}\cong\mathbb{A}^{2}/(z_{0},z_{2})\sim(\zeta_{2}z_{0},\zeta_{2}z_{2})
\\
&
U_{3}\cong\mathbb{A}^{2}
\end{align*}
Since my transition functions are invariant under these actions, I am still unsure about how to obtain the form given in my reference.


text:
Q: sonarqube v4.3 cobertura reports I was using sonar 4.2 and sonar-runner 2.3 and cobertura plugin.
After upgrade sonar to 4.3 and sonar-runner to 2.4, all my projects are with 0% coverage.
On log contains:
14:57:28.135 INFO  - Sensor JaCoCoSensor...
14:57:28.135 INFO  - Project coverage is set to 0% as no JaCoCo execution data has been dumped: C:\Desenvolvimento\shared_view\SILCE\TE151\03-Implementacao\Componentes\caixa-util\target\jacoco.exec
14:57:28.464 INFO  - Sensor JaCoCoSensor done: 329 ms
14:57:29.089 INFO  - Execute decorators...

My sonar-project.properties:
#http://docs.codehaus.org/display/SONAR/Analysis+Parameters

# required metadata
sonar.projectKey=br.gov.caixa:caixa-util
sonar.projectName=caixa-util
sonar.projectVersion=1.000

# path to source directories (required)
sonar.sources=src

# path to test source directories (optional)
sonar.tests=test

# path to project binaries (optional), for example directory of Java bytecode
sonar.binaries=build/classes

# optional comma-separated list of paths to libraries. Only path to JAR file and path to directory of classes are supported.
sonar.libraries=../caixa-lib/lib/cobertura/1.9.4.1/cobertura.jar,../caixa-lib/lib/cache/ehcache-core-2.5.0.jar

# Uncomment this line to analyse a project which is not a java project.
# The value of the property must be the key of the language.
#sonar.language=cobol

# Additional parameters
#my.property=value

#clearcase
sonar.scm.url=scm\:clearcase|caixa-util

#coverage
#teste de cobertura
sonar.java.coveragePlugin=cobertura
sonar.dynamicAnalysis=reuseReports
sonar.junit.reportsPath=build/docs-temp/junit
sonar.cobertura.reportPath=build/docs/cobertura-reports/coverage.xml

A: We have an issue on Java 2.2 and Cobertura 1.6 : The reuse report on Cobertura 1.6 is not working and so you will have to wait for fix version java 2.2.1 and cobertura 1.6.1 to be released (This will happen shortly, vote is open on SonarQube dev mailing list : http://sonarqube.15.x6.nabble.com/sonar-dev-VOTE-Cobertura-version-1-6-1-td5024837.html
and http://sonarqube.15.x6.nabble.com/sonar-dev-VOTE-Java-Plugin-version-2-2-1-td5024834.html
).
Please note that with these version, as the tests won't be executed by SonarQube analysis anymore, you will have to generate the cobertura reports yourself : check http://docs.codehaus.org/display/SONAR/Cobertura+Plugin


text:
Q: Delphi - Disable [x] Close Button in VCL Styles I'd like disable [X] close Button with VCL Style in DX Berlin.
Wy this code do not work wiht VCL Style?
EnableMenuItem(GetSystemMenu(Form3.Handle, LongBool(False)),SC_CLOSE, MF_BYCOMMAND or MF_GRAYED);

A: If you set the action in the FormClose event to caNone, when you try to close the form (clicking on the red cross) nothing is going to happen. In this way you can disable the button.
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
 //You cannot type only caNone, otherwise you'll get a compiler error
 Action := TCloseAction.caNone;
end;

You can find caNone in System.UITypes; read the documentation for more information.

A: When using VCL Styles by default style affect the appearance of fonts being used, client area of your form and also your forms border (this also include minimize, maximize and close buttons).
So from what I see you have two options:

*

*You could change StyleElements property of your form to [seFont, seClient] which means that style will only be applied to used fonts and client area of your form but the border area of your form would be unstyled and rendered by OS.

*You modify the style at runtime in order to achieve desired effect. Unfortunately I don't have enough experience with Styles to present you with an example of how to achieve this.


text:
Q: Is DbContext thread safe? I was wondering if the DbContext class is thread safe, I am assuming it's not, as I am currently executing paralell threads that access the DbContext in my application and I am getting a host of locking exceptions and other things that look like they may be thread related.
Until recently I wasn't getting any errors...but until recently I wasn't accessing the DbContext in the threads.
If I am right, what would people suggest as a solution?

A: It's not thread safe. Simply create a new instance of DbContext in you thread.

A: No it is not thread safe - whole EF is not thread safe because EF context should never be shared.

A: Edited - old answer below.
I now always use this pattern with DbContext:
using(var db = new LogDbContext())
{
    // Perform work then get rid of the thing
}

My approach of one per Request Thread meant cached objects in the DbContext would stick around and become stale even while other DbContext instances were writing new values to the actual database behind it. This would create some strange issues of for example one request performing an insert and the next request for the list coming in on a different thread that had a cached, stale list of the data for that query.
There are approaches that make the below work and even improve performance  of many-reads/few-writes style apps, but they take more design and strategy than the much simpler pattern above.
Update
I also use a useful helper method for library methods, like logging calls. Here's the helper method:
    public static async Task Using(Db db, Func<Db, Task> action)
    {
        if (db == null)
        {
            using (db = new Db())
            {
                await action(db);
            }
        }
        else
        {
            await action(db);
        }
    }

With this I can easily write code that takes an optional existing DbContext, or instantiates one inside a using context, depending on how it happens to be called.
For example, while working with a DbContext I might load some data, log some info, and then save that data - it's best to do this all with the same DbContext from a performance perspective. On the other hand I might also want to log something in response to a simple action, and neither load nor write any other data. By leveraging the above method I can have just the one logging method that works whether you want to work inside an existing DbContext or not:
public async Task WriteLine(string line, Db _db = null)
{
    await Db.Using(_db, db => {
        db.LogLines.Add(new LogLine(line));
        await db.SaveChangesAsync();
    });
}

Now this method call can be called inside or outside of an existing DbContext and still behave the right way, instead of having to have 2 versions of this and every other convenience logging method or other utility method I have, and instead of having to know and plan for the context of every call that will ever be made to them or their callers. This basically returns to me one of the benefits of the below threadstatic strategy where I didn't have to worry about when exactly the db opened in utility calls that should be worried about it.
Old answer
I usually handle thread-safety with EF DbContext like so:
public class LogDbContext : DbContext
{
    . . .

    [ThreadStatic]
    protected static LogDbContext current;

    public static LogDbContext Current()
    {
        if (current == null)
            current = new LogDbContext();

        return current;
    }

    . . .
}

With this in place I can get a DbContext for this thread like so:
var db = LogDbContext.Current();

It's important to notice that since each DbContext keeps its own local cache, each thread will now have its own separate cache of entity objects, which can introduce some crazy behavior if you're not prepared for it. However, creating new DbContext objects can be expensive, and this approach minimizes that cost.


text:
Q: I want to get a 'INT' value from a DB::Select get() I want to make a simple login and redirect each user to their private page, so each user will have their own page. Like www.example.com/user1.
This is for my new Application that I'm developing in this job.
public function login(request $req){
    $username = $req->input('username');
    $password = $req->input('password');
    $type = 1;
    $checklogin = DB::table('users')->where(['username'=>$username,'password'=>$password])->get();
    $checktype = DB::table('users')->where(['username'=>$username,'password'=>$password,'type'=>$type])->get();
    $url2 = DB::table('users')->where(['username'=>$username,'password'=>$password])->get('id');
    if(count($checklogin) >0){
        if (count($checktype) ==1) {
            header("Location: /admin/$url2", true, 301);
            exit();
        }else{
            if ($url2 == 4) {
                echo "$url2";
            }
        }
    }else{
        return view('loginfailed');
    }
}
}

The url that is redirecting is: "http://localhost:8000/admin/[%7B%22id%22:2%7D]"

A: You can fetch id as,
// fetching 1 record and then id of it
$url2 = DB::table('users')->where(['username'=>$username,'password'=>$password])->first()->id;

A: public function login(request $req){
    $username = $req->input('username');
    $password = $req->input('password');
    $checklogin = DB::table('users')->select('type')->where(['username'=>$username,'password'=>$password])->get()->first();

    if(count($checklogin){
        if ($checklogin->type ==1) {
            header("Location: /admin/$url2", true, 301);
            exit();
        }elseif ($checklogin->type == 4) {
                //do something else
        }
    }else{
        return view('loginfailed');
    }
}
}


text:
Q: Change "Request Headers"(Post Protocol) using FiddlerScript how can I change the "Request Headers"(Post Protocol) using FiddlerScript, for clarification please take a look at this:

It should be somewhere here ?
oSession.oRequest["..."] = "...";

But I don't know the correct key for oRequest.

A: Ok, I solved it by my self: it should be oSession.oRequest.headers.RequestPath="somepath"; and another statement oSession.oRequest.headers.HTTPMethod...


text:
Q: Getting error in TPU with python mnist_tpu.py --use_tpu=false --tpu='' I try to run this code from tensorflow git: mnist_tpu with
python mnist_tpu.py --tpu=''
python mnist_tpu.py --use_tpu=false --tpu=''

but all the time I get the following error:
AttributeError: module 'official.mnist.mnist' has no attribute 'create_model'

I don't know where the create_model method is defined. I have the feelin the docu is still lacking some info.
Any ideas? Thanks in advance.

A: 'create_model' is defined in mnist.py, which is present alongside with mnist_tpu.py. Confirm that you have that file from github: https://github.com/tensorflow/models/blob/master/official/mnist/mnist.py
And it will work.


text:
Q: React Native Search bar position New to RN. I am displaying a Google map and a search bar.
Problem is that the search bar is under the status bar.
How can I adjust this to be below the status bar at least?
<View>
        <StatusBar backgroundColor="rgba(1.0, 0, 0, 0.2)" translucent />
        <SearchBar
          ref='searchBar'
          placeholder='Find me'
          barStyle="black"
          showsCancelButtonWhileEditing={false}
        />
        <MapView
          provider={ PROVIDER_GOOGLE }
          style={ styles.container }
          initialRegion={{
            latitude: 32.815013,
            longitude: -117.273404,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}
        />
      </View>

A: If this issue replicates only in iOS you could check the platform to apply the correct styling.
<View style={styles.containerStyle}>
    <StatusBar backgroundColor="rgba(1.0, 0, 0, 0.2)" translucent />
    <SearchBar
      ref='searchBar'
      placeholder='Find me'
      barStyle="black"
      showsCancelButtonWhileEditing={false}
    />
    <MapView
      provider={ PROVIDER_GOOGLE }
      style={ styles.container }
      initialRegion={{
        latitude: 32.815013,
        longitude: -117.273404,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
      }}
    />
</View>

const styles = StyleSheet.create({
    containerStyle: {
        marginTop: Platform.OS === 'iOS' ? 20 : 10
    }
})

A: You can use SafeAreaView
Just wrap your entire view with SafeAreaView.It automatically adds space on IOS devices.
<SafeAreView style={{flex:1}}>
<View>
        <StatusBar backgroundColor="rgba(1.0, 0, 0, 0.2)" translucent />
        <SearchBar
          ref='searchBar'
          placeholder='Find me'
          barStyle="black"
          showsCancelButtonWhileEditing={false}
        />
        <MapView
          provider={ PROVIDER_GOOGLE }
          style={ styles.container }
          initialRegion={{
            latitude: 32.815013,
            longitude: -117.273404,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}
        />
      </View>
</SafeAreaView>


text:
Q: how to call a javascript function on radio button's 'checked' property? I have N number of radio button groups in the page with auto generated names.
I want to call a javascript function as the value of the checked property.  THIS LINE EXCLUDED AFTER EDIT ( Depending on the return value, the radio button needs to  be checked or unchecked.)
<input type="radio" name="auto_generated_name" value="some_value" checked="test_check(args);" />

and the javascript function is
function test_check(params) {
    if(conditions){
        return true;
    }
    else
        return false;
}

But that does not work. Whatever value I assign to 'checked' property, be it any javascript function or any string etc, the radio button becomes checked.
How can I achieve my goal?
EDIT:
 <input type="radio" name="auto_generated_name" value="somevalue" onclick="test_check(args)"/>

4 radio buttons make a group. such N radio groups have html class names in this way :  button_group_1, button_group_2, button_group_3, button_group_4 etc.
The 'args' need to be these class (i.e. radio button group) names and the corresponding values (from value="1", value="2", value="3" and value="4" ).
Cookies with the class names and values will be created inside the javascript function.
On page refresh, cookies matching with the class names will be checked and depending on the existence of the corresponding cookies, the radio button will be checked or unchecked.
How to achieve the goals/

A: Assuming you are using jQuery, use the change event: http://api.jquery.com/change/

A: try this:
Here I user a custom attribute to input named groupname. In OP's case groupname="<?php echo $radio_button_group_name; ?>". Then checking the value of this attribute OP can assign checked attribute value.
<input type="radio" name="r1" groupname="gr1"/>
<input type="radio" name="r2" groupname="gr2"/>

$('input:radio').each(function() {
    if ($(this).attr('groupname') == 'gr1') {
        $(this).attr('checked', true);
    } else {
        $(this).attr('checked', false);
    }
});

A: The checked attribute is simply a boolean value to indicate whether the radio button should be checked, it cannot contain script, or a reference to a scripting function. Any value in the attribute will cause the radio button to be checked.
Without knowing what mechanism you are using to check each radio button - I can see an args variable but don't know what type this is - it's going to be tricky to write some code for you.
If you can make args into an array of values, then something along the lines of the following should work for you:
var args = new Array(true,false,true)

$.each(args, function(index, value) {
    $("INPUT[type=radio]").eq(index).attr("checked", value)
});

Here's a fiddle to show what I mean more clearly

A: check this output, valid args is 'aa'.
http://jsfiddle.net/X7rcC/1
html:
<input type="radio" name="auto_generated_name" value="some_value1" checked="bb" />

js:
$(function() {
    var radios = $("input[type='radio']");
    $.each(radios, function(index, value){
        var args = value.attributes[1].nodeValue;
       test_check(args, value);
    })

});

function test_check(params, value){

    if(params == "aa"){
     $(value).attr("checked",true);
    }else
     $(value).attr("checked",false);

}

A: You cannot use a checked attribute this way, because anything as the value will be the same as checked=true Even just checked checks a radio button. What you should do is use a custom attribute which will create the checked attribute:
<input type="radio" name="auto_generated_name" value="some_value" needs_check="param">

<script>
  // Do test_check on param for each input
  $('input:radio').each(function()
  {
    var radio = $(this);
    var param = radio.attr('needs_check');

    var condition = test_check(param);

    radio.attr('checked', condition);
  });

  function test_check(param)
  {
    return true or false based on param
  }
</script>

A: Your question really boils down to:

How can I set the value of a checkbox when the page first loads? (Using a parameter stored with the checkbox)

The key insights are:

*

*you can't store a function inside a parameter and expect it to automatically evaluate on load

*you can store the data about an object inside data- properties

*you can set the value of objects on page load in jQuery using the $(document).ready() event

.

<script type="text/javascript">
$(document).ready( function() {                    // this code runs when the page is first loaded
   var radios = $("input[type='radio']");          // find all of your radio buttons
    $.each(radios, function(){
       var radio = $(this);
       var param = radio.attr('data-param');       // retrieve the param from the object
       radio.attr('checked', test_check(param) );  // set the value of the radio button
    })
});

function test_check(params) {
    if(conditions){
        return 'checked';
    }
    else
        return '';
}
</script>

A: I was facing same problem and my conclusion is that don't use " " to contain a function.
Correct:
<input type="radio" name="im" id="b1" onclick=alert("hello"); />

Incorrect:
<input type="radio" name="im" id="b1" onclick="alert("hello");" />


text:
Q: how to populate dynamic values in HTML email template with Letter head in a trigger I am working on a Round robin record assignment on case object and I need to notify the contacts noted on the case with the new case owner details after case assignment. I have tried with workflows but it didn't worked out. So I have written a single email message class with custom html template in trigger to send an email to contact noted on case. So I am receiving the template as  HTML but my client want it with my company letterhead.
So could someone please let me know how can we populate dynamic values to a Html template with letterhead
Also I have tried to replace the values on existing HTML template with Letterhead even though I am unable to get the letterhead instead able to see a blank at the top followed by HTML message
Any thoughts would be highly appreciated...!!!
It's part of a trigger:
 for(case cm : [select id, CaseNumber, Subject, Priority,
                       Description,Contact_Method__c,
                       Preferred_Language__c, contact.Name,ContactEmail
                from case
                where ID IN :Emaillist.keySet()])
    {
        system.debug('case list for email' + cm);
        for(User Un : Eulist)
        {
            if(Emaillist.get(cm.id) == un.id)
            {
                Messaging.SingleEmailMessage sm = new Messaging.SingleEmailMessage();
                String[] toAddresses = new String[] {cm.ContactEmail};
                sm.setToAddresses(toAddresses);
                sm.setReplyTo('support@zzzz.com');
                sm.setSenderDisplayName('Support');
                sm.setSubject('Your Request was started/updated - ref' + cm.CaseNumber);
                String body = 'Dear'+ ' '+ cm.contact.Name +',
';
                body += '
 We are pleased to inform you that the Incident you reported has
';
                body += 'been successfully entered into the ticketing
';
                body += 'system. Your assigned Reference Number is'+' '+ cm.CaseNumber +'. This
';
                body += 'number should be retained for reference purposes. A support
';
                body += 'engineer has claimed your case and will contact you as soon as possible.

';
                body += 'Reference Number:'+' '+cm.CaseNumber +'
';
                body +=     'Assigned To :' +' '+  Un.Name +'
';
                body +=    'Mail Address :' +' '+ Un.Email +'
';
                body +=       'Telephone :' +' '+ Un.Phone +'
';
                body +=          'Subject:' + ' '+cm.Subject +'
';
                body +=         'Priority:' + ' '+cm.Priority +'
 ';
                body +=   'Contact Method:' +' '+ cm.Contact_Method__c +'
';
                body +='Preferred Language:'+' '+cm.Preferred_Language__c +'
';
                body +=      'Description:' +' '+cm.Description+'
';
                sm.setHtmlBody(body);
                FEmaillist.add(sm);
           }
        }
    }
    Messaging.sendEmail(FEmaillist);


text:
Q: Unable to display address using reverse Geocoding This is my code......
public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
            TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
            TextView myAddress = (TextView)findViewById(R.id.myaddress);

            myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
            myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));

            Geocoder geocoder = new Geocoder(this, Locale.getDefault());

            try {
                //List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
                /* List<Address> addresses = new Geocoder(this,Locale.getDefault()).getFromLocation(LATITUDE, LONGITUDE, 1);

                if(addresses != null) {
                    Address returnedAddress = addresses.get(0);
                    StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
                    for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                        strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                    }
                    myAddress.setText(strReturnedAddress.toString());*/

                List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
                StringBuilder sb = new StringBuilder();
                if (addresses.size() > 0) {
                   Address address = addresses.get(0);

                   for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                      addr=address.getAddressLine(i);
                }
                else{
                    myAddress.setText("No Address returned!");
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                /*e.printStackTrace();
                myAddress.setText("Canont get Address!");*/
            }

        }

Can anyone sort out what is the problem???
Thanks in advance.

A: public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
            TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
            TextView myAddress = (TextView)findViewById(R.id.myaddress);

            myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
            myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));

            Geocoder geocoder = new Geocoder(this, Locale.getDefault());

            try {
                //List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
                /* List<Address> addresses = new Geocoder(this,Locale.getDefault()).getFromLocation(LATITUDE, LONGITUDE, 1);

                if(addresses != null) {
                    Address returnedAddress = addresses.get(0);
                    StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
                    for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                        strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                    }
                    myAddress.setText(strReturnedAddress.toString());*/

                List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
                StringBuilder sb = new StringBuilder();
                if (addresses.size() > 0) {
                   Address address = addresses.get(0);

                   for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                      sb.append(address.getAddressLine(i)+ ",");

                }
                else{
                    myAddress.setText("No Address returned!");
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                /*e.printStackTrace();
                myAddress.setText("Canont get Address!");*/
            }
                  myAddress.setText(sb.toString());
        }

A: I would suggest you should first check the presence of GeoCoder implementation and only then use it. It is not necessarily present in all devices.

The Geocoder class requires a backend
  service that is not included in the
  core android framework. The Geocoder
  query methods will return an empty
  list if there no backend service in
  the platform. Use the isPresent()
  method to determine whether a Geocoder
  implementation exists.


text:
Q: Ion sets the imageView height to a wrong value I dont know why this is happening: After loading the image with the Ion library, my image shows two white bars below and above image. I don't want to have that.

My ImageView is displayed in a listview item. My adapter code looks like this:

if (node.getImageUrl() != null) {
    ivImage.setVisibility(View.VISIBLE);
    Ion.with(ivImage)
            .placeholder(R.drawable.anne_eli_icons_set_up_anne_eli_logo_530px)
            //.error(R.drawable.error_image)
            //.animateLoad(android.R.anim.cycle_interpolator)
            .animateIn(android.R.anim.fade_in)
            .load("http://app.anne-eli.at/" + node.getImageUrl().getUrlBig());

} else {
    ivImage.setVisibility(View.GONE);
}

My imageview layout like this:

<LinearLayout ...
    <ImageView
            android:id="@+id/fragment_appointment_list_item_article_iv_image"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/anne_eli_icons_set_up_anne_eli_logo_530px"
            android:background="@color/gray1" />
</LinearLayout>

Any ideas?

A: change your imageview layout to this one:
<LinearLayout ...
<ImageView
        android:id="@+id/fragment_appointment_list_item_article_iv_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY" <!-- this line added , also your can use other value too like cropCenter ... -->
        android:src="@drawable/anne_eli_icons_set_up_anne_eli_logo_530px"
        android:background="@color/gray1" />
</LinearLayout>

A: I think it may be whatever value "gray1" is, but it looks very white because it's lighter than the image in the background.  Remove the background attribute in the xml and it'll be invisible.
Likewise, without setting a scaleType on the ImageView, it's going to default to center.  This will attempt to resize the image so it fits to the center of the ImageView without cropping.  The ImageView is bound to the width of it's container.  The image provided is much wider than that, so it shrinks the image to fit. This means the tops and bottoms will be shrunk as well, and the image becomes smaller than the height of the container.  If you want the image to be near the top, you can try setting the scaleType to fitStart instead.


text:
Q: Design pattern: Which one to choose? First of all this is all just concept, I have no actual programming done yet. This is the situation:
I have a Class A which uses the Filesystemwatcher to watch for changes in a folder. (using events)
Then I have a 'Collection Class' B which has a List of A's.
Now what I want to happen is as follows,
A Change happens with the folder, A detects this and sends a message to B, B transfers this message to Class C. Class C then begins a method which updates the GUI. (What changes were made etc..)
Now I have searched and thought pretty long on this subject, but can't find the solution. But, I have found 2 design patterns:
Mediator and Observer.
As a software engineer I have to some degree once made the Observer pattern so I know some of the basics there.
Now to my questions:

*

*What pattern is best to use in this situation?

*How do I make it so that B transmits the message to C?

*Do I need custom Events / delegates to make A transmit data to B or can I use the Built-in events?
P.S.: I'm using C# as my programming language.
edit: Thanks to everyone for helping me, votes are on the way.

A: Observer is fine. You can either make C an observer of B (so that B transmits events from A's to C), or make C listen directly to A's (this is probably the worse choice as it creates a direct dependency from C to A).
Note that this basically a variation of Model-View-Controller, where A are the models and C the view. Now whether or not B would make a proper controller depends largely on its responsibilities: if it is only a collection of A's, it is not a good idea to make it a controller. Without more details about your classes and responsibilities, it is hard to say more.

A: For what I make out of this, there are a bunch of 'A' objects that pass on events asynchronously to a single B, that in turn passes that info on to a single C.
So, let B contain and observe the A's and let C observe B.
If you got a lot of A's, you might want to have B do some gathering/caching of A's events before notifying C. Especially if C is serving a user interface.
Side note: don't over-patternize your software. Try to be open-minded and always find the simplest and easiest solution. Only use a pattern where its appropriate, and not just because it's possible. I have seen many people throwing in proxies, command-patterns, observers, MVC's, mediators etc, where they were unneccesary.
Good luck.

A: public class A
{
    public event FileSystemEventHandler FileSystemEvent;

    A()
    {
        this.fsw = new FileSystemWatcher();
        this.fsw.OnFileSystemEvent += (sender, e) =>
            { if(this.FileSystemEvent != null)
                 this.FileSystemEvent(this,e); };
    }
}

public class B
{
    public event FileSystemEventHandler FileSystemEvent;

    B()
    {
        this.RegisterAClasses();
        foreach( A item in this.AClasses )
             item.FileSystemEvent += (sender, e) =>
                 { if(this.FileSystemEvent != null)
                      this.FileSystemEvent(sender, e) };
    }
}

public class C
{
    C()
    {
        this.RegisterBClass();
        this.BClass.FileSystemEvent += (sender, e) =>
             { /* update gui... */ };
    }
}

(psuedo code...)

A: I ended up using nearly the same scenario for a demo of Reactive Extensions.
RX is a formalism of the observer pattern - but generalized to be the inverse/dual of the iterator pattern.
Details and source code - http://code.msdn.microsoft.com/RxDemos

A: Observer is a proper pattern here. I don't understant why u said this:

Then I have a 'Collection Class' B
  which has a List of A's.

because, to Observer pattern, I think B should observe A, so in class A, there some Bs for listen an event fire by A(a folder be changed). Similarly, class C should observe B, so in class B there are some objects C register for listening event fire by B.
The neccesary for a custom event or build in event depend on you class. If its .NET's class, I think there's some event for notifying a change in a dicrectory. If not, you should write your own events / delegate.


text:
Q: Javascript: Onload if checkbox is checked, change li class I have this code on javascript side:
function changeSelectionStyle(id) {
    if(document.getElementById(id).className != 'yes'){
    document.getElementById(id).className = 'yes';
    }
    else{document.getElementById(id).className = '';}
}

And this on html:

    <input type="checkbox" id="selectedAuthorities-4_1" name="selectedAuthorities" value="ROLE_ADD_COMMENT_TO_CV" checked="checked" onload="changeSelectionStyle(this.id + 'li');" onclick="changeSelectionStyle(this.id + 'li'); checkFatherSelection(this.id);">

      Agregar comentario <samp>Permite agregar comentario en el detalle.</samp>

Well what I cant get work is when the checkbox is selected, on load, the JS should check it, and assign class="yes" to the li, here:

What should I add to my original JS function to make that possible. Note that li ids are not static, they are dynamic, the html li id is generated.
Process for the solution (logic):
Event on load, check if the input with X id is checked, if it is, update the parent li with the JS function changeSelectionStyle. Because the problem that I have right now, is that when I select an input (check it), the li color is switching, but when it loads with a selected/checked input, the color remains untouched, and its changing the color when I click the input (uncheck it - wrong effect)

A: Try this code:
window.onload=function(){
 const checkBoxes=document.querySelectorAll("input[type='checkbox']");
 for(var i=0; i < checkBoxes.length; i++)
 {
    if(checkBoxes[i].checked=='checked')
       checkBoxes[i].parentNode.className='yes';
 }
}

A: window.onload=function(){
var inputFields=document.getElementsByTagName('input');
var checkBoxes[];
for(var i=0;i<inputFields.length;i++)
 if(inputFields[i].type=='checkbox'&&inputFields[i].checked=='checked'&& inputFields[i].parentNode.tagName=='LI')
inputFields[i].parentNode.className='yes';
}

Here we go..


text:
Q: Outputting data from within an object (JAVA) I'm trying to output some data from within an object to the console. Seems to be working, but below the data I'm getting a strange message.
Below is the code:
import java.text.DecimalFormat;

/**
 * The Circle class calculates area, diameter, and circumference
 */

public class Circle {

    DecimalFormat fmt = new DecimalFormat("#0.00");

    // Fields
    private double radius;                  // Holds the circle radius
    private final double PI = 3.14159;      // The formula for PI

    /**
     *      Start Constructors
     */

    public Circle(double rad) {

        radius = rad;
        System.out.println("The circle's radius is " + (fmt.format(radius)));
        System.out.println("The circle's area is " + (fmt.format(PI * radius * radius)));
        System.out.println("The circle's diameter is " + (fmt.format(radius * 2)));
        System.out.println("The circle's circumference is " + (fmt.format(2 * PI * radius)));
    }

}

The console output is:
The circle's radius is 2.00
The circle's area is 12.57
The circle's diameter is 4.00
The circle's circumference is 12.57
Circle@5115a298

What is the circle message?

A: Give your Circle class a decent toString() method override. You're seeing the return from Object's default version of this method.
@Override
public String toString() {
   /*  return a String that shows the "state" of this object */
}

A: You must have a System.out somewhere else that only has a Circle object as output. Then Hovercraft Full Of Eels' answer applies.
Btw: Math.PI already gives you Pi!


text: Q: Crashlytics wants dSym file that I do not have anymore Crashlytics is complaining about missing dSym files, but I don't have them anymore. Is there a way to remove the warning, remove the crashes or upload a fake file?


text:
Q: How can I stream audio from a Windows PC to speakers connected to an AirPort Express? I'm running Windows 10 on a PC and I have an AirPort Express connected via Ethernet.
I can find and stream audio to the AirPort Express when using iTunes.
However, I often listen music on YouTube and would love to stream the audio through the AirPort Express.
How can I do this?

A: A company called Rogue Amoeba makes a product called AirFoil, including a Windows version, which supports streaming audio from any app to AirPort Express.
Note that AirPort Express audio streaming is buffered (read: delayed), so if this is for listening to music, you'll be fine. But it's not good for real time things like gaming or audio/video chat, and if you try to watch a video your audio will be way behind your video.


text:
Q: What's the point of assassins taking over a city? I'm looking at a minion assassin mission in Assassin's Creed: Revelations and it says the rewards is that

The Assassins will take control of this city.

Does that have any tangible benefits?

A: By taking over a city, you're effectively creating another source of income and supplies.  Just like when you take over Templar Dens and renovate the stores in the zone.  The difference here is that you acquire the different revenue/item generating sources through the different missions.
Once you have removed the templar influence in the city, you should send assassins to the missions that show the difficulty bar as stars (rather than diamonds).  Being successful in that mission will increase the assassin influence in the city as well as other perks such as additional income, experience for the assassins that are occupying the city, crafting items and an additional slot for occupation.


text:
Q: OutputStream null object error I have a big problem and i cant solve. Please help me.
I have a data at the fragment i want to send data other devices with bluetooth but my ConnectedThread does not work. For the solve my problem firstly i tried log cat and i find my ConnectedThread is empty but why ? i although initilazed on my fragment.
**BluetoothConnectionService.java **
package com.example.duygu.mybluetoothdevicelist;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.UUID;

public class BluetoothConnectionService {
    private static final String TAG = "BluetoothConnectionServ";

    private static final String appName = "MYAPP";

    private static final UUID MY_UUID_INSECURE =
            UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");

    private final BluetoothAdapter mBluetoothAdapter;
    Context mContext;

    private AcceptThread mInsecureAcceptThread;

    private ConnectThread mConnectThread;
    private BluetoothDevice mmDevice;
    private UUID deviceUUID;
    ProgressDialog mProgressDialog;

    private ConnectedThread mConnectedThread;

    public BluetoothConnectionService(Context context) {
        mContext = context;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        start();
    }

    /**
     * This thread runs while listening for incoming connections. It behaves
     * like a server-side client. It runs until a connection is accepted
     * (or until cancelled).
     */
    private class AcceptThread extends Thread {

        // The local server socket
        private final BluetoothServerSocket mmServerSocket;

        public AcceptThread(){
            BluetoothServerSocket tmp = null;

            // Create a new listening server socket
            try{
                tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, MY_UUID_INSECURE);

                Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE);
            }catch (IOException e){
                Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
            }

            mmServerSocket = tmp;
        }

        public void run(){
            Log.d(TAG, "run: AcceptThread Running.");

            BluetoothSocket socket = null;

            try{
                // This is a blocking call and will only return on a
                // successful connection or an exception
                Log.d(TAG, "run: RFCOM server socket start.....");

                socket = mmServerSocket.accept();

                Log.d(TAG, "run: RFCOM server socket accepted connection.");

            }catch (IOException e){
                Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
            }

            //talk about this is in the 3rd
            if(socket != null){
                connected(socket,mmDevice);
            }

            Log.i(TAG, "END mAcceptThread ");
        }

        public void cancel() {
            Log.d(TAG, "cancel: Canceling AcceptThread.");
            try {
                mmServerSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() );
            }
        }

    }

    /**
     * This thread runs while attempting to make an outgoing connection
     * with a device. It runs straight through; the connection either
     * succeeds or fails.
     */
    private class ConnectThread extends Thread {
        private BluetoothSocket mmSocket;

        public ConnectThread(BluetoothDevice device, UUID uuid) {
            Log.d(TAG, "ConnectThread: started.");
            mmDevice = device;
            deviceUUID = uuid;
        }

        public void run(){
            BluetoothSocket tmp = null;
            Log.i(TAG, "RUN mConnectThread ");

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
                        +MY_UUID_INSECURE );
                tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
            } catch (IOException e) {
                Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
            }

            mmSocket = tmp;

            // Always cancel discovery because it will slow down a connection
            mBluetoothAdapter.cancelDiscovery();

            // Make a connection to the BluetoothSocket

            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                mmSocket.connect();

                Log.d(TAG, "run: ConnectThread connected.");
            } catch (IOException e) {
                // Close the socket
                try {
                    mmSocket.close();
                    Log.d(TAG, "run: Closed Socket.");
                } catch (IOException e1) {
                    Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage());
                }
                Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE );
            }

            //will talk about this in the 3rd video
            connected(mmSocket,mmDevice);
        }
        public void cancel() {
            try {
                Log.d(TAG, "cancel: Closing Client Socket.");
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage());
            }
        }
    }

    /**
     * Start the chat service. Specifically start AcceptThread to begin a
     * session in listening (server) mode. Called by the Activity onResume()
     */
    public synchronized void start() {
        Log.d(TAG, "start");

        // Cancel any thread attempting to make a connection
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
        if (mInsecureAcceptThread == null) {
            mInsecureAcceptThread = new AcceptThread();
            mInsecureAcceptThread.start();
        }
    }

    /**
     AcceptThread starts and sits waiting for a connection.
     Then ConnectThread starts and attempts to make a connection with the other devices AcceptThread.
     **/

    public void startClient(BluetoothDevice device,UUID uuid){
        Log.d(TAG, "startClient: Started.");

        //initprogress dialog
        mProgressDialog = ProgressDialog.show(mContext,"Connecting Bluetooth"
                ,"Please Wait...",true);

        mConnectThread = new ConnectThread(device, uuid);
        mConnectThread.start();
    }

    /**
     Finally the ConnectedThread which is responsible for maintaining the BTConnection, Sending the data, and
     receiving incoming data through input/output streams respectively.
     **/
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG, "ConnectedThread: Starting.");

            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            //dismiss the progressdialog when connection is established
            try{
                mProgressDialog.dismiss();
            }catch (NullPointerException e){
                e.printStackTrace();
            }

            try {
                tmpIn = mmSocket.getInputStream();
                tmpOut = mmSocket.getOutputStream();
            } catch (IOException e) {
                Log.d(TAG, "ConnectedThread: doest work OUTPUT");

                e.printStackTrace();
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run(){
            byte[] buffer = new byte[1024];  // buffer store for the stream

            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                // Read from the InputStream
                try {
                    bytes = mmInStream.read(buffer);
                    String incomingMessage = new String(buffer, 0, bytes);
                    Log.d(TAG, "InputStream: " + incomingMessage);
                    Intent incomingMessageIntent = new Intent("incomingMessage");

                    incomingMessageIntent.putExtra("theMessage", incomingMessage);
                    LocalBroadcastManager.getInstance(mContext).sendBroadcast(incomingMessageIntent);

                } catch (IOException e) {
                    Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
                    break;
                }
            }
        }

        //Call this from the main activity to send data to the remote device
        public void write(byte[] bytes) {
            String text = new String(bytes, Charset.defaultCharset());
            Log.d(TAG, "write: Writing to outputstream: " + text);
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
                Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
            }
        }

        /* Call this from the main activity to shutdown the connection */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }

    private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
        Log.d(TAG, "connected: Starting.");

        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(mmSocket);
        mConnectedThread.start();
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     *
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out)  { //changed this
        // Create temporary object
        if(mConnectedThread!=null){
            ConnectedThread r;
            r=mConnectedThread;

            // Synchronize a copy of the ConnectedThread
            Log.d(TAG, "write: Write Called.");
            //perform the write
            r.write(out);

        }
        else{
            Log.d(TAG, "ConnectedThread empty");

        }

    }

}

I saw this log.cat: ConnectedThread empty
 public void write(byte[] out)  { //changed this
        // Create temporary object
        if(mConnectedThread!=null){
            ConnectedThread r;
            r=mConnectedThread;

            // Synchronize a copy of the ConnectedThread
            Log.d(TAG, "write: Write Called.");
            //perform the write
            r.write(out);

        }
        else{
            Log.d(TAG, "ConnectedThread empty");

        }

    }

But i initilazed service in there (Fragment)
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(convertView==null) {
            convertView = inflater.inflate(R.layout.fragment_ota__update, container, false);

            text=(TextView)convertView.findViewById(R.id.text);
            InputStream  is =this.getResources().openRawResource(R.raw.blink);
            BufferedReader reader = new BufferedReader( new InputStreamReader(is));
            send =(Button) convertView.findViewById(R.id.send);
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

            mBluetoothConnection = new BluetoothConnectionService(getActivity().getApplicationContext());
            if(is!=null){

                try {
                    while ((data = reader.readLine()) != null) {
                        char [] ch =data.toCharArray();

                        for (char c: ch) {
                            int i= (int) c;
                            sbuffer.append(Integer.toHexString(i).toUpperCase());
                            text.setText(sbuffer);

                        }

                    }

                    is.close();

                }
                 catch (IOException e) {
                    e.printStackTrace();
                }
            }

            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(sbuffer!=null) {
                  String deneme;
                   deneme="Hi";
                        byte[] bytes = deneme.toString().getBytes(Charset.defaultCharset());
                        mBluetoothConnection.write(bytes);

                    }
                }
            });
        }


text:
Q: fulltext search for dataset I'd like to implement fulltext search for a datatable ?
are there any .net libraries which support indexing/searching on the fly ?

A: Lucene.NET.
Here's a blog post about how I used it in my application.
http://ifdefined.com/blog/post/Full-Text-Search-in-ASPNET-using-LuceneNET.aspx

A: here's a simple extension of DataTable, which is not exactly "fulltext search", but funny and helpful.
public static List<DataRow> FullTextSearch(this DataTable dataTable, string[] keywords)
{

var q = dataTable.AsEnumerable().Where<DataRow>(row => keywords.All(keyword =>row.ItemArray.Select(p => p.ToString()).Any<string>(s => s.Contains(keyword))));

return q.ToList();

}


text:
Q: Getting value from an object with jQuery I have this JSON, that I need to use.
{"services":{"344":{"post":{"ID":344}},"345":{"post":{"ID":345}}}}

I need to get the value of services.344.post.ID which is 344.
How can this be achieved?
Thank you in advance.

A: If
var obj = JSON.parse('{"services":{"344":{"post":{"ID":344}},"345":{"post":{"ID":345}}}}');

Then you want obj['services']['344']['post']['ID']


text:
Q: Having force close error with open new intent for Google Map I'm getting the lat and lng from one URL.
In my coding,
it will be like,
if(lat==1.3005060 && lng== 103.8745850) ,
it will open up up the next class, map.java.
else, invalid map.
I've initially declare it as string to display it as text view.
Next I've declare it as float in the onClick method,
so that it can pass to google map.
However,
there is force close error occuring.
Can someone guide me?
LogCat Error:
08-14 11:07:13.190: E/AndroidRuntime(457): FATAL EXCEPTION: main
08-14 11:07:13.190: E/AndroidRuntime(457): java.lang.IllegalStateException: Could not execute method of the activity
08-14 11:07:13.190: E/AndroidRuntime(457):  at android.view.View$1.onClick(View.java:2185)
08-14 11:07:13.190: E/AndroidRuntime(457):  at android.view.View.performClick(View.java:2585)
08-14 11:07:13.190: E/AndroidRuntime(457):  at android.view.View$PerformClick.run(View.java:9299)
08-14 11:07:13.190: E/AndroidRuntime(457):  at android.os.Handler.handleCallback(Handler.java:587)
08-14 11:07:13.190: E/AndroidRuntime(457):  at android.os.Handler.dispatchMessage(Handler.java:92)
08-14 11:07:13.190: E/AndroidRuntime(457):  at android.os.Looper.loop(Looper.java:130)
08-14 11:07:13.190: E/AndroidRuntime(457):  at android.app.ActivityThread.main(ActivityThread.java:3691)
08-14 11:07:13.190: E/AndroidRuntime(457):  at java.lang.reflect.Method.invokeNative(Native Method)
08-14 11:07:13.190: E/AndroidRuntime(457):  at java.lang.reflect.Method.invoke(Method.java:507)
08-14 11:07:13.190: E/AndroidRuntime(457):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
08-14 11:07:13.190: E/AndroidRuntime(457):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670)
08-14 11:07:13.190: E/AndroidRuntime(457):  at dalvik.system.NativeStart.main(Native Method)
08-14 11:07:13.190: E/AndroidRuntime(457): Caused by: java.lang.reflect.InvocationTargetException
08-14 11:07:13.190: E/AndroidRuntime(457):  at java.lang.reflect.Method.invokeNative(Native Method)
08-14 11:07:13.190: E/AndroidRuntime(457):  at java.lang.reflect.Method.invoke(Method.java:507)
08-14 11:07:13.190: E/AndroidRuntime(457):  at android.view.View$1.onClick(View.java:2180)
08-14 11:07:13.190: E/AndroidRuntime(457):  ... 11 more
08-14 11:07:13.190: E/AndroidRuntime(457): Caused by: java.lang.NumberFormatException: latitude
08-14 11:07:13.190: E/AndroidRuntime(457):  at org.apache.harmony.luni.util.FloatingPointParser.initialParse(FloatingPointParser.java:114)
08-14 11:07:13.190: E/AndroidRuntime(457):  at org.apache.harmony.luni.util.FloatingPointParser.parseFloat(FloatingPointParser.java:319)
08-14 11:07:13.190: E/AndroidRuntime(457):  at java.lang.Float.parseFloat(Float.java:323)
08-14 11:07:13.190: E/AndroidRuntime(457):  at com.example.fambond.SingleMenuItemActivity.onClick(SingleMenuItemActivity.java:75)
08-14 11:07:13.190: E/AndroidRuntime(457):  ... 14 more

part of my code for singlemenu.java
public void onClick(View v) {
         //TODO Auto-generated method stub
    float lat=Float.parseFloat(KEY_LATITUDE);
    float lng =Float.parseFloat(KEY_LONGITUDE);
    if(lat==1.3005060 && lng== 103.8745850){
    Log.d("coords", "lat: " + KEY_LATITUDE + " long: " + KEY_LONGITUDE);
    Intent intent = new Intent(SingleMenuItemActivity.this,map.class);
    intent.putExtra("MAP",KEY_LATITUDE.toString());
    intent.putExtra("MAP",KEY_LONGITUDE.toString());
    startActivity(intent);

    }
    else
    {
        Toast.makeText(SingleMenuItemActivity.this, "Invalid MAP", Toast.LENGTH_LONG).show();
    }
}

A: The problem seems to be that you are comparing floats with == sign. The correct way to test floats for 'equality' is:
if( (Math.abs(lat-1.3005060) < epsilon) && (Math.abs(lng-103.8745850) < epsilon) ){
}

where epsilon is a very small number like 0.00000001, depending on the desired precision.
See What's wrong with using == to compare floats in Java? and Manipulating and comparing floating points in java question for more.


text:
Q: Why would I use a Bound Service? For communicating between the application and a Service, why would I use a Bound service rather than sending data in the Intent:
mServiceIntent = new Intent(getActivity(), RSSPullService.class);
mServiceIntent.setData(Uri.parse(dataUrl));

I read that "If the service is already running, it will be called with onStartCommand() again, to deliver the new Intent, but a second copy is not created."  Which means that I Could send messages in that intent to affect the service's progress, this is what is done in the google RandomMusicPlayer example:
public void onClick(View target) {
    // Send the correct intent to the MusicService, according to the
    // button that was clicked
    if (target == mPlayButton)
        startService(new Intent(MusicService.ACTION_PLAY));
    else if (target == mPauseButton)
        startService(new Intent(MusicService.ACTION_PAUSE));
    else if (target == mSkipButton)
        startService(new Intent(MusicService.ACTION_SKIP));
    else if (target == mRewindButton)
        startService(new Intent(MusicService.ACTION_REWIND));
    else if (target == mStopButton)
        startService(new Intent(MusicService.ACTION_STOP));
    else if (target == mEjectButton) {
        showUrlDialog();
}

A: There are a number of reasons for binding to a Service as opposed to sending it asynchronous messages.  One important reason is it gives you more control of the lifetime of a service.  If you are simply sending intents that are handled by the service, the service may well go away -- losing any internal state -- between messages.  Bound services receive special treatment when Android is looking for resources that can be freed.
Another, unrelated, reason is if you are binding to an in-process service you can cast the IBinder to a known class and call methods on it directly.  This provides a very rich (although tightly coupled) interface to the service.  It would be difficult to simulate this rich interaction using message passing via Intents.


text:
Q: How to run inquirer.prompt on every occurance of element using cheerio library? I'm currently developing the console application which allows users to change the values inside HTML files. I'm using the cheerio library to find in the HTML file every occurrence of the class called "dynamic" and next I want the user to assign a new value for each element.
But when I run .each() method on the cheerio object I end up being able to only assign value to the last occurrence, and then all the previous ones are assigned the same value I just provided for the last one. As I mentioned before, I want the user to input the new value for each occurrence separately one by one.

Here is my code:
async function readFile(htmlPath) {
        const htmlFile = fs.readFileSync(htmlPath, 'utf8');
        // Load the HTML into Cheerio
        const $ = cheerio.load(htmlFile);
        const dynamicElements = $('body').find('.dynamic');
        // Log the contents of each dynamic element
        await dynamicElements.each(async (i, el) => {
            await nameVariable($(el).text());
        });
        return $.html();
    }

async function nameVariable(value) {
    await inquirer.prompt({
        type: "input",
        name: "variableName",
        message: `Name the variable for value:${value} =>`,
        default: "variableName",
    },).then((r) => {
        return r.variableName;
    });
}

Here is also the html file:

    <title>Example HTML File</title>
    <meta charset="utf-8"/>

First Name :

John

Last Name :

Smith

Species: Human

List Item 1

List Item 2

List Item 3

List Item 4


text:
Q: How to add mongodb server to dotnet project installer I have created an installer for my dotnet project by running dotnet publish -r osx-arm64. However, when I try to run the executeable it looks like it does start the server on http://localhost:5000.
Here are the logs:
Starting C-Store SCP server on port 11112
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]

However, since my GET endpoint fetches data from a local mongo server, when I try to run the GET endpoint http://localhost:5000/api/getItems it throws an error as shown below
Microsoft.AspNetCore.Server.Kestrel[13]
  Connection id "XXXXXXX", Request id "XXXXX": An unhandled exception was thrown by the application.
  System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
     at MongoDB.Driver.Core.Misc.Ensure.IsNotNull[T](T value, String paramName)
     at MongoDB.Driver.Core.Configuration.ConnectionString..ctor(String connectionString, Boolean isInternalRepresentation, IDnsResolver dnsResolver)
     at MongoDB.Driver.Core.Configuration.ConnectionString..ctor(String connectionString)
     at MongoDB.Driver.MongoUrlBuilder.Parse(String url)
     at MongoDB.Driver.MongoUrlBuilder..ctor(String url)
     at MongoDB.Driver.MongoUrl..ctor(String url)
     at MongoDB.Driver.MongoClientSettings.FromConnectionString(String connectionString)
     at MongoDB.Driver.MongoClient..ctor(String connectionString)

I am assuming this is because there's no mongodb server/driver in the executable?
I need some suggestion on how I can include the mongodb server on the executable which will automatically spin up once I run the executable. My overall goal is to have an executable for my dotnet project which contains a mongo server with it. Thanks!


text:
Q: Is there any way to make constructor understand parameter type automatically? I have a Feature class which has a public vehicle_type in it and I have 3 candidates for vehicle_type variable which are; Car,Truck and Motor classes. When I call constructor for Feature class, well I want my program to get which  vehicle type was called with constructor automatically. I actually tried to use Templates for the problem but it didn't work. So, can someone tell me how to achieve this with or without using Templates.
This is my Feature.h file:
#ifndef FEATURE_H
#define FEATURE_H

#include <string>
#include "../includes/Car.h"
#include "../includes/Truck.h"
#include "../includes/Motor.h"

template <typename T>
class Feature{
    public:
        Feature();
        Feature(int w, std::string b, std::string clr, double p, T v_t);
        T vehicle_type;
        int wheels;
        std::string brand;
        std::string color;
        double price;

};

#endif

This is my Feature.cpp file:
# include "../includes/Feature.h"

template <typename T>
Feature::Feature(int w, std::string br, std::string clr, double p, T v_t){wheels = w; brand=br; color = clr; price=p;  vehicle_type = v_t; }
Feature::Feature(){}

and lastly, this below is the error occurs when I hover my mouse  on Feature constructor in the Feature.cpp file.
name followed by '::' must be a class or namespace name

Feel free to ask for more information. Thanks.

A: It looks like you just need to supply the template declaration and the fix the syntax:
template <typename T>
Feature<T>::Feature(int w, std::string br, std::string clr, double p, T v_t);

template<class T>
Feature<T>::Feature();


text:
Q: How do I fix my java program not stopping running? I am writing a simple program as some practice for Java. It takes in integers and puts them into a two-dimensional array of R rows and C columns and then simply prints out each element of the array (just for troubleshooting). When I run the code it prints every integer like it should but the program does not stop running. I have to force stop it. Why is it not stopping on its own? I tried some basic debugging and tried to see if I accidentally had an infinite loop in the code but I couldn't find it.
In case it is important I am using IntelliJ Idea Ultimate 2019.3.
Thanks
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt(); //Takes number of test cases
        for(int i = 1; i <= T; i++){ //This is the counter for each test case
            int R = in.nextInt(); //R is # of rows
            int C = in.nextInt(); //C is # of columns
            int K = in.nextInt(); //K is the thickness allowed
            int numArray[][] = new int[R+1][C+1];

            for(int j = 0; j < R; j++){
                for(int k = 0; k < C; k++){
                    numArray[j][k] = in.nextInt();
                    System.out.println(numArray[j][k]);
                }
            }

        }
        in.close();
    }//End of main
}//End of main class

Edit: Just for future reference I will include the input and the output I was getting.
Input:
3
1 4 0
3 1 3 3
2 3 0
4 4 5
7 6 6
4 5 0
2 2 4 4 20
8 3 3 3 12
6 6 3 3 3
1 6 8 6 4
Output:
3
1
3
3
4
4
5
7
6
6
2
2
4
4
20
8
3
3
3
12
6
6
3
3
3
1
6
8
6
(and here the cursor is stuck blinking not doing anything and the program doesn't quit on its own)
I solved the issue by manually typing the input instead of copying and pasting it. Not sure what caused that issue but it worked!

A: This little piece of code requires the user to input 3 integers (R, C  and K) T-times:
int T = in.nextInt();
for(int i = 1; i <= T; i++){
    int R = in.nextInt();
    int C = in.nextInt();
    int K = in.nextInt();
    // ...
}

Additionally the user has to input an integer R*C-times until i <= T:
for(int j = 0; j < R; j++){
    for(int k = 0; k < C; k++){
        numArray[j][k] = in.nextInt(); // << requires user-interaction each loop here >>
        System.out.println(numArray[j][k]);
    }
}

If you use T=1, R=1, C=1, K=1 the user has to input only 1 additional integer, as there is only 1 test-repitition and R*C = 1. With that your program terminates just as expected.
With bigger values of T, R, C, K the required user-interactions grow exponentially, which probably makes you think that your program should have ended but it still waits for additional user-input.

A: Ok I think I figured out the issue. I was copying and pasting the test inputs from a web page. I tried double checking to make sure the input was valid and then inputting them by hand and it fixed it. Not 100% why but that fixes the problem. Thanks for the help!

A: your for(int i = 1; i <= T; i++) probably newer ends because you are increasing T.
You need to made some condition in loop to exit. For example
if (xx == yy) break;


text:
Q: Platform.isIOS not workin on real iOS device I made a login with Apple on my login screen, and I made an if statement to check if the platform is iOS to show it in iOS devices.
The problem is when I run the app on the iOS simulator the button shows up, but when I run the app on a real device the button does not show up.
if (Platform.isIOS)
     _LoginWithAppleIdWidget()