Como gravar sons do alto-falante e do microfone simultaneamente com o python no windows?

Question: Eu tentei gravar o som do desktop com o pyaudio, mas eu só posso ouvir o som do microfone ou do alto-falante.
Também baixei o portaudio, mas não tenho certeza se posso obter o som do alto-falante e o som do microfone com ele simultaneamente
Reparei que quando eu mudei o dispositivo de entrada para stereo mixer consegui gravar o áudio do auto-falante mas deixei de gravar o microfone.
Este é o código que estou utilizando:
import pyaudio
import wave
import threading
import time
import subprocess

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "tmp/tmp.wav"

class recorder:
    def __init__(self):
        self.going = False
        self.process = None
        self.filename = "ScreenCapture.mpg"
    def record(self,filename):
        try:
            if self.process.is_alive():
                self.going = False
        except AttributeError:
                print("test")
        self.process = threading.Thread(target=self._record)
        self.process.start()
        self.filename = filename
    def _record(self):
        p = pyaudio.PyAudio()
        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK,
                        as_loopback=True)

        #print("* recording")

        frames = []

        self.going = True

        while self.going:
            data = stream.read(CHUNK)
            frames.append(data)

       # print("* done recording")

        stream.stop_stream()
        stream.close()
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

    def stop_recording(self):
        self.going = False

O que devo fazer?
Código atualizado conforme o conselho do ederwander mas ainda não funcionou.Não sei se o problema é o código ou meu notebook :
import pyaudio
import wave
import threading
import time
import subprocess
#from pydub import AudioSegment
import numpy as np

CHUNK = 1024
FORMAT = pyaudio.paInt16
#CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "tmp/tmp.wav"

p = pyaudio.PyAudio()

for i in range(0, p.get_device_count()):
    print(i, p.get_device_info_by_index(i)['name'])

class recorder:
    def __init__(self):
        self.going = False
        self.process = None
        self.filename = "ScreenCapture.mpg"

    def record(self, filename):
        try:
            if self.process.is_alive():
                self.going = False
        except AttributeError:
            print("test")
        self.process = threading.Thread(target=self._record)
        self.process.start()
        self.filename = filename

    def _record(self):
        #p = pyaudio.PyAudio()
        stream = p.open(
            format=FORMAT,
            channels=2,
            rate=RATE,
            input=True,
            frames_per_buffer=CHUNK,
            input_device_index=0,
            as_loopback=True)
        stream2 = p.open(
            format=FORMAT,
            channels=1,
            rate=RATE,
            input=True,
            frames_per_buffer=CHUNK,
            input_device_index=1)
        # as_loopback=False)

        print("* recording")

        frames = []
        frames2= []

        self.going = True

        while self.going:
            data = stream.read(CHUNK)
            data2 = stream2.read(CHUNK)
            frames.append(data)
            frames2.append(data)
        # frames = dados do som as_loopback (Speakers)
        frames = b''.join(frames);

        # frames2 = dados do som  Microfone
        frames2 = b''.join(frames2);

        # decodificando os dados do Speaker
        Sdecoded = np.frombuffer(frames, 'int16')

        # decodificando o microfone
        Mdecoded = np.frombuffer(frames2, 'int16')

        # convertendo os dados do Speaker em um vetor do tipo Numpy (facilitando a vida na hora de pegar os canais de áudio)
        Sdecoded = np.array(Sdecoded, dtype='int16')

        # pegando os dados do lado direito
        direito = Sdecoded[1::2]

        # pegando os dados do lado esquerdo
        esquerdo = Sdecoded[::2]

        # mixando tudo para mono = somar lado direito + lado esquerdo + os dados decofificados do Microfone q já estão em mono
        mix = (direito + esquerdo + Mdecoded)

        # garantindo que nenhum valor extrapole os limites do short int
        signal = np.clip(mix, -32767, 32766)

        # codificar os dados novamente
        encodecoded = wave.struct.pack("%dh" % (len(signal)), *list(signal))

        print("* done recording")

        stream.stop_stream()
        stream.close()
        stream2.stop_stream()
        stream2.close()
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(1)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        #wf.writeframes(b''.join(frames))
        wf.writeframes((encodecoded))
        wf.close()

    def stop_recording(self):
        self.going = False

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](https://chat.stackexchange.com/rooms/103201/discussion-on-question-by-gabriel-como-gravar-sons-do-alto-falante-e-do-microfon)
Answer: Vamos lá, primeiro instale o Numpy via pip um  pip install numpy deve resolver a questão... Vamos precisar dele pra fazer o decode de forma rápida, neste código também uso ele pra converter listas em vetores, também uso a função clip que funciona como um limiter no áudio, quando vc mixa algo vc apenas soma os vetores, ao fazer isso inevitavelmente vc irá extrapolar o valor mínimo do short int então precisamos forçar os dados extrapolados a ficarem dentro do limite com a função clip.
Deixei o código bem clean e comentei cada parte para vc entender o que tá rolando, fiz um for no inicio para o Pyaudio me mostrar quais são as interfaces que tenho no meu SO:
C:\Python37>python.exe gravando.py
0 Mapeador de som da Microsoft - Input
1 Microfone (Realtek High Definit
2 Mixagem estéreo (Realtek High D
3 Mapeador de som da Microsoft - Output
4 Alto-falantes (Realtek High Def
5 Alto-falantes (Realtek High Definition Audio)
6 Microfone (Realtek High Definition Audio)
7 Mixagem estéreo (Realtek High Definition Audio)
8 Speakers (Realtek HD Audio output)
9 Mixagem estéreo (Realtek HD Audio Stereo input)
10 Microfone (Realtek HD Audio Mic input)
11 Entrada (Realtek HD Audio Line input)

Essa é a saída que recebo quando rodo o script, estou usando o idex 0 para capturar o áudio do SO via loopback e o index 1 para capturar os dados do microfone, dentro do loop estou capturando as duas instâncias, depois que a captura termina iniciei todo o processo de decodificação do áudio, conversão do áudio de stereo para mono, clipando o áudio, e finalmente gravando tudo em mono em 44100Hz em um arquivo .wav  ...
import pyaudio
import wave
import numpy as np

CHUNK = 1024
FORMAT = pyaudio.paInt16
RATE = 44100
RECORD_SECONDS = 2
WAVE_OUTPUT_FILENAME = "tmp.wav"

p = pyaudio.PyAudio()

for i in range(0, p.get_device_count()):
    print(i, p.get_device_info_by_index(i)['name'])

#stream usando o as_loopback para pegar som do SO
stream = p.open(
    format = FORMAT,
    channels = 2,
    rate = RATE,
    input=True,
    frames_per_buffer=CHUNK,
    input_device_index=0,
    as_loopback=True)

##stream usando o iput device do meu Microphone
stream2 = p.open(
    format = FORMAT,
    channels = 1,
    rate = RATE,
    input=True,
    frames_per_buffer=CHUNK,
    input_device_index=1)
    #as_loopback=False)

frames = []
frames2 = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    data2 = stream2.read(CHUNK)
    frames.append(data)
    frames2.append(data2)

#frames = dados do som as_loopback (Speakers)
frames= b''.join(frames);

#frames2 = dados do som  Microfone
frames2= b''.join(frames2);

#decodificando os dados do Speaker
Sdecoded = np.frombuffer(frames, 'int16')

#decodificando o microfone
Mdecoded = np.frombuffer(frames2, 'int16')

#convertendo os dados do Speaker em um vetor do tipo Numpy (facilitando a vida na hora de pegar os canais de áudio)
Sdecoded= np.array(Sdecoded, dtype='int16')

#pegando os dados do lado direito
direito=Sdecoded[1::2]

#pegando os dados do lado esquerdo
esquerdo=Sdecoded[::2]

#mixando tudo para mono = somar lado direito + lado esquerdo + os dados decofificados do Microfone q já estão em mono
mix=(direito+esquerdo+Mdecoded)

#garantindo que nenhum valor extrapole os limites do short int
signal=np.clip(mix, -32767, 32766)

#codificar os dados novamente
encodecoded = wave.struct.pack("%dh"%(len(signal)), *list(signal))

#parar todos os streams e finalizar o pyaudio
stream.stop_stream()
stream.close()
stream2.stop_stream()
stream2.close()
p.terminate()

#gravando o áudio mixado em mono
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes((encodecoded))
wf.close()

Se tudo correu bem vc deve ter um arquivo de áudio com a captura do Microfone + SPEAKERS
PS: se vc não quiser que o arquivo .wav seja em mono vc pode somar os dados do microfone em um dos canais (direito ou esquerto) ou simplesmente tentar mesclar os dados do Microfone entre os dois canais (fiz a saída em mono pq é beeeemm mais simples ....)
Comment: Ainda não funcionou.
Comment: Coloquei o código na descrição
Comment: Funcionou agora!!Mudei o input_device_index do SO.
Comment: Por favor alguém faça o ederwander o rei da internet
Comment: Só não consegui usar dentro do meu projeto ainda mas o código está correto


Como criar um efeito mouse-over em uma imagem e posiciona-lo onde quero?

Question: Estou querendo replicar um efeito de mouse over mas o que consegui até agora está meio bugado, a linha com o efeito está passando de um lado até o outro, e não está somente no comprimento do texto, que é o que quero, não sei como fazer para posicionar esse div com link dentro na parte inferior da imagem, assim como na página do oscar em BEST PICTURE.
Como eu poderia fazer isso?
Código HTML:

text here

CSS:
div.button--border-rotated {
    display: none;
    position: relative;
    text-align: center;
    top: -170px;
}

div.button--border-rotated:hover, img:hover + div {
    display: block;
}

.button--border-rotated {
    border: none;
    position: relative;
}

a, a:active, a:focus, a:hover {
    text-decoration: none;
    color: inherit;
}

a {
    background-color: transparent;
}

.button--border-rotated:before {
    top: 0;
}

.button--border-rotated:after, .button--border-rotated:before {
    transition: top .3s ease-in-out;
    position: absolute;
    content: "";
    height: 2px;
    background-color: #bfa267;
    width: 100%;
    left: 0;
}

.button--border-rotated:after, .button--border-rotated:hover:before {
    top: 100%;
}

.button--border-rotated:after, .button--border-rotated:before {
    transition: top .3s ease-in-out;
    position: absolute;
    content: "";
    height: 2px;
    background-color: #bfa267;
    width: 100%;
    left: 0;
}

*, :after, :before {
    box-sizing: border-box;
}

Aqui está o link do jsfiddle, pois o código Bootstrap v3.3.6 é longo e não coube na pergunta.
Aqui a página do oscar como referencia, note que ao passar o mouse, aparecem 2 links com efeito, é isso estou tentando fazer.
Comment: Dei mais uma modificada no codigo, para deixar mais parecido com o teu exemplo. Se te ajudou, marque a resposta como correta.
Answer: Criei uma div pai para o conteúdo e deixei o texto como position absolute e com bottom 0.
https://jsfiddle.net/6k2Lhaje/191/


Multiple line code example in Javadoc comment

Question: I have a small code example I want to include in the Javadoc comment for a method.
/**
 * -- ex: looping through List of Map objects --
 *
 * for (int i = 0; i < list.size(); i++) {
 *      Map map = (Map)list.get(i);
 *      System.out.println(map.get("wordID"));
 *      System.out.println(map.get("word"));
 * }
 *
 *
 * @param query - select statement
 * @return List of Map objects
 */

The problem is the code example shows up in the Javadoc with no line breaks making it hard to read.
-- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get("wordID")); System.out.println(map.get("word")); }
Parameters
query - - select statement
Returns:
List of Map objects

I guess I am wrong in assuming the code tag would handle line breaks.  What is the best way to format code examples in Javadoc comments ?
Comment: If you use Java 18 (or higher) then you want to look into [@snippet](https://stackoverflow.com/a/69828162/194894).
Answer: In addition to the already mentioned
 tags, you should also use the @code JavaDoc annotation, which will make life much easier when it comes to HTML entities issues (in particular with Generics), e.g.:
*

* {@code
* Set<String> s;
* System.out.println(s);
* }
*

Will give correct HTML output:
Set<String> s;
System.out.println(s);

While omitting the @code block (or using a  tag) will result in HTML like this:
Set s;
System.out.println(s);

For reference, a full list of tag descriptions available in Java SE 8 can be found here.
Comment: I would have thought so too, but unfortunately it doesn't, you still need to add the  tag to get line breaks.
Comment: Another unfortunate, if you have blocks in your example code using curly braces "{}", the first closing brace will terminate the @code block. One way around it is to use (wait for it...) html entities for the braces. I don't see a compelling argument for  tags for code with blocks.
Comment: Unfortunately, it seems when you hit ctrl+shift+F (Format code in Eclipse), Eclipse messes up the {@code} tag and replaces it with {@code ...
Comment: @jpdaigle I just tried this in Eclipse Galileo and Helios and the formatter does not replace anything for me (on Mac OS, but I have never seen the formatter do anything like that on other platforms either).
Comment: _Eclipse messes up the {@code} tag and replaces it with {@code-_  This isn't because of Eclipse, this is because of (bugged?) javadoc utility. If you have @ character in the multiline code inside {@code ...multiline...} then javadoc fails to parse it correctly:( At least this is what I see with Oracle JDK1.7.0_45 javadoc implementation.
Comment: It also doesn't play well with @ symbols.
Comment: I'm also having issues with using `@` symbol in code wrapped with `{@code}` tag. Without `{@code}` I can at least escape them with `{@literal @}`
Comment: At last I stay with `<code>{...}</code>` because I don't want to escape blocks with `{}`. `{@code ...}` eats that off.
Comment: If someone is looking here for kotlin android: https://stackoverflow.com/questions/40400593/kdoc-insert-code-snippet
Comment: Gradle 4.9 fails complaining about "unclosed inline {@code} tag"
Comment: `{@code SomeCode}` still works in Android Studio 3.6.1 (Java 8), unfortunately it ignores indented code like OP's `Map map = (Map)list.get(i);` (I tried spaces and tabs) and just uses the same indentation for everything.
Comment: Note for others, as I lost time on that: It seems that `` fails to do its job in the `@return` part of the JavaDoc, as well as in `@param` (at least in the render given by IntelliJ). Need to keep such things for the global description. :(
Answer: I had a really tough time with including a specific code example in a javadoc comment. I'd like to share this one.
Please note the following:

usage of old  - tag to prevent the curly brackets from being interpreted
usage of "new" {@code ...} - tag to get the generics included in the output
escaping of the @ sign in @Override via "{@literal @}Override" because javadoc generator "tilts" there due to the fact that the @ goes directly after an opening curly bracket
remove one space in front of {@code and {@literal, to compensate inner spaces and keep the alignment

javadoc code:
/** this methods adds a specific translator from one type to another type. `
  * i.e.
  *

  * new BeanTranslator.Builder()
  *   .translate(
  *     new{@code Translator<String, Integer>}(String.class, Integer.class){
  *      {@literal @}Override
  *       public Integer translate(String instance) {
  *         return Integer.valueOf(instance);
  *       }})
  *   .build();
  *
  *

  * @param translator
  */

gets printed as
new BeanTranslator.Builder()
  .translate(
    new Translator<String, Integer>(String.class, Integer.class){
      @Override
      public Integer translate(String instance) {
        return Integer.valueOf(instance);
      }})
  .build();

Comment: This is the one worked, the accepted answer don't work well in my eclipse (4.6.2).
Comment: This works but I get a warning when running javadoc outputting this warning    "warning: {@code} within "
Comment: I wonder why all of this is necessary, my intellij 13 and later work fine with the code in the accepted answer. Is this just an eclipse issue ?
Comment: Yes, I have also seen this work fine in IntelliJ 11 and later.  IntelliJ handles it correctly.  Unfortunately Eclipse does NOT render the JavaDoc correctly (hover state), and ignores both new lines and html breaks.  I'm trying to find a solution that works well in both IDE's, since they are two of the top IDE's in use today.
Comment: Using {@code} within `<code></code>` causes javadoc to emit a "{@code} within " warning. Instead of `{@code Translator}` you should write `Translator` or use [@snippet](https://stackoverflow.com/a/69828162/194894), which is available since Java 18.
Answer: The java source has lots of good examples for this. Here's an example from the head of "String.java":
....
 * is equivalent to:
 *

 *     char data[] = {'a', 'b', 'c'};
 *     String str = new String(data);
 *

 * Here are some more examples of how strings can be used:
 *

 *     System.out.println("abc");
 *     String cde = "cde";
 *     System.out.println("abc" + cde);
 *     String c = "abc".substring(2,3);
 *     String d = cde.substring(1, 2);
 *

...

Comment: In summary, `...`
Comment: Rather `` ``
Comment: This appears to work for most code, but does not escape angular brackets such as in `List`. For that I'm using `{@code ... }`.
Comment: @JinKwon sadly this is not always working, not in my code snippet :( adding an {@code at the beginning works, even if the closing } will not be reached
Comment: @Daniel won't work if the doc itself contains a `}`. This closing curly brace will end the `{@code ...}`.
Answer: Enclose your multiline code with

 tags.
Answer: You need the

 tags for the line breaks, and the {@code ... } inside them for generics. But then it's not allowed to place the opening brace on the same line as the <generic> tag, because then everything will be displayed on 1 line again.
Displays on one line:
* ..
*

* {@code
* public List<Object> getObjects() {
*    return objects;
* }
*

* ..

Displays with line breaks:
* ..
*

* {@code
* public List<Object> getObjects()
* {
*    return objects;
* }
*

* ..

Another weird thing is when you paste the closing brace of {@code, it gets displayed:
* ..
*

* {@code
*   public List<Object> getObjects()
*   {
*     return objects;
*   }
* }
*

* ..

Output:
public List<Object> getObjects()
{
   return objects;
}
}

Comment: Welcome on Stack Overflow. To format code in posts, you can either prefix it (on a separate paragraph) by four spaces, or surround them by backticks (`` `...` ``). You don't need `<code>` and `` tags. I edited your answer in this mind.
Comment: The reason for the extra closing brace being displayed is that your first closing brace is in fact interpreted as the end of `{@code,` therefore the second closing brace becomes simple text that gets displayed. In short the problem is that either you use @code but no braces in the sample code, OR you don't and are allowed to use braces in the pure  block...
Answer: Since Java 18 (JEP 413) you may use @snippet tag:
/**
 * -- ex: looping through List of Map objects --
 * {@snippet :
 * for (int i = 0; i < list.size(); i++) {
 *      Map map = (Map)list.get(i);
 *      System.out.println(map.get("wordID"));
 *      System.out.println(map.get("word"));
 * }
 * }
 *
 * @param query - select statement
 * @return List of Map objects
 */

Comment: Gosh, why this isn't added much earlier
Answer: /**
 *

 * {@code
 * public Foo(final Class<?> klass) {
 *     super();
 *     this.klass = klass;
 * }
 * }
 *

 **/

 is required for preserving lines.
{@code must has its own line

 is just for indentation.

public Foo(final Class<?> klass) {
    super();
    this.klass = klass;
}

UPDATE with JDK8
The minimum requirements for proper codes are
 and {@code}.
/**
 * test.
 *
 *
{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }

 */

yields
 <T> void test(Class<? super T> type) {
     System.out.printf("hello, world\n");
 }

And an optional surrounding
 inserts an indentation.
/**
 * test.
 *
 *

{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }

 */

yields
     <T> void test(Class<? super T> type) {
         System.out.printf("hello, world\n");
     }

Inserting
 or surrounding with
 and
 yields warnings.
Answer: Here's my two cents.
As the other answers already state, you should use

 in conjuction with {@code }.
Use pre and {@code}

Wrapping your code inside
 and
 prevents your code from collapsing onto one line;
Wrapping your code inside {@code } prevents <, > and everything in between from disappearing. This is particularly useful when your code contains generics or lambda expressions.

Problems with annotations
Problems can arise when your code block contains an annotation. That is probably because when the @ sign appears at the beginning of the Javadoc line, it is considered a Javadoc tag like @param or @return. For example, this code could be parsed incorrectly:
/**
 * Example usage:
 *
 *
{@code
 * @Override
 * public void someOverriddenMethod() {

Above code will disappear completely in my case.
To fix this, the line must not start with an @ sign:
/**
 * Example usage:
 *
 *
{@code  @Override
 * public int someMethod() {
 *     return 13 + 37;
 * }
 * }

 */

Note that there are two spaces between @code and @Override, to keep things aligned with the next lines. In my case (using Apache Netbeans) it is rendered correctly.
Answer: I was able to generate good looking HTML files with the following snip-it shown in Code 1.
 *

 * {@code
 * A-->B
 *  \
 *   C-->D
 *    \   \
 *     G   E-->F
 * }
 *

(Code 1)
Code 1 turned into the generated javadoc HTML page in Fig 1, as expected.
A-->B
 \
  C-->D
   \   \
    G   E-->F

(Fig. 1)
However, in NetBeans 7.2, if you hit Alt+Shift+F (to reformat the current file), Code 1 turns in to Code 2.
 * <
 * pre>
 * {@code
 * A-->B
 *  \
 *   C-->D
 *    \   \
 *     G   E-->F
 * }
 *

(Code 2)
where the first
 is now broken onto two lines.  Code 2 produces generated javadoc HTML file as shown in Fig 2.

 A-->B \ C-->D \ \ G E-->F

(Fig 2)
Steve B's suggestion (Code 3) seems to give the best results and remains formatted as expected even after hitting Alt+Shift+F.
*

* A-->B
*  \
*   C-->D
*    \   \
*     G   E-->F
*

(Code 3)
Use of Code 3 produces the same javadoc HTML output as shown in Fig 1.
Answer: I just read the Javadoc 1.5 reference here, and only the code with <and > must be enclosed inside {@code ...}. Here a simple example:
 /**
 * Bla bla bla, for example:
 *
 *

 * void X() {
 *    List{@code <String>} a = ...;
 *    ...
 * }
 *

 *
 * @param ...
 * @return ...
 */
 .... your code then goes here ...

Comment: Surprised this is not up-voted enough! This solved my rpoblem as using both "edge-to-edge" caused the first closing brace of the code to be matched as the end of {@code. Thanks for sharing.
Answer: There is a significant difference between

... and
{@code.... The former will omit the type declarations in generics but the latter will keep it.
E.g.:
List<MyClass> myObject = null;
displays as List myObject = null; with the firts and as List<MyClass> myObject = null; with the second
Answer: A combination of two of the other solutions seems perfect:
*
{@code
*     {@literal @}Override
*     public void someMethod() {
*         Set<String> s;
*     }
* }

ie. use
{@code to start and }
 to end the snippet. Also, replace @ with {@literal @}.
Haven't found an easier solution. Quite sad for a language that has been under active development for decades.
Answer: If you are Android developer you can use:

TODO:your code.

To pretty print your code in Javadoc with Java code.
Comment: Please explain: what in Android's tools should make this work, considering the issues that require the @code tag? And which component should define the prettyprint class? Android uses regular Javadoc.
Comment: Xamarin/VS, Android Studio, or does it not matter?
Comment: @tyblu Android Studio works,but Xamarin Studio/VS maybe not work.You can have a try.
Answer: Try replacing "code" with "pre". The pre tag in HTML marks the text as preformatted and all linefeeds and spaces will appear exactly as you type them.
Answer: I work through these two ways without any problem:

 ... java code, even including annotations

and

 ... java code, even including annotations

Of course the latter is more simplest and observe the class="code" part
Answer: I enclose my example code with

 tags and use SyntaxHighlighter for published javadocs. It doesn't hurt IDE and makes published code examples beautiful.
Comment: highlight asked at: http://stackoverflow.com/questions/1391614/syntax-highlighting-for-javadoc
Comment: With Syntax Highlighter you must load script and correct css. Looks amazing, but you must put correct path to required scripts and css. Also, if wish to use offline, must be careful with correct paths.
Answer: In Visual Studio Code at least, you can force a Javadoc comment to respect line-breaks by wrapping it in triple-backticks, as seen below:
/** ```markdown
 * This content is rendered in (partial) markdown.
 *
 * For example, *italic* and **bold** text works, but [links](https://www.google.com) do not.
 * Bonus: it keeps single line-breaks, as seen between this line and the previous.
 ``` */

Answer: Using Java SE 1.6, it looks like all UPPERCASE PRE identifiers is the best way to do this in Javadoc:
/**
 *

 * insert code as you would anywhere else
 *

 */

is the simplest way to do this.
An Example from a javadoc I got from a java.awt.Event method:
/**
 *

 *    int onmask = SHIFT_DOWN_MASK | BUTTON1_DOWN_MASK;
 *    int offmask = CTRL_DOWN_MASK;
 *    if ((event.getModifiersEx() & (onmask | offmask)) == onmask) {
 *        ...
 *    }
 *

 */

This produces output that looks exactly like the regular code, with the regular code spacings and new lines intact.
Comment: This doesn't add anything to the existing answers.
Comment: case sensitive in the html tag?
Comment: madth3, you're right. I thought I had seen a difference when using lower vs. UPPERCASE pre modifiers, but on second look, it doesn't seem like it.  It might also have something to do with how it appeared on this webpage vs. how it appears in javadoc.


How to find the limit of a two variable function

Question:
Plugging in (0, 0) leads to an indeterminate form (zero divided by zero).
Would the only way to approach this problem be through multiplying by the conjugate $\dfrac{(x^2 - y^2)^{3/2}}{(x^2 - y^2)^{3/2}}$?
Comment: Using polar coordinates, you will find 0.
Comment: Use finite expansions.
Answer: Hint:
Using polar coordinates we get $\lim_{r\to 0}\frac{e^{r^4}-1}{r^3}$.

Then, since $$r=0\implies e^{r^4}-1=0=r^3$$
we can use L'Hopital rule: $$\lim_{r\to 0}\frac{e^{r^4}-1}{r^3}=\lim_{r\to 0}\frac{\frac{d}{dr}(e^{r^4}-1)}{\frac{d}{dr}r^3}=\lim_{r\to 0}\frac{4r^3e^{r^4}}{3r^2}$$
Comment: Actually I was thinking that but wouldn't that still lead to division by zero?
Answer: set $$x=r\cos(\phi)$$ and $$y=r\sin(\phi)$$


Difference between mat and md in angular 2

Question: I am new to angular2. I would like to know the difference between using md and mat in angular2. I tried googling but cant find the answers that I expect. I am using Angular 2 in Visual Studio 2015. Can someone please help me with the answers.
Thanks
Answer: mat- and md- are prefixes in two different versions of angular materials.
"md" prefix is deprecated from material version 2.0.0-beta.11.
deprecation-of-md-prefix


nginx sets content-type text/html on redirect

Question: I set up nginx as a reverse proxy for Drupal. Static files are served from a different domain. It works well, imagecache files are generated well, too. But the problem is: when the derivated image does not exist, the request for this image returns a redirect with the content-type:text/html, and Facebook or jQueryMobile (only when running in an iPhone, not in desktop browser) does not like it.
The context: when a file is requested from mycdn.com, if it does not exist, it is redirect to mysite.com which is a site that does the reverse proxy. So, it can be seen that imagecache does nothing here, just a use case. The question here: why nginx adds a text/html when it does a redirect?
Here is  the scenario:
GET http://mycdn.com/sites/default/files/imagecache/gallery/myfile.jpg

Server  nginx
Date    Tue, 26 Jul 2011 05:28:09 GMT
Content-Type    text/html
Content-Length  154
Connection  keep-alive
Location    http://mysite.com/sites/default/files/imagecache/gallery/myfile.jpg
Expires Thu, 25 Aug 2011 05:28:09 GMT
Cache-Control   max-age=2592000

then the result of the redirect
GET http://mysite.com/sites/default/files/imagecache/gallery/myfile.jpg
Server  nginx
Date    Tue, 26 Jul 2011 05:28:10 GMT
Content-Type    image/jpeg
Connection  keep-alive
X-Powered-By    PHP/5.2.17
Expires Tue, 09 Aug 2011 05:28:10 GMT
Cache-Control   max-age=1209600, private, must-revalidate
Etag    "58a657c2ee47424f202387000c191b7e"
Set-Cookie  DRUPAL_UID=64; expires=Thu, 18-Aug-2011 09:01:29 GMT; path=/; domain=.thongtincongnghe.com
Vary    Cookie,Accept-Encoding,User-Agent
Last-Modified   Tue, 26 Jul 2011 05:28:10 GMT
Content-Encoding    gzip
Content-Length  1400

nginx configuration on mycdn.com (I removed unrelated info):
server {
    listen       80;
    server_name mycdn.com;
    root   /home/ttcn/public_html;
    expires 30d;

    location / {
        try_files $uri @redirect;
    }

    location @redirect {
        rewrite ^(.*)$ http://mysite.com$1;
    }
}

Brief, with a desktop browser, there is no difference. Everything works flawlessly. But jQueryMobile on a mobile does not work (until the derivated image is generated, through a desktop browsing), Facebook OpenGraph does not work (I put the derivated image url in the og:image value) - it does not take that image until it exists on the server.
Comment: So the answer is there is nothing wrong with it. The problem comes elsewhere.
Answer: There is nothing wrong with the redirect having a content type of text/html. On the contrary, it is actually mandated by the HTTP/1.1 specification itself:

The temporary URI SHOULD be given by the Location field in the
  response. Unless the request method was HEAD, the entity of the
  response SHOULD contain a short hypertext note with a hyperlink to the
  new URI(s).

The cache control header might be confusing Webkit mobile. Have you tried add expires off; inside the location @redirect block?
Comment: I've just added "expires off;" in the @redirect block, but it does not help. I don't know if it is Webkit mobile mor jQuery Mobile problem, because it worked before in jQM alpha2 (not sure which version of webkit mobile). BTW I think you had a correct answer about content-type even the problem is not solved, I'll wait a day before giving out the bounty ;)


orthogonalization in GAP

Question: I'm using Eigenvectors in GAP to diagonalize a matrix $M$. The matrix is guaranteed to be diagonalizable and in fact it should be so by an orthogonal transformation. This works fine and $D$ is the desired diagonal matrix :
C:=Eigenvectors(CF(4),M);
D:=C*M*C^-1;

However $C$ is usually not orthogonal. There are several methods to orthogonalize it. For example this matlab code https://blogs.mathworks.com/cleve/2016/07/25/compare-gram-schmidt-and-householder-orthogonalization-algorithms/
should be translatable to GAP without much difficulty; but my guess is that it will be slow. Is there anything already built in GAP for this?
I gathered an example before some of the comments and answers were written. I'll post here for reference; (I usually work with much larger matrices). I added a simple Gram-Schmidt orthogonalization translated from the referenced link:
M:=[
[1,0,0,0,0,2,0,0,0,0,2,0,0,0,0,2],
[0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,0,0,2,0,0,2,0,0,2,0,0,0],
[0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0],
[2,0,0,0,0,1,0,0,0,0,2,0,0,0,0,2],
[0,0,0,2,0,0,1,0,0,2,0,0,2,0,0,0],
[0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0],
[0,0,0,2,0,0,2,0,0,1,0,0,2,0,0,0],
[2,0,0,0,0,2,0,0,0,0,1,0,0,0,0,2],
[0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0],
[0,0,0,2,0,0,2,0,0,2,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0],
[2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,1]];

C:=Eigenvectors(CF(4),M);

Print("C*M*C^-1 diagonal? : ",IsDiagonalMat(C*M*C^-1),"\n");
Print("C orthonal?        : ",TransposedMat(C)=C^-1,"\n");

gramschmidt:=function(V)local U,n,m,T,norm,k,h;
 norm:=v->Sqrt(v*v);
 T:=DimensionsMat(V);
 m:=T[1];n:=T[2];U:=NullMat(m,n);
 U[1]:=V[1]/norm(V[1]);
 for k in [2..m] do
  U[k]:=V[k];
  for h in [1..k-1] do
   U[k]:=U[k]-((U[h]*U[k])/(U[h]*U[h]))*U[h];
  od;
  U[k]:=U[k]/norm(U[k]);
 od;
 return U;end;

R:=gramschmidt(C);

Print("R*M*R^-1 diagonal? : ",IsDiagonalMat(R*M*R^-1),"\n");
Print("R orthonal?        : ",TransposedMat(R)=R^-1,"\n");

Comment: There is no buil-in routine for Gram-Schmidt (or other ONB), as orthonormalization introduces square roots, and thus might require field extensions. Why do you need the base change to be orthogonal?
Comment: I had written up a warning of the dangers of square roots already. I can take my answer down if you write one :-)
Comment: Yes, just redefine `norm := v -> 1;` and I think yours is fine.  It would be faster if it sorted by eigenvalue (since they are already orthogonal and don't need any updates)
Comment: Can you give an example M where you have trouble? There are a number of small things you might want fixed, but most of the big issues are handled automatically by Eigenvectors.
Comment: @ahulpke : I can live without orthonormality but I do need orthogonality because that simplifies calculations built on the results. I've posted my GS implementation; maybe it can be modified to avoid Sqrt...I'm not sure
Comment: @JackSchmidt : no need to take down your answer. I was pretty sure the slowness is because of the Sqrt...the simple change to norm does work : so now R*TransposedMat(R) is diagonal...that should be enough; thanks.
Answer: I'll try to answer without knowing exactly what part of Eigenvectors isn't what you want. The short version of my answer is:

Don't worry about the length of vectors. It is usually easy to adjust other algorithms to handle non unit-length vectors in a way that never needs square roots. GAP defaults to using exact square roots, and these are expensive in terms of time and space. You can use floating point in gap, but usually then another program is more suited (and sage would be an easy way to use that other program with gap).

Square roots in GAP (just don't)
GAP represents most numbers exactly. For example, $\sqrt{2}$ is part of a field $\mathbb{Q}[\sqrt{2}]$ with an abelian Galois group, so it is a subfield of the cyclotomic field CF(8). Indeed, Sqrt(2) gives E(8)-E(8)^3 ${}=\zeta_8 - \zeta_8^3$. Notice the decimal approximation or any other properties of the $\mathbb{R}$ number/embedding are not important to GAP, only the algebraic properties of the groups acting on it.
Unfortunately, this means that some vectors have much more cpu and memory hungry lengths than others. For example to compute the length of the vector [100,1] GAP will work with the roots $\zeta_{10001}$ living in a field of dimension 9792. Multiplication and division (and even addition and subtraction) will be at least 10,000 times slower than with a rational number.
Even worse, what if the length-squared is not a rational number? What if gasp the Galois group of the length is not abelian over the rationals? Then you will be forced to define the field extensions yourself. And what if you need two different square roots? Then you will need to form the composite field of the two extensions. At this point, I am usually using a GAP package that calls out to another algebra system that handles more number theory.
A sample session
I'm not sure whether you mean orthogonal or unitary. Set g:=1 to use orthogonal and g:=-1 to use unitary. Set n:=6 to use 6x6 matrices. Set c:=4 to use CF(4) as the field.
Step 0, choose your constants:
g := -1;;
n := 6;;
c := 4;;

Step 1, generate some sample data:
fld := CF(c);;
s := RandomMat(n,n,fld); s:= (s-TransposedMat(GaloisCyc(s,g)))/2;;
o := (s^0+s)*(s^0-s)^(-1);;
d := DiagonalMat(RandomMat(1,n,fld)[1]);;
M := o*d*o^-1;;
IsDiagonalMat(d); # always true
IsDiagonalMat(o*TransposedMat(GaloisCyc(o,g))); # always true
IsOne(o*TransposedMat(GaloisCyc(o,g))); # always true

Step 2, recover an eigendecomposition
C := Eigenvectors(fld,M);;
D := C*M*C^(-1);;
IsDiagonalMat(D); # always true
IsDiagonalMat(C*TransposedMat(GaloisCyc(C,g))); # usually true
IsOne(C*TransposedMat(GaloisCyc(C,g))); # usually false, but that is ok?

Step 3, make C be orthogonal
If the eigenvalues are distinct, then the eigenvectors are uniquely determined up to a scalar multiple, so the only correction needed (and the only correction possible) is to rescale them. However, it is very inefficient to take exact square roots of arbitrary cyclotomic numbers. For example, in GAP it is about 32 times more expensive to divide by the norm of a vector $\vec v$ with $\vec v \cdot \vec v = 30$ than it is to divide by the norm of a vector with $\vec v \cdot \vec v$ a perfect (rational) square. However, it is very cheap to divide by $\vec v \cdot \vec v$, so usually instead of requiring $\vec v \cdot \vec v = 1$, we just update our formulas to divide by it as required.
If the eigenvalues are not distinct, then you can apply a type of Gram-Schmidt orthogonalization just to the eigenvectors whose eigenvalues match. The only difference between the typical Gram-Schmidt is that you don't divide by the length. If you want the vectors to be "short" then you can use the built-in LLL, but if you only care about the rows being orthogonal, then you can just use the "root free" Gram-Schmidt.
Let me know if you want the code for Gram-Schmidt (zlattice.gi has it in a repeat loop, but it and my own version both assume you want a non-standard inner product, and so would need to be simplified for this answer).
Comment: For the matrices I work with,  $M$ and $C$ are real; I used that restriction to simplify things a l bit. I'll work with the root free GS from now on; I don't know how you would use LLL. What advantages could it give?
Comment: Real: yes, then all the GaloisCyc acts like the identity.  LLL: If you use LLL on a basis of the eigenspace for a specific eigenvalue, then it will find a basis whose vectors are as short as possible (under integer row ops). However, I think maybe it is not as useful to you, since (while it goes through a stage where everything is orthogonal) it may not end up with an orthogonal result.
Comment: I see. BTW nice use of cayley transform to get orthogonal from anti-symmetric; I've used something similar in the past...you do have to protect for non-invertible (s^0-s) though which can happen with some probability.

orthogonalization in GAP


Rewrite results for user picture to except tokens

Question: I have a user role called "Residents" in D7, and created a view the show profile information. I want to add colorbox to the User Picture, but there is only one token available [picture]. How do I add the image path as the destination if I can only use one token (see attachment)?
Comment: If you haven't got live users on the site, now is the time to stop using user picture and add an image field to the user entity instead. Much easier to work with, and you can then install modules that work with image fields and have them work right away.
Comment: I believe there's active users, but a high percentage of them don't have profile pictures. So that may be a good solution. Thanks!
Comment: I'll write it up as an answer.
Answer: Please take a look at these two solutions:
https://www.drupal.org/node/2396813#comment-11571515
and
Getting user photo url and profile url using views_json
Answer: Generally I would advocate using an image field on the user entity over the legacy user picture feature. The latter has a lot of limitations and you have just discovered one of them. If you try solving this issue by in the theme layer you'll find in the template that all you have to work with is an opaque "picture" variable containing the image html plus the original account object, meaning that to do anything different you have to re-implement the logic that generated the image html yourself. Not very helpful.
By using a custom image field you have access to a whole raft of contrib modules that integrate with it - including colorbox - without the need for custom code.


How to overcome the computational cost of the KNN algorithm?

Question: How to overcome the computational cost of the KNN algorithm when the dataset is large.
Bear in mind that I am using my own function for building the knn algorithm in R
Is there any manipulation to do with this?
I have tried dataset with 6000 instances and it takes a long time.
Note
wdbc_n is my normalized data set.
Lbl is the class label of the data set.
0.1 is the l norm as I defined within lpnorm function which I do not put here.
fx1NN<-function(TrainS, TestS,TrainLabel,p){
  n<-dim(TrainS)[1]
  Dist=matrix(0,nrow=n,ncol=1)
    for (i in 1:n){
      Dist[i]=lpnorm(as.matrix(TrainS[i,]-TestS),p)
    }
  Dist2=which.min(Dist)
  predL=TrainLabel[Dist2]
  return(predL)
}

LOOCV1NN<-function(Data,Lbl,p){
  N<-dim(Data)[1]
  predLOOCV=matrix(0,nrow=N,ncol=1)
  for (i in 1:N){
    LOOOCV_train=Data[-i,]
  LOOOCV_test=Data[i,]
  TLabel=Lbl[-i]
predLOOCV[i]=fx1NN(LOOOCV_train,LOOOCV_test,TLabel,p)
  }

  confM=confusionMatrix(factor(predLOOCV),factor(Lbl))
  R=as.matrix(confM)
  Recall=R[1,1]/sum(R[,1])
  Precision=R[1,1]/sum(R[1,])
  F1score=2/((1/Recall)+(1/Precision))
  CorClass=sum(predLOOCV==Lbl)
LL<-list(confM,CorClass,F1score)
  return(LL)
}
LOOCV1NN(wdbc_n,Lbl,0.1)

Comment: See cover tree and KD tree algorithms, implemented in R's FNN package.
Comment: To bring more attention to your post see our help at https://stats.stackexchange.com/help/no-one-answers.  But please stop making trivial edits: that's gaming the system and annoys regular users.
Comment: What is the dimensionality of your data, i.e. how many dimensions are there?
Comment: @HelloGoodbye, (6598) (168)
Answer: There's a large literature on speeding up nearest neighbor search, as well as numerous software libraries (you might consider using one of these instead of re-implementing from scratch). I'll describe some general classes of solutions below. Most of these methods aim to reduce the amount of computation by exploiting some kind of structure in the data.
Parallelization
One approach is to parallelize the computation (e.g. using a cluster, GPU, or multiple cores on a single machine). Rather than reducing the amount of computation, this strategy breaks the problem into multiple pieces that are solved simultaneously on different processing units. For example, Garcia et al. (2008) report large speedups by parallelizing brute force search using GPUs.
Exact space partitioning methods
This class of methods aims to reduce the number of distance computations needed to find nearest neighbors. The data points are used to build a tree structure that hierarchically partitions the data space. The tree can efficiently identify some data points that cannot be nearest neighbors of a new query point, so distances to these points don't need to be computed. Many algorithms exist using different types of trees. Common variants include KD trees, metric/ball trees, and cover trees. For example, see Kibriya and Frank (2007). Tree-based methods can be used to compute exact solutions (i.e. nearest neighbors match those found by brute force search). This approach is efficient for low dimensional data, but performance can degrade in high dimensional settings. There are also tree-based methods for approximate nearest neighbor search (see below).
Approximate nearest neighbor search
Larger speedups can be achieved (particularly for high dimensional data) if one is willing to settle for approximate nearest neighbors rather than exact nearest neighbors. This is often sufficient in practice, especially for large datasets. Many different strategies have been proposed for approximate nearest neighbor search. See Muja and Lowe (2014) for a review.
Methods based on locality sensitive hashing (LSH) are particularly popular (e.g. see Andoni and Indyk 2006). The idea here is to use specialized hash functions that efficiently map data points to discrete buckets, such that similar points end up in the same bucket. One can search for neighbors among the subset of training points that are mapped to the same buckets as the query point. The hash functions should be tailored to the distance metric used to define nearest neighbors.
There are also approximate nearest neighbor search algorithms based on space-partitioning trees and nearest neighbor graphs. For example, see Muja and Lowe (2014) and Liu et al. (2005).
Dimensionality reduction
Dimensionality reduction maps high dimensional data points to a lower dimensional space. Searching for neighbors in the lower dimensional space is faster because distance computations operate on fewer dimensions. Of course, one must take into account the computational cost of the mapping itself (which depends strongly on the method used). Note that nearest neighbor search in the low dimensional space is equivalent to using a different distance metric.
In some cases (depending on the method and structure of the data), it's possible to reduce the dimensionality such that nearest neighbors in the low dimensional space approximately match those in the high dimensional space. For supervised learning (e.g. KNN regression and classification), matching neighbors in the high dimensional space typically doesn't matter. Rather, the goal is to learn a function with good generalization performance. Dimensionality reduction can sometimes increase generalization performance by acting as a form of regularization, or by providing a space where distances are more meaningful to the problem.
There's a large literature on dimensionality reduction including linear, nonlinear, supervised, and unspervised methods. PCA is often the first thing people try because it's a standard method, works well in many cases, and scales efficiently to large datasets. But, whether it (or another method) will work well depends on the problem.
For an example application to nearest neighbor search, see Degalla and Bostrom (2006), comparing PCA and random projections for nearest neighbor classification.
Feature selection
Feature selection methods retain a subset of the input features and discard the rest. Typically, labels/target values from the training set are used to select features relevant for solving a classification or regression problem. Similar to dimensionality reduction, feature selection speeds up nearest neighbor search by reducing the number of dimensions. It is not generally aimed toward preserving distances.
Nearest prototypes
The idea here is to compress the training set into a smaller number of representative points (called prototypes). This speeds up neighbor search by reducing the number of points to search over. It can also have a denoising effect for supervised learning problems. Garcia et al. (2012) review various approaches.
Combining methods
Many of the techniques described above could be combined to yield even further speedups. For example, Pan and Manochoa (2011) and Gieseke et al. (2014) use GPUs to parallelize locality sensitive hashing and tree-based methods, respectively.
References

Andoni and Indyk (2006). Near-optimal hashing algorithms for approximate nearest neighbor in high dimensions.
Deegalla and Bostrom (2006). Reducing high-dimensional data by principal component analysis vs. random projection for nearest neighbor classification.
Garcia et al. (2008). Fast k nearest neighbor search using GPU.
Garcia et al. (2012). Prototype selection for nearest neighbor classification: Taxonomy and empirical study.
Gieseke et al. (2014). Buffer kd trees: processing massive nearest neighbor queries on GPUs.
Kibriya and Frank (2007). An empirical comparison of exact nearest neighbour algorithms.
Liu et al. (2005). An investigation of practical approximate nearest neighbor algorithms.
Muja and Lowe (2014). Scalable nearest neighbor algorithms for high dimensional data.
Pan and Manocha (2011). Fast GPU-based locality sensitive hashing for k-nearest neighbor computation.


DynamicMethod in Cecil

Question: Is there anything similar to Reflection.Emit.DynamicMethod in Cecil? Thanks.

DynamicMethod

Edit:
What about for the following things?

EmitCall  (e.g.
IL.EmitCall(OpCodes.Callvirt, GetBuildKey, null);
IL.Emit(OpCodes.Unbox_Any, dependencyType);
)
LocalBuilder   (e.g. LocalBuilder resolving = ilContext.IL.DeclareLocal(typeof(bool));)
System.Reflection.Emit.Label   (e.g. Label existingObjectNotNull = buildContext.IL.DefineLabel();)    //Do I have to use TextMap?
ILGenerator.BeginCatchBlock (e.g.  ilContext.IL.BeginCatchBlock(typeof(Exception)); )
ILGenerator.MarkLabel  (e.g. ilContext.IL.MarkLabel(parameterResolveFailed); )
ILGenerator.EndExceptionBlock()  (e.g. ilContext.IL.EndExceptionBlock(); )
Comment: Is cecil mono library, right? I have added a tag *mono*
Comment: @Michael, you moving from .Net to mono or just testing it out? Oh, btw, I think we know each others before.
Comment: I'm just testing and reading some codes of Cecil. I have a few friends called "Mark".. maybe, you are one of my friends "Mark" that i know. :) Are you from China? or SG? But SG doesn't ban Google. :) Give me some hints. man.. :)
Comment: @Michael, you recently posted about Silverlight user meet up on MITP, right? search "Mark" there, top result is me.
Comment: oh! okay.. I know you.. we had a few conversions before in other forum.. cool. man. good to see you here..
Comment: maybe.. EmitCall  = callWriteLine = worker.Create(OpCodes.Call, writeLine); but for Label, I think i need to create an instruction..
Comment: seems like noone are not that familiar with Cecil.
Answer: There's no way to create a DynamicMethod with Cecil, nor does it have an equivalent.
A DynamicMethod is strongly tied to the runtime, while Cecil is completely decoupled. The two of them have a completely separate type system. DynamicMethod are meant to be, well, dynamic, and as such have to use the System.Reflection type system, as it's the one available at runtime. Mono.Cecil has another representation of this type system suitable to static analysis, without having to actually load the assembly at runtime. So if you want to use a DynamicMethod, you have to use it along with its environment.
This question was originally asked, iirc, in the context of runtimes without DynamicMethods or SRE all-together, like the Compact Framework, where Cecil can be used to emit code at runtime.
Of course it's possible, but then you have to pay the price of loading the assembly, which is no small price on CF devices. It means that if you could somehow emulate a DynamicMethod by creating an assembly with only one static method with Cecil, it sounds a terrible idea. The assemblies would not be collectable (DynamicMethods are), making it a giant memory leak.
If you need to emit code at runtime on the Compact Framework, emit as less as possible, and emit as few assemblies as possible.

DynamicMethod in Cecil


Filter Taxonomy reference field on Workbench Access permission

Question:
i need some help with Workbench access based on taxonomy.
This is my use case:
I have this taxonomy structure for my site:
 - Term A
 - Term B
 - Term C
And i have 2 roles:
 - editor
 - editor C
Editor c users must be able to create or update only the term C nodes.
I installed Workbench, Workbench Access and Field Property to control this behavior.
I configured Workbench Access on Taxonomy.
In admin/config/workbench/access/roles i put Roles "Editor C" only in "Term C" Section.
I created in each content type a Taxonomy Reference field, based on Workbench Access (i checked "Workbench Access control field").
So this fields has two purposes:
 - tagging the node on my taxonomy structure
 - Assign the proper editorial group
The problem:
When an Editor C user adds a content, he can select any term value, not only "Term C".
In other words the  Taxonomy Reference field display all result.
How can i filter/limit the record of taxonomy reference on workbench access permission?
P.S.
If i check "Require a Workbench Access form element" in admin/config/workbench/access/settings the module add a "core" access control field in each content type.
This fields are filtered on Workbench access permission but i loose my first purpose (tagging the node on my taxonomy structure).
Can anyone help me?
Thanks in advance,
Matteo
Answer: You must install Taxonomy Access Control module. Follow this steps:
1) Enable the module.
2) Go to admin/config/people/taxonomy_access
3) Click configure link for role "editor"
4) Click "Add vocabulary" link. Then select the vocabulary where you have terms "Term A", "Term B" and "Term C" and press "Add" button.
5) Click "Add term" link. Select "Term A". Configure permissions for this role and term (you should select "Allow" in every case). Once done press "Add" button.
6) Do the same for Term B
7) Do the same for Term C, but this time select "Deny" in every case.
8) Press button "Save all"
9) Go to previous window and do the same but this time for role "editor c". However you have to do the opposite: Terms A and B should have "Deny" in every case and Term B should have "Allow" in every case.
I hope this helps you! If it doesn't, you should checkout the Organic Groups module too. In case you need Organic Groups notice you also have OG Vocabulary module.


Way to update css properties on-the-fly based on form content?

Question: I have a form on a website, in which one of the inputs is to be used to enter hexadecimal colour codes to be entered into a database.
Is there any way for the page to dynamically update itself so that if the user changes the value from "000000" to "ffffff", the "colour" CSS property of the input box will change immediately, without a page reload?
Answer: Not without Javascript.
With Javascript, however...
<input type='text' name='color' id='color'>

And then:
var color = document.getElementById('color');
color.onchange = function() {
    color.style.color = '#' + this.value;
}

If you are going to go the Javascript route, though, you might as well go all out and give them a color picker. There are plenty of good ones.
Answer: CSS properties have corresponding entries in the HTML DOM, which can be modified through Javascript.
This list is somewhat out of date, but it gives you some common CSS pieces and their corresponding DOM property names.
Granted, a JS lib like like jQuery makes this easier...
Answer: You can use Javascript to achieve that.
As an example:
Your HTML:
<input type="text" id="test" />

Your JS:
var test = document.getElementById('test');
test.onchange = function(){
    test.style.color = this.value;
};

But this doesn't check the user's input (So you would have to extend it).


Input on console doesn't work with this java program - why?

Question: With this program it skips past the inputs - and outputs this to the console:
    C:\Users\User\workspace\ClassManager\bin>java AccessPupilData
What would you like to do?
l = list pupils -------- a = add pupil ---------
a
a
You want to add a pupil.
Enter your first name:
Enter your surname:
Firstname :null
Surname: null
Age :0
You created a pupil called null null who is aged 0

(I'm using a dos prompt to run the program in, not the eclipse console). Why don't I get to input when the scanner is called?
First the initial class that kicks off everything:

public class AccessPupilData {

public static void main (String arguments[]){

...
case 'a': Pupil pupil = new Pupil(); break;

And then the Pupil class that is where I want to collect all the information:
import java.util.Scanner;

public class Pupil {
    private String surname;
    private String firstname;
    private int age;

public Pupil(){

    Scanner in = new Scanner(System.in);

       // Reads a single line from the console
       // and stores into name variable
       System.out.println("Enter your first name: ");
       if(in.hasNext()){
           this.firstname = in.nextLine();
       }

       System.out.println("Enter your surname: ");
       if(in.hasNext()){
           this.surname = in.nextLine();
       }
       // Reads a integer from the console
       // and stores into age variable
       if(in.hasNext()){
       System.out.println("Enter your age: ");
       this.age=in.nextInt();
       }
       in.close();

       // Prints name and age to the console

       System.out.println("Firstname :" +firstname);
       System.out.println("Surname: " + surname);
       System.out.println("Age :"+ age);

    System.out.print("You created a pupil called " + this.firstname + " " + this.surname + " who is aged " + this.age);
}

}
Answer: Use Console.readLine
Console c = System.console();
this.firstname = c.readLine("Enter your first name: ");

Comment: I'm still getting errors if I change the code to this (with the relevant import): Exception in thread "main" java.lang.NullPointerException
        at Pupil.(Pupil.java:16)
        at AccessPupilData.main(AccessPupilData.java:12)
Comment: I agree that Console is a better option, but the fact that he is using Scanner is IMO not the source of problem. I tried his code with Scanner and it works for me ( hasNext() methods block waiting for input from System.in ).
Comment: Ln16: this.firstname = c.readLine("Enter your first name: ");
Comment: I'm open to any method - I'm learning java myself and so am appreciative of any particular method that proves succesful.
Comment: If you have a NPE in that line you didn't instantiate c (see me first line of code).
Comment: I did put Console c = System.console(); before that.
Comment: Can you try this?
Console c = System.console();
if (c == null) throw new RuntimeException("Could not get console.");
Comment: C:\Users\User\workspace\ClassManager\bin>java AccessPupilData
What would you like to do?
l = list pupils -------- a = add pupil ---------
a
a
You want to add a pupil.
Enter your first name:
Exception in thread "main" java.util.NoSuchElementException: No line found
        at java.util.Scanner.nextLine(Unknown Source)
        at Pupil.(Pupil.java:22)
        at AccessPupilData.main(AccessPupilData.java:12)
Comment: Sorry I didn't come back anymore, busy week. Replace all the input code with the Console alternative.
Comment: It's fixed - replacing everythingn worked. I think I was using a scanner in another class (PupilMenu) which then must have interfered with the console. Thanks.
Answer: I would suggest using BufferedReader
Scanner is definitely very convenient to use but it is slower since it has to read the content of the stream every time next token in the stream is requested. While Buffered Reader buffers the tokens so that there is no need to read from the stream again. Quoted from Scanner vs BufferedReader.
public static void main(String[] args) {
    String firstName = getInput("Enter your first name: ");
    System.out.println("Hello " + firstName);
}

public static String getInput(String prompt) {
    BufferedReader in = new BufferedReader(
            new InputStreamReader(System.in));

    System.out.print(prompt);
    System.out.flush();

    try {
        return in.readLine();
    } catch (IOException e) {
        return "Error: " + e.getMessage();
    }

}