Expand Bass Guitar Playing Beyond Root Notes

Question: I am fairly new to the bass guitar and I'm in a band.  So far, I almost always just play the root note of the chord.  I sometimes hold it until a new chord and sometimes repeatedly play this same note.
The root notes I commonly play are C, D, B, F#, E, etc.   For example, a song may be D G Bm A.
What I am doing is fine, but I feel like it would be great to branch out and play things besides just the root.  How should I go about this?  What are examples?
Answer: There are many different ways to approach playing bass and depending on what style you are trying to go for it may be all you need to fill the sound. I'll explain a few simple styles and techniques that can spice up a bass line.
Octaves
Rather simple, but effective. Your still playing only the root note, but changing the octave is a very simple and effective way to make the bass line pop a little more as the octave jump will stand out and is used a lot when creating bass lines.
Arpeggiation
A little more movement you can move from the root note of a chord to the other notes of the chord. For example if you start out playing the root note of a G major chord you can play the 3rd (B) or 5th (D) of the chord no problem. As long as you start on the root and play chord tones you should be fine. Even simpler most bassist when they arpeggiate only uses the root, fifth, and octave above. It's simple but it's effective and is used in many different techniques including alberti bass (for piano).
Chromatic/Diatonic Moment
A very effective method utilize non-chord tones as a bassist is to move step wise to move from one chord to another. For example if the harmony was going from a C to Dm, you could play the root note C and then play a C# before you play the root of the Dm chord. Again very simple, but effective.  Another example is if you were going from Dm to F, you could play an E while transitioning between the two chords as mentioned above.
Walking Bass
Pretty much a combination of everything mentioned above. It's a very nice technique to learn as a bassist even if you don't play songs that would work with this technique because you learn how to "move" a lot as a bassist. Here is more detail on how to create a walking bass line.

There are other techniques, but try to explore these first. At the end of the day do what sounds good to you.
Comment: Also consider the bass like a drum/percussion instrument. Experiment with slides or different speeds, and think about syncopation and altering how long you hold each note for - how much space is left between tones. And of course the interplay with the snare drum and how you lock in with the drummer. Consider jumping in on parts of the melody.
Comment: Inversions are also a solid approach but may not be the best starting point.  So maybe after these are tackled you could look into inversions.
Answer: The first suggestion I would make is learn some music theory. While not necessary, music theory can help make sense of what your doing. For example, lets say there is a song that rotates through a very basic I-V-vi-IV progression. Music theory will help you understand not only how the notes of each chord relate to each other but also allow you know what notes make up the chord. Ultimately, this knowledge will create a basis for what notes you could play. From there it a matter of deciding what you want add or support in the progression. Keep in mind this is a very general sweeping concept that has very specific components to it.
The second suggestion I would make is listen to bassists that try to take a more dominant roles in the mix. Furthermore, do not exclude genre of music that you dislike. Why shouldn't you avoid bassists that play in bands that you know you don't like? because your not trying like the music your trying to learn. After all one doesn't have to like their school teacher to learn from them. If my general point isn't self-explanatory then let me make it clear. Learn from other bassists and "semi-steal" their ideas.
The third and probably the most important suggestion is  take the risk and improvise (music theory can help with improvising). I mean the worst that can happen is you make some dissonance and you learn from you mistake.
To ensure clarity let me further define "semi-steal". Semi-steal is reference to the idea that when you learn a musical phrase from another artist you rebuild or reinvent the phrase in a way that suits the song or your own personal style.
As for the lack examples... I can think of a few but in reality all I am really doing is check out what this bassist is doing in front of x,y,z chords.
Answer: For instance this?

    choord: | D       |         | G       |          | D       |          |
    note:   | D - - - | A - - - | G - - - | - A B C# | D - - A | D E D C# |

    Bm       |          | G ...
    B - - F# | B C# B A | G ...

Most commonly, the bass would play the root (1st) and the dominant (5th), and less commonly other notes of the appropriate choords. You can as well some bass melodies to connect the choords, and the rhytms need not be plain at all.


Como faço para voltar check in que eu fiz no TFVC?

Question: Preciso voltar atrás em alguns check ins, não queria ter que buscar o último código válido e fazer check in por cima, e sim apagar essas entradas no controle de versão. É possível fazer?
Answer: Se o seu código está no TFVC, antes existia uma funcionalidade de Rollback no Team Foundation Power Tools, ela foi movida para o TF.exe!
Para usar:
<code>tf rollback /changeset:changesetfrom~changesetto [itemspec] [/recursive]
[/lock:none|checkin|checkout] [/version:versionspec]
[/keepmergehistory] [/noprompt] [/login:username,[password]]

tf rollback /toversion:versionspec itemspec [/recursive]
[/lock:none|checkin|checkout] [/version:versionspec]
[/keepmergehistory] [/noprompt] [/login:username,[password]]
</code>
Para voltar para uma versão específica o parâmetro que deve ser utilizado é o /toversion
A ajuda para o comando pode ser encontrada aqui: http://msdn.microsoft.com/en-us/library/dd380776.aspx
Também é possível executar no VS.Net de maneira visual: http://msdn.microsoft.com/en-us/library/ms194956.aspx#to_one
Comment: Não tenho reputação suficiente pra dar upvote (ainda), mas isso resolve meu problema. Muito obrigado!!


Dropdown selection populates div with hidden buttons that then populate another div with hidden content on click

Question: I am trying to make a somewhat complicated form... and perhaps am making it more complicated than it needs to be!
The title says it all:

Select dropdown option
Based on dropdown selection, the designated div #info is populated with a hidden set of buttons (and changes button set based on which option is selected).
Those buttons can then be clicked to display hidden content in the additional designated div #info2 (which also changes content based on the button clicked).

In my fiddle, I tried to show what I am attempting to do, only I used buttons in place of the dropdown.
I hope this makes sense!
Edit: I want to be able to click/navigate freely between all buttons and dropdowns, in that when a particular choice is clicked, any content related to the previous choice will be removed from the div which will then be populated by the current div choice content.

$(document).ready(function (){
    $('.buttons button').click(function (){
        $('#info').empty();
        $('#info').html($("#" + $(this).data('link')).html());
    });

 });

<button id="button1" data-link="option1">Button 1</button>

<button id="button2" data-link="option2">Button 2</button>

<button id="button3" data-link="option3">Button 3</button>

<button id="button1" data-link="option4">Option 4</button>

<button id="button2" data-link="option5">Option 5</button>

<button id="button3" data-link="option6">Option 6</button>

<button id="button1" data-link="option7">Option 7</button>

<button id="button2" data-link="option8">Option 8</button>

<button id="button3" data-link="option9">Option 9</button>

<button id="button1" data-link="option10">Option 10</button>

<button id="button2" data-link="option11">Option 11</button>

<button id="button3" data-link="option12">Option 12</button>

<button id="button1" data-link="option10">Fee</button>

<button id="button2" data-link="option11">Fi</button>

<button id="button3" data-link="option12">Foo</button>

Here's my fiddle
Answer: Okay, so here it goes...
Let's say you have a select field:

function func() {
  var val = document.getElementById("select").value;

  if(val == "bla") {
    document.getElementById("bla").style.visibility = "visible";
  }

  if(val == "blo") {
    document.getElementById("blo").style.visibility = "visible";
  }
}
<select id="select" onchange="func()">
  <option value="" disabled selected style="display:none;">Label 1</option>
  <option value="bla">bla</option>
  <option value="blo">blo</option>
</select>

Do you get the idea?
I'm sorry, I just saw that you used jQuery........... You would have smth like a class with visibility:hidden and toggle it with jQuery... The equivalent event  would be change(). Well, this still should ring a bell. If you need further help (like with jQuery) don't hesitate to ask.
:-)
Comment: I think I see what you are saying here, but it's not quite the answer I am looking for. In your code example, I clicked on one dropdown selection and then the other, but the previous content did not disappear. I get how dropdowns work, but I don't know how to connect them with hidden content to populate a div. If you look at my fiddle, you'll (hopefully) see what I am trying to do.
Comment: I did look at your fiddle. Thats why i mentioned jQuery's toggle. Well give me a second, I will code you something working really quick.
Answer: So here is the other approach...

$(document).ready(function (){
    $('.buttons button').click(function (){
        $('#info').empty();
        $('#info').html($("#" + $(this).data('link')).html());
    });
});

function func() {
    $(".info").each(function() {
        $(this).css("display", "none");
    });

    var val = $("#select").val();

    if(val == "bla") {
        $("#option1").css("display", "block");
    }

    if(val == "blo") {
        $("#option2").css("display", "block");
    }
}
#button-column {
  display: inline;
  float: left;
}
button {
    font-size: 10px;
    width: 50px;
    height: 30px;
    margin: 15px;
}

#info {
    width: 200px;
    height: 200px;
    padding-top: 37.5px;
    border: 1px solid black;
    display: inline;
    float: left;
    text-align: center;
}

.info {
 display:none;
}

        <select id="select" onchange="func()">
            <option value="" disabled selected style="display:none;">Label 1</option>
            <option value="bla">bla</option>
            <option value="blo">blo</option>
        </select>

<button id="button1" data-link="option4">Option 1</button>

<button id="button2" data-link="option5">Option 2</button>

<button id="button3" data-link="option6">Option 3</button>

<button id="button1" data-link="option4">Option 4</button>

<button id="button2" data-link="option5">Option 5</button>

<button id="button3" data-link="option6">Option 6</button>

The code itself shouldn't be too hard to understand. If you have trouble though, I can break it down for you :-)
Comment: Thanks for trying again -- still not quite what I am looking for. Two primary problems here: I can move between the two dropdown divs but when I click one of the buttons that populate the div, I am unable to move back to the other dropdown. Second problem is that there is no additional div (see #info2 in my example) being populated with content when you click one of the buttons. I am going for the ability to navigate freely between dropdown options, buttons. Any thoughts?
Comment: I think I figured it out. Thanks so much for your suggestions!
Comment: Oh okay, I only intended on showing in which direction this could go. But I'm happy you managed nevertheless!


What is this scale: (Bb, C#, D, Eb, F#, G, A, Bb)

Question: I merged Bb major and D major to see what comes up. The scale has the notes: Bb, C#, D, Eb, F#, G, A, Bb.
What scale is this?
Can I have chords in this scale?
Let me know!
Notation for the scale:
Comment: What makes you think it is a scale in its own right, other than just a bunch of notes in order? Most scales (minors apart) will have only # *or* b in them. Your header goes to B#, while the body goes to Bb. Spurious..!
Comment: The definition of scale calls for a set scheme to a set of notes.  Cannot any set of notes be written ascending or descending then a scheme be assigned to it?
Answer: Assuming you meant for the scale to go from Bb to Bb and not from Bb to B# (???), it's apparently called the Ionian ♯2 ♯5 scale.
I found out by going through Wikipedia's category Musical scales with augmented seconds.
Relevant article here.
And, uh, yes, sure you can find chords that will be diatonic with that scale. (That's generally true about pretty much any scale.) Just at a glance I see Bb+, D, Eb or Gmi.
Answer: AFAIK there's no generally recognised name for this scale other than a simple description like 'Major with #2 and #5'.
Sure, you can build chords from this set of notes.   You can build chords from ANY set of notes. There's even some major and minor triads in there!
Comment: This is not a random scale, as Divizna points, it's a mode of double harmonic scale.
Comment: @user1079505 And yet the article I found doesn't give a name other than "Ionian #2 #5" either, which says exactly the same as "major with #2 and #5".
Comment: If you have to dig deep into the Internet to find a single instance of a label for something, it's a fair indication that that label won't be generally understood.  Stick to the descriptive name.


Janela modal com conteúdo do banco de dados

Question: Eu até sei os PHP e Javascript, o problema é que eu não sei como criar o modal de forma dinâmica para cada clique em um link, trazer informações especificas daquele link. Se clicar no usuário 1, trazer informações na janela modal do usuário 1, se clicar no usuário 2, mostrar informações do usuário 2, e assim por diante.
Eis o que eu tenho até agora, não sou muito experiente em Jquery, creio que dai a minha maior dificuldade em resolver esse problema
$(document).ready(function()
{
    //Show modal box
    $('.showdialog').click(function(e) {
        $('#dialog').show();
        e.preventDefault();
    })

    //Hide modal box
    $('.closeModal').click(function(){
        $('.mask').hide();
    });
});

Usuário 1
Usuário 2

Segue-se uma lista de links vindos do banco de dados, nos resultados do banco, não tem erro, fora da janela os resultados aparecem normalmente.
Comment: Não sabe PHP com DB, ou não sabe criar o modal? Veja um exemplo de [*modal*](http://getbootstrap.com/javascript/#modals)
Comment: [Duplicata](http://pt.stackoverflow.com/questions/31812/janela-modal-exibir-conte%C3%BAdo-vindo-do-banco-de-dados-mysql-php)
Comment: Eu até sei os dois, o problema é que eu não sei como criar o modal de forma dinâmica, a cada clique em um link, trazer informações especificas daquele link, Se clicar no usuário 1, trazer informações na janela modal do usuário 1, se clicar no 2, mostrar informações do usuário 2, e assim por diante,espero que tenha ficado claro!!!
Comment: JS é bem flexível e acaba tendo N respostas com o mesmo efeito, então recomendo você mostrar o que tem feito para podermos ajudar.
Comment: Bom, desculpe se não ajudar. Mas eu faria assim: as informações poderiam vir via ajax. Eu passaria como parametro o id do usuario e retornaria todos os dados dele. No momento em que o ajax devolvesse esses dados eu criaria o html do modal e ativaria o modal com o js. Se achar que isso ajuda eu monto um código de exemplo.
Answer: Criei um jsfiddle bem básico. O loop vai criar uma div oculta para receber as informações e o modal vai usa-las e aceita formatação. Espero que sirva como base para você montar seu modelo.
Seu loop monta uma div id="usuario1" para link e uma div id="data_usuario1" com a formatação em HTML.
JS
$(document).ready(function()
{
    $("a").click(function () {
        var id = $(this).attr('id');
        $('#myModal').modal('show');
        $("#conteudoModal").html($('#data_'+id).text());
    });
});

HTML / PHP
Opção manual
usuário 1

Dados do usuário 1

Opção simulando loop de registros
for($i = 1; $i <= 10; $i++)
{
    echo 'usuário '.$i.'
';
    echo '
Dados do usuário '.$i.'
';
}

Html da janela modal

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

Paginas

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

arquivos
ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
http://getbootstrap.com/dist/js/bootstrap.min.js
http://getbootstrap.com/dist/css/bootstrap.min.css

Comment: Muito obrigado pela ajuda Papa Charlie!!! o código que você mandou funciona do jeito que eu preciso, vou adaptar ao meu projeto!!!
Comment: @Wilerson Vaz, se resolveu, clique na resposta para aceitar e de uma lida no FAQ [como perguntar](http://pt.stackoverflow.com/help/asking).
Comment: @WilersonVaz, confira o guia [*Como e por que aceitar uma resposta?*](http://meta.pt.stackoverflow.com/q/1078/201)
Answer: Olá pessoal queria ajuda de vocês, eu fiz o exemplo passado acima e funcionou, porém eu apliquei em meu projeto e não estou tendo sucesso, será que vocês podem me ajudar?
Abaixo os códigos utilizados.
echo ''
echo '
'.$sequencial.'
';
echo '
'.$descricao.'
';
echo '
'.$quantidade.'
';
echo '
'.$valor_item.'
';

e abaixo o javascript


NetStream receiving events after being closed

Question: I'm developing a one-on-one video chat application using Wowza. After the remote client stops publishing, I'm disconnecting the incoming NetStream. Here's a gist of my code:
incomingStream = new NetStream(netConnection);
incomingStream.addEventListener(NetStatusEvent.NET_STATUS, incomingStreamHandler);
incomingStream.play("media");

private function incomingStreamHandler(event:NetStatusEvent):void
{
    trace(event.info.code);
    if (event.info.code == "NetStream.Play.UnpublishNotify")
    {
        incomingStream.close();
        incomingStream.removeEventListener(NetStatusEvent.NET_STATUS, incomingStreamHandler);
        incomingStream = null;
    }
}

Here's the problem: after the NetStream.Play.UnpublishNotify event fires and I close the incoming stream, I receive the following runtime error:
Error #2044: Unhandled NetStatusEvent:. level=error, code=NetStream.Play.StreamNotFound

If I comment out the removeEventListener() line in incomingStreamHandler() above, I see that NetStream.Play.UnpublishNotify is followed by NetStream.Play.StreamNotFound. But why does this event still fire even after I close the incoming NetStream?
(Initially, I was disconnecting the incoming stream on NetStream.Play.StreamNotFound instead of NetStream.Play.UnpublishNotify but I found that the former event doesn't always fire so I want to rely on NetStream.Play.UnpublishNotify instead.)
Answer: Try moving:
incomingStream.removeEventListener(NetStatusEvent.NET_STATUS, incomingStreamHandler);
over
trace(event.info.code);
I hope it works...


How do I go about sorting this kind of object?

Question: Here is my object
{
    "1MON": "1",
    "1TUE": "1",
    "2TUE": "2",
    "3WED": "3",
    "6FRI": "6"
}

I have been trying to search hoping to get an answer but no luck.
I want to use the values to sort it
The expected output is
{
    "1MON": "1",
    "1TUE": "1",
    "2TUE": "2",
    "3WED": "3"
}

and then later on, I want to loop on it to remove the values and create a string like 1MON1TUE2TUE3WED6FRI. The reason why  i am doing this is that i want to add HTML classes like class="class-1MON1TUE2TUE3WED6FRI" and when i want to remove 1 slot in that class i will use myClassAsString.replace(/1TUE/g, "") please help me!
Comment: you should start implementing your code and come back if you are stuck... stackoverflow is not exactly a place where you ask work to be done for you
Comment: The code is up there, I thik mentioned what i need
Comment: Forklif, I tried putting it in an array and some are saying  that JavaScript Arrays do not support keys
Comment: Look at toastal's answer short and simple
Answer: Object keys in JavaScript aren't sorted and you can never expect them to be. You need to convert to an Array for that behavior.
const x = { "1MON": "2", "1TUE": "1", "2TUE": "2", "3WED": "3", "6FRI": "6" }

Object.entries(x)
  .sort(([,a], [,b]) => a > b)
  .map(([y]) => y)
  .join("")
//=> "1MON1TUE12TUE3WED6FRI"

Comment: This answer sorts by keys, not values, but that may not matter?
Comment: You're right... the question wasn't very clear, but I updated it.
Answer: For Sorting you can try like this.

Get All the properties of the Object using Object.keys(obj);
Sort Items in the array by using the Comparer callback function for strings.

var obj = {"1MON":"1","1TUE":"1","2TUE":"2","3WED":"3","6FRI":"6"};
var allProperties = Object.keys(obj);
var sortedResult = allProperties.sort( (first, second) => first.localeCompare(second) );

console.log(sortedResult)


Stack implementation of DFS. All test cases work except the first

Question: From https://structy.net/problems/largest-component
Write a function, largestComponent, that takes in the adjacency list of an undirected graph. The function should return the size of the largest connected component in the graph.
The problem is this code works for all test cases except the first one. And i do not want to solve this with the recursive DFS method i want to use the stack or queue DFS method.
The main function
const largestComponent = (graph) => {
    //init the largest count variable to 0
    let largest=0;
    // use a global set data structure to keep track of visited nodes
    let visited =  new Set();

    //loop through graph object and send each node to DFS function
    for (node in graph) {
        //if node has been visited then skip to next node
        if(visited.has(String(node))) continue;

        let currentCount = DFS(graph, node, visited);

        // get largest count per iteration
        largest = Math.max(largest, currentCount);

    }
    // return result
    return largest;
}

The depth first search function
const DFS = (graph, node, visited) => {

    // initiate count for neighbors of current node but also count current node so init to 1
    let currentCount = 1;

    // populate stack with node
    let stack = [node];

    //loop for as long as stack isn't empty
    while(!!stack.length){

        // get current node from stack
        let current = stack.pop();

        // mark node as visited
        visited.add(String(current));

        // loop through neighbors of node
        for( neighbor of graph[current]){

            // if neighbors have been visited already then skip them
            if(visited.has(String(neighbor))){
                continue;
            } else {
                // add neighbor to count
                currentCount++;

                // add the next neighbor to stack
                stack.push(neighbor);
            }
        }
    }
    // return count of connected components for current node
    return currentCount;
}

Test case 1
console.log(largestComponent({
  0: ['8', '1', '5'],
  1: ['0'],
  5: ['0', '8'],
  8: ['0', '5'],
  2: ['3', '4'],
  3: ['2', '4'],
  4: ['3', '2']
})) // should give -> 4

Test case 2
console.log(largestComponent({
  1: ['2'],
  2: ['1','8'],
  6: ['7'],
  9: ['8'],
  7: ['6', '8'],
  8: ['9', '7', '2']
})); // should give  -> 6

Test case 3
console.log(largestComponent({
  3: [],
  4: ['6'],
  6: ['4', '5', '7', '8'],
  8: ['6'],
  7: ['6'],
  5: ['6'],
  1: ['2'],
  2: ['1']
})); // should give -> 5

Test case 4
console.log(largestComponent({
  0: ['4','7'],
  1: [],
  2: [],
  3: ['6'],
  4: ['0'],
  6: ['3'],
  7: ['0'],
  8: []
})); // should give -> 3

Answer: Cause
What happens in Test case 1 is that you are counting 8 twice (once when current is 0 and once when current is 5).
Step by step:

Current node is 0, currentCount=1, stack=[], visited=[]

Mark 0 as visited -> [0]
Add to stack: 8, 1, 5 -> [8, 1, 5]
Current count becomes: 1 + 3

Current node is 5, currentCount=4, stack=[8, 1] (pop 5), visited=[0]

Mark 5 as visited -> [0, 5]
Add to stack: 8 (0 is visited, but 8 still not) -> [8, 1, 8]
Current count becomes: 4 + 1  here is the problem

Solution
This can be solved changing three things:

Count nodes when visited (not when checking neighbors).
As a consecuense of point 1, start the currentCount variable at 0.
Check if the current node poped from stack hasn't been visited.

Code
The final code will be like this:
const largestComponent = (graph) => {
    //init the largest count variable to 0
    let largest=0;
    // use a global set data structure to keep track of visited nodes
    let visited =  new Set();

    //loop through graph object and send each node to DFS function
    for (node in graph) {
        //if node has been visited then skip to next node
        if(visited.has(String(node))) continue;

        let currentCount = DFS(graph, node, visited);

        // get largest count per iteration
        largest = Math.max(largest, currentCount);

    }
    // return result
    return largest;
}

const DFS = (graph, node, visited) => {

    // count starts at 0, `node` will always be counted in the first iteration
    let currentCount = 0;

    // populate stack with node
    let stack = [node];

    //loop for as long as stack isn't empty
    while(!!stack.length) {

        // get current node from stack
        let current = stack.pop();

        // if current node has been visited then skip to next node
        if (visited.has(String(current))) continue;

        // mark node as visited and count it
        visited.add(String(current));
        currentCount++;

        // loop through neighbors of node
        for( neighbor of graph[current]){

            // if neighbors have been visited already then skip them
            if(visited.has(String(neighbor))){
                continue;
            } else {
                // add the next neighbor to stack
                stack.push(neighbor);
            }
        }
    }
    // return count of connected components for current node
    return currentCount;
}


Example for monotone convergence

Question: I'm searching for an example of sequence of function in which if doesn't exist a Lebesgue integrable function g that increases the sequence, then the equality in the convergence theorem is not anymore maintained.
Thank you.
Comment: " if doesn't exist a Lebesgue integrable function g that increases the sequence" : what do you mean ? The monotone convergence theorem is true from the moment you have a positive increasing sequence; there is no more condition.
Comment: @TheSilverDoe yes, I want to prove what you wrote: if I haven't the positive increasing then the theorem in not valid.
Answer: Take
$$f_n(t) = \left\{
    \begin{array}{ll}
       1 & \mbox{if } t \geq n \\
        0 & \mbox{otherwise.}
    \end{array}
\right.$$
Then $$\int \lim_{n \rightarrow +\infty} f_n = 0 \neq +\infty = \lim_{n \rightarrow +\infty} \int f_n$$
You see here that the theorem is wrong if the sequence is decreasing.

Example for monotone convergence


CSS Sprites performance

Question: I have static image 500x640 sitting in folder catted by 20x20 pieces with css sprites, I am setting background-position to display each piece, I need such kind of display to be able to manipulate with each piece later.
css:
   .piece
        {
            width: 20px;
            height: 20px;
            display: inline-block;
            //display: inline;
            //zoom:1;
        }

    .ob { background-image: url("/Images/ob.jpg");}

js:

function div(val, by){
    return (val - val % by) / by;
}

So am having some performance issues.
For example in Opera and FF images loading very quickly about 1 sec, in IE about 3 sec, but in Chrome it is loading very slow
it is taking about 17 sec to display all pieces in Chrome...
Browser doing just one request to get the image and than cutting small pieces from it, why it may take so long in Chrome?
Is there any way i can improve performance?

just did CTRL+Refresh and here strange loading result:

UPDATE:
I just placed a sample here: http://bit.ly/TrcCdp
UPDATE:
In my sample there is JSON array, it is contains 800 elements, so I just find out if I make it less, eg 600-700 elements the performance is getting better, but I need 800 elements anyway.
e.g When there is only 600 elements it is reducing the load in Chrome to about 6 sec....
So probably may be the problem somewhere at the point where knockout iterating template?
Comment: I don't think the problem is related to your images. Why are you requesting images after the js? Put css and images first and later JS and see if the problem will continue..
Comment: Sorry, the picture's a little small. How big is your sprite?
Comment: @canon if you right click on image and press open it will open in real size(http://i.stack.imgur.com/WGdAr.jpg). My sprite is 83.78kb.
Comment: @SLaks i will see what i can do, it may take some time.
Comment: That's odd, you get a 304 Not Modified response, yet it takes 17 seconds for it to load. Does loading the image manually (e.g. navigating to it) also take long?
Comment: Try clearing you cache (CTRL+Refresh), see if that helps.
Comment: @pimvdb not it is not, it is loading very quick when navigating, even when chrome loading file from the cache - same thing taking too long.
Comment: @Truth just did CTRL+Refresh - same thing...no luck.
Comment: How do you request the image? Is it a background image or do you load it with JavaScript?
Comment: @Torsten Walterbackground-image, just updated question with my css
Comment: @Thiago Custodio in my original code css is first, so why browser request image last i have no idea. But probably browser load that image only when first div gets created?
Comment: How long is the "Waiting" vs "Receiving" time on your image?
Comment: @Mike Robinson 2ms/17s http://i.stack.imgur.com/uISwD.jpg
Comment: Try to use this tool: http://cssspritegenerator.net
Comment: @bigb Your browser request 4 files each time. That's why you should put css first and the JS at the end of the page. http://developer.yahoo.com/performance/rules.html
Comment: @bigb I found other people with css sprite with Chrome too. Take a look and see if it helps https://github.com/CloudMade/Leaflet/issues/640
Comment: Load picture after CTRL+Refresh pressed, http://i.stack.imgur.com/Njby4.jpg quite strange. May be it is just image loading issue in my Chorome?
Comment: @SLaks sample is here: http://bit.ly/TrcCdp
Comment: Still fighting with that....if some one may take a look at my sample here http://bit.ly/TrcCdp to reproduce it in your Chrome browser
Comment: Any CSS background image is only ever requested if a node uses it and is not `display:none`.
Comment: So maybe the problem is not in the loading but in layout? Have you profiled your page?
Comment: @Torsten Walter Looks like the problem is knockout foreach loop, it is slow with lots of elements, so I will replace it with jquery template and see what's happens.
Answer: The problem is not the image. The image can be fixed by placing a preload at the top, before any of the stylesheet or script tags:
<meta name="viewport" content="width=device-width">

<link href="TestApp_files/jquery00.css" rel="stylesheet">
<link href="TestApp_files/jquery01.css" rel="stylesheet">

After this, the image loads in 170ms (locally). However, the page still mucks about for another 10-15 seconds afterwards trying to decide what to do.
The root issue is that the javascript is an absolute mess. Image/file/function names are cryptic. Things in the middle of the page depend on code at the end depends on code at the beginning depends on code at the end. Controller/view/model logic is all over the map. Global variables and multi-file coupling... hokay, </soapbox>, now onto treating the symptom.
Problem 1: binding knockout before the DOM loads
Put applyBindings into a domready callback:
jQuery(function($) {
   ko.applyBindings(viewModel);
});

Problem 2: foreach is slow
The knockout foreach binding is incredibly slow with large data sets. You can try jQuery templates and move the foreach inside the template, as described in this SO question. It seems to drop the time down to about 3 seconds.
I don't really understand why this is necessary as it seems to render fine with your current foreach, it simply hangs forever while knockout does some magic in the background that, as far as I can tell, takes place after foreach completes.
Side note: is it necessary to put flips into an observable array? I assume you intend to use that later as nothing in the current code needs it. If not, take it out and it will help performance (though it won't solve this issue).
Cheers, I hope this helps.
Answer: It's some sort of strange rendering bug between the foreach binding and Chrome. I tried just adding a character in your template before the div and that fixed the delay (but also messed up the layout).
A good way to fix this is to use something other than foreach. My repeat binding works well here and solves the delay problem.
Here is that section of your code using repeat:

Because repeat doesn't use an observable for $index, you'll also need to change your getTopValue and getLeftValue functions to take out the parentheses () after index.
Answer: You should also look into streamlining your code that is called by the foreach loop. I don't know how often you call the getLeftValue and getTopValue methods but they are pretty unoptimized.

Try limiting function calls that give you the same result, use local vars to cache since they are cheap
don't concatenate strings in large loops, this is way slower than using an array to join them.

I tried optimizing your two functions. You should see at least some improvement:
getLeftValue: function (index) {

    var position = 0,
        realIndex = index(),
        currentLine = div(realIndex, 25);

    if (currentLine > 0)
        return ["-", (realIndex - (currentLine * 25)) * 20, "px"].join("");
    else
        return ["-", realIndex, "px"].join("");
},

getTopValue: function (index) {

    return ["-",(div(index(), 25)) * 20,"px"].join("");
}

CSS Sprites performance


É possível trocar a função click para outro tipo de função?

Question: Segue o código:
var connection = $.hubConnection();
var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');
contosoChatHubProxy.on('addContosoChatMessageToPage', function(name, message) {
    console.log(name + ' ' + message);
});
connection.start().done(function() {
    // Wire up Send button to call NewContosoChatMessage on the server.
    $('#newContosoChatMessage').click(function () { // <----------AQUI
        contosoChatHubProxy.invoke('newContosoChatMessage', $('#displayname').val(), $('#message').val());
        $('#message').val('').focus();
                });
    });

Só não quero a função click para executar essa linha abaixo:
contosoChatHubProxy.invoke('newContosoChatMessage', $('#displayname').val(), $('#message').val());
Existe outra forma de executar a linha acima sem usar a função click ?
Documento SignalR: https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client
UPDATE:
$(function () {
    myFunction();
});

function myFunction() {
    var connection = $.hubConnection();
    var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');
    contosoChatHubProxy.on('addContosoChatMessageToPage', function (name, message) {
        console.log(name + ' ' + message);
    });
    connection.start().done(function () {
        $('#newContosoChatMessage').click(function () { // <----------AQUI
            contosoChatHubProxy.invoke('newContosoChatMessage', $('#displayname').val(), $('#message').val());
            $('#message').val('').focus();
        });
    });
}

Comment: Se não é no `click`, em que momento deseja? Existem várias formas
Comment: Cara qualquer coisa !!!, menos a função click. Pode ser uma função simples de `myFunction`. Já tentei de tudo, não funciona.
Answer: Podes alterar para outro evento sim, sem problemas acredito.
Exemplo :
$('#newContosoChatMessage').focusin(function () { //Foco no elemento
$('#newContosoChatMessage').blur(function () { //Saindo do foco do elemento

Answer: Poderia isolar em outra função:
function invoke(){
    contosoChatHubProxy.invoke('newContosoChatMessage', $('#displayname').val(), $('#message').val());
}

E invocar em done:
connection.start().done(function() {
   invoke();
});

No ready do jQuery (não testado):
$(document).ready(function(){
    function invoke(){
        contosoChatHubProxy.invoke('newContosoChatMessage', $('#displayname').val(), $('#message').val());
    }

    connection.start().done(function() {
       invoke();
    });
});

Comment: Valeu funcionou aqui
Comment: `ready` do jQuery? Se for nenhum problema @MatheusMiranda
Comment: Lucas digamos que o código está dentro de uma função `ready`. Será que é possivel chamar `invoke();` ?
Comment: Sim, atualizei post, favor olhar.
Comment: Atualizei a resposta @MatheusMiranda


how to design responsive image button & layout by using android studio?

Question: i am new to android development . I designed one parking app , but the layout is not responsive to all mobile devices.
I tried to make responsive image buttons by using 9patch png images & by taking different drawable folder(hdpi,mdpi,xhdpi) . But both are not working for large screen devices.
This is one sample xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    >
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/exit"
        android:layout_gravity="center_vertical"
        android:background="@android:color/transparent"
        android:src="@drawable/exit1"
        android:onClick="on_Bexit"
        android:layout_alignTop="@+id/home0"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/home0"
        android:layout_gravity="center_vertical"
        android:background="@android:color/transparent"
        android:src="@drawable/home1"
        android:onClick="on_Bhome0"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/car"
        android:layout_gravity="center_vertical"
        android:background="@android:color/transparent"
        android:src="@drawable/c4"
        android:onClick="on_Bcar"
        android:cropToPadding="true"
        android:nestedScrollingEnabled="true"
        android:layout_alignBottom="@+id/textView5"
        android:layout_alignLeft="@+id/bike"
        android:layout_alignStart="@+id/bike" />
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bike"
        android:layout_gravity="center_vertical"
        android:src="@drawable/b3"
        android:background="@android:color/transparent"
        android:onClick="on_Bbike"
        android:layout_above="@+id/exit"
        android:layout_centerHorizontal="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="ENTRY   "
        android:id="@+id/textView"
        android:textColor="#8dacbe"
        android:textStyle="bold"
        android:textSize="35dp"
        android:layout_above="@+id/car"
        android:layout_toLeftOf="@+id/textView6"
        android:layout_toStartOf="@+id/textView6" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bike_count"
        android:text="90"
        android:textColor="#140441"
        android:textSize="30dp"
        android:textStyle="bold|italic"
        android:layout_alignBottom="@+id/bike"
        android:layout_toLeftOf="@+id/exit"
        android:layout_toStartOf="@+id/exit"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/car_count"
        android:text="120"
        android:textStyle="bold|italic"
        android:textColor="#140441"
        android:textSize="30dp"
        android:layout_alignBottom="@+id/car"
        android:layout_alignRight="@+id/bike_count"
        android:layout_alignEnd="@+id/bike_count" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView5"
        android:visibility="invisible"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/T_areadis"
        android:hint="Parking area id and name"
        android:textColor="#8dacbe"
        android:text="kharghar"
        android:textSize="30dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="PAGE"
        android:id="@+id/textView6"
        android:textColor="#005384"
        android:textSize="40dp"
        android:textAlignment="center"
        android:fontFamily="@string/abc_action_bar_home_description"
        android:textStyle="bold"
        android:layout_alignTop="@+id/textView"
        android:layout_toRightOf="@+id/car_count"
        android:layout_toEndOf="@+id/car_count" />
</RelativeLayout>

Please kindly help me out.
Comment: _"But both are not working for large screen devices."_ - in what way are they not working?
Answer:
Large screen devices use xxhdpi.
How to has equal width

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <ImageButton
        android:id="@+id/exit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:layout_gravity="center_vertical"
        android:background="@android:color/transparent"
        android:onClick="on_Bexit"
        android:src="@drawable/icon_login" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ENTRY   "
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#8dacbe"
        android:textSize="35dp"
        android:textStyle="bold" />
</LinearLayout>

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <ImageButton
        android:id="@+id/home0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:layout_gravity="center_vertical"
        android:background="@android:color/transparent"
        android:onClick="on_Bhome0"
        android:src="@drawable/icon_login" />

    <TextView
        android:id="@+id/bike_count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="90"
        android:textColor="#140441"
        android:textSize="30dp"
        android:textStyle="bold|italic" />
</LinearLayout>

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <ImageButton
        android:id="@+id/car"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:layout_gravity="center_vertical"
        android:background="@android:color/transparent"
        android:onClick="on_Bcar"
        android:src="@drawable/icon_login" />

    <TextView
        android:id="@+id/car_count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="120"
        android:textColor="#140441"
        android:textSize="30dp"
        android:textStyle="bold|italic" />
</LinearLayout>

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical">

    <ImageButton
        android:id="@+id/bike"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:layout_gravity="center_vertical"
        android:background="@android:color/transparent"
        android:onClick="on_Bbike"
        android:src="@drawable/icon_login" />
    <TextView
        android:id="@+id/T_areadis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Parking area id and name"
        android:text="kharghar"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#8dacbe"
        android:textSize="30dp" />
</LinearLayout>


Show that $I_{(0,\theta)}(x_1) \dots I_{(0,\theta)}(x_n) = I_{(0,\theta)}(x_{(n)})$

Question: Show that $I_{(0,\theta)}(x_1) \dots I_{(0,\theta)}(x_n) = I_{(0,\theta)}(x_{(n)})$
where $x_{(n)}$ is the order statistic, and $X = (X_1,..., X_n)\sim U(0,\theta)$ iid.
I can show that it is equal to $I_{(0,\infty)}(x_{(1)}) I_{(-\infty,\theta)}(x_{(n)})$, but not really sure where to go from there.
Comment: $I_{(0,\infty)}(x_1)I_{(-\infty,\theta)}(x_{(n)})$ is the same as $I_{(0,\theta)}(x_{(n)})$ in this case.
Comment: I don't understand how to show that
Comment: Nothing to show really. Product of the two indicators is the indicator of the intersection of $(0,\infty)$ and $(-\infty,\theta)$.
Comment: But then which variable should be inside the indicator function? couldn't it equally be $x_{(1)}$?
Comment: The full string of inequality is $00$ and $x_{(1)}<x_{(n)}$, you have just $0<x_{(n)}<\theta$. You can keep the $x_{(1)}$ in the indicator also, makes no difference.
Answer: If $0\le x_i\le \theta$ for all $i$, and $ x_i \le x_{(n)}$, then $\cap_{i=1}^{n}\{0\le x_{i}\le \theta\} = \cap_{i=1}^{n}\{0\le x_{i}\le x_{(n)}\le \theta\}= \{0\le x_{(n)}\le \theta\}$
Comment: Can't the same argument be made for $x_{(1)}$?
Comment: Sure, as $0 \le x_{(1)} \le x_i \le x_{(n)} \le \theta$ for all $i$
Answer: You are completely right that $$I_{(0,\theta)}(x_1) \dots I_{(0,\theta)}(x_n) = I_{(0,\infty)}(x_{(1)})I_{(0,\theta)}(x_{(n)}).$$ Check initial equality $$I_{(0,\theta)}(x_1) \dots I_{(0,\theta)}(x_n) = I_{(0,\theta)}(x_{(n)})$$ at $x_{(1)}=-1$, $x_{(n)}<\theta$.  L.h.s. equals to $0$ and r.h.s. equals to $1$.
Note that this cases have zero probability: $\mathbb P(x_{(1)}\leq 0)=0$. So the initial equality can be considered as equality with probability $1$:
$$I_{(0,\theta)}(x_1) \dots I_{(0,\theta)}(x_n) = I_{(0,\theta)}(x_{(n)}) \text{ a.s.}$$
In statistics, it is usual to skip letters a.s. since we cannot expect to see some $X_i\leq 0$ in a sample from Uniform $(0,\theta)$ distribution.
Comment: Isn't it also true that $P(X_{(n)}>\theta) = 0$ ?
Comment: Sure. But note that this r.h.s. is also a function of $\theta$ and can be used to estimate $\theta$ given $X_1,\ldots,X_n$ as MLE. In this problem we must consider all possible values of $\theta$: $\theta\leq x_{(n)}$ as well as $\theta>x_{(n)}$. So, if you look at this product as the function of elementary event $\omega$ given $\theta$, it differs from last indicator or from $1$ only on event of zero probability. If you look at it as a function of $\theta$ given samples which are already positive, then $\omega$ is fixed. Then it is $I_{(0,\theta)}(x_{(n)}) = I_{(x_{(n)},\infty)}(\theta)$.


Replacing binary logistic regression with multinomial logistic regression?

Question: I am reviewing a study. It's authors wanted to investigate which of the care settings were more often used by women and which by men. Adjusting was done for age, comorbidity status. There were a total of 10 care settings. Thus, they did the following:
Binary logistic regression
sex ~ care_settings + covariates for adjusting

But IMHO they should have been used multiple logistic regression
care_settings ~ sex + covariates for adjusting

Could you have a comment on that. Is their approach correct?
Answer: The key question is what to predict / or what is the dependent variable.
If the study is about investigating the "correlation" between gender and care setting, or how to use care setting to predict gender, then the original formulation can be used.
If we want to use gender and other variable to "predict" care setting, then your formulation can be used.
In real world, to do a 10 class classification requires much more data than binary classification, I think this is another reason why the authors choose their formulation.
Comment: Thanks! Therefore, their approach is also OK, meaning that this gives quite the same results (e.g. males used setting type A more than females)?
Comment: @ethan282712, definitely not "same results", but interchangeable results. Think about model y~x vs x~y, suppose the real function is y=0.5x, we can also get x=2y. There are relationships between to models.


How to Read a word document in asp.net in mvc

Question:
can any one help me to find out the solution to show/Read the word
  documents in asp.net mvc any example or any suitable links. searched a lot on internet for suitable
  article but did not find any thing helpful. i have implemented the
  download functionality of the document. but can not able to read or
  preview the documents.
Answer: You could use the Office Web Viewer provided as a service from Microsoft .
What is the Office Web Viewer?
It's a service that creates Office Web Viewer links.  Office Web Viewer links open Word, PowerPoint or Excel files in the browser that would otherwise be downloaded. You can easily turn a download link into an Office Web Viewer link to use in your website or blog (e.g., recipes, photo slide show, a menu, or a budget template).
Office Web Viewer: View Office documents in a browser
Some benefits of the Office Web Viewer include:

You don't need to convert Office files for the web (e.g., PDF, HTML).
Anyone can view Office files from your website or blog, even if they
don't have Office.
It keeps eyes on your website or blog, because readers don't need to
download the file and they stay in the browser.
One link will work for computers, tablets, and mobile phones.
Answer: To manipulate .docx files (as well as .xlsx, .pptx, etc.) you would use Open XML SDK (also available as installer from Microsoft download centre).
The PowerTools for Open XML, which greatly simplifies working with Open XML SDK, contains functionality for
High-fidelity conversion of DOCX to HTML/CSS using HtmlConverter.cs
I've only used this SDK and Powertools to manipulate Word documents, so could not say much about conversion to HTML/CSS. But this could be one of your options for previewing Word documents, although it is a complicated way of solving your problem.
Answer: Try the MVC viewer in Gnostice XtremeDocumentStudio .NET.
ASP.NET MVC document viewer using ASPX and Razor engines.
DISCLAIMER: I work for this company.


Bootstrap dropdown menu not displaying on mouseover / click

Question: Here's the HTML for the dropdown part:

    Contact Us

testpage

testpage2

It just looks like this:

Nothing happens when I mouseover it, and clicking it takes me to the contact us page.
I should have all the necessary JS files:

Not sure where I'm going wrong.
Edit - getting this error in console:

Not sure what's causing that though, there is no HTML in there
Comment: Please check console for errors
Comment: are you loading `jquery` at the end of `body` tag or before end of `head` tag
Comment: check your visible and hidden class in html
Comment: Looks like your js isn't loading. What happens if you navigate to `yoursite.com/js/plugins/bootstrap.min.js`?
Comment: Shouldn't be a duplicate, I am loading jquery before bootstrap,min.js. DavidG, bootstrap.min.js works fine if I navigate to it.
Comment: Updated original post with error. I'm loading jquery before the end of the head tag.
Comment: Possible Duplicate : http://stackoverflow.com/questions/32766270/dropdown-menu-not-working-in-header/
Answer:

<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Contact Us </button>

HTML

CSS

JavaScript

Working fiddle
https://jsfiddle.net/DTcHh/
Answer: There were few errors in your code.

You are not giving id to your button.
Missing data-toggle="dropdown" from button
You are not using aria-labelledby attribute in ul.

Checkout this snippet.

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

    Contact Us

testpage

testpage2


iSCSI Discovery Issue

Question: I have an issue with iSCSI discovery. Just some background, I'm using Openstack Cinder and part of Cinder requires the use of iSCSI for networked drives. Cinder is unable to get the list of nodes anymore for some reason, and after tracing, it seems to be due to the inability of my Openstack controller to get the list of nodes via iscsiadm.
The command I'm referring to is
iscsiadm --mode discovery --op update --type sendtargets --portal <target_address>:3260
I'll get the following error message
iscsiadm: connecting to <target_address>:3260
iscsiadm: connected local port 58654 to <target_address>:3260
iscsiadm: connected to discovery address <target_address>
iscsiadm: discovery session to <target_address>:3260 starting iSCSI login
iscsiadm: sending login PDU with current stage 1, next stage 3, transit 0x80, isid 0x00023d000000 exp_statsn 0

iscsiadm: Connection to Discovery Address <target_address> failed
iscsiadm: Login I/O error, failed to receive a PDU

Interestingly enough, this command runs fine when running on the host directly. It cannot run from any other network-ed server, whether Linux or Windows.
Now if I create a new portal via the following command
tgtadm --lld iscsi --op new --mode portal --param portal=0.0.0.0:1234
I'm able to get the list of nodes just fine via the command
iscsiadm --mode discovery --op update --type sendtargets --portal <target_address>:1234
So it rules out a network issue, at least.
For the record, nothing else is running on port 3260 aside form iscsid and tgtd, both of which are related to iSCSI. When I create a portal on port 1234, I get similar outputs when I netstat -nltp | grep <port_number>
I'm running Ubuntu 20.04 LTS Server Edition. The firewall is disabled, iptables are empty aside from the rule to allow incoming packets at port 3260, SELinux is also disabled.
Comment: i may be blind, but what is acutally the business related question or issue exactly?
is the target ip a public ip? If not, why do you hide it?
Comment: It's a private IP, but anyway the question is,

I am unable to get the list of nodes via iSCSI discovery and am wondering if I'm missing a consideration. For some reason, discovery via port 3260 is not working, whereas discovery via other ports seem to work fine, once I create a new portal
Comment: tr,  a NC ip 3260 on the target not that it's been blocked
Comment: @dgdomi NC -L 3260 on the target -> Currently in use (tgtd active);

NC -L 3260 on the target  when tgtd is disabled-> Seems to be listening, no response;

Initiator sends a discovery message, the login message appears;

NC -L 1234 on the target when tgtd is diabled -> Same log in message as above appears ;

NC -zv  3260   - get message [tcp/iscsi-target] succeeded;
Comment: @dgdomi Thanks! I've solved my problem by rolling back an automatic kernel update.
Answer: The issue that I had was due to a kernel update that broke something at the lower level.
Wireshark dumps of the working connection via 1234, and 3260 showed that the 3-way TCP handshake mentioned here https://elatov.github.io/2012/06/iscsi-login-packet-capture/ was not established when communicating via 3260.
Downgrading the Linux Kernel to 5.15.0-41-generic from 5.15.0-46-generic resulted in the issue being solved.
For reference, I'm using a SuperMicro File Server Model SSG-6049P-E1CR24H

iSCSI Discovery Issue


Visualização de PDF com jQuery

Question: Preciso exibir um PDF como se fosse uma revista dentro de uma pagina HTML. A ideia é otimizar a visualização de um documento que está bem pesado(+100 paginas).
Atualmente só tenho um link que abre o arquivo em outra aba, e está demorando muito para carregar.
Encontrei um plugin chamado TurnJS. Mas nunca usei.
Vocês já utilizaram esse plugin? Conhece uma solução melhor?
Answer: Recomendo o PDFObject aproveite e leia também as instruções para o uso do mesmo.
O melhor que eu já usei, além de ser o mais leve pela minha opinião.

Visualização de PDF com jQuery


TypeScript - get type of generic class parameter

Question: I need to implement a type GetClassParameter<T> that would work like this:
class Foo<T> {

}

type foo = Foo<string>

type x = GetClassParameter<foo>; // should be string

I'm sorry if it's a duplicate, I couldn't find it. I only found a hardcoded solution (source):
type GetFooParameter<T extends Foo<any>> = T extends Foo<infer R> ? R : unknown;

I tried to do something like this:
class Foo<T> {
    public value: T;
    public value2: string;
    constructor (value: T) {
        this.value = value;
    }
}

type BaseT<T> = {
  value: T  // if removed, it wouldn't work
}
type GetClassParameter<T extends BaseT<any>> = T extends BaseT<infer R> ? R : unknown;

type x = GetClassParameter<foo> // string - almost works, requires shared property with a T

The above almost works but requires BaseT to have a value: T property.
Is there a way to do it without hardcoding anything, assuming the target class has only one generic parameter?
Update:
Another take, unsuccessful.
type ClassLike<T> = (new <T>(...args: any[]) => any);
type GetClassParameter<T extends ClassLike<any>> = T extends ClassLike<infer R> ? R : unknown;
type x = GetClassParameter<foo> // error, does not satisfy constraint

Update 2
It's not possible currently. Nevertheless, I tried a hack to define BaseT with value property and then removed it. It doesn't work. I'm adding it as a reference if someone had a similar idea to save you time. playground
Update 3
I'm adding a workaround I'm using to get the class parameter type for 2  classes that have nothing in common (it can be extended to cover more classes just by adding additional conditional).
playground
class Alpha<T> {
    private a: T;
}

class Beta<T> {
    private b: T;
}

type GetClassParameterForAlphaBeta<T extends Alpha<any> | Beta<any>> =
    T extends Alpha<infer R>
    ? R : T extends Beta<infer R>
    ? R : unknown;

type alpha = Alpha<string>
type beta = Beta<number>

type x = GetClassParameterForAlphaBeta<alpha> // string
type y = GetClassParameterForAlphaBeta<beta> // number

Comment: And the feature that takes the general form of `UtilType> => T` is not supported by TS. _Higher kinded type_ is the term, and TS doesn't have it. So forget perfect solution, best you can get is workarounds with limitations. Your two takes are actually good enough.
Comment: I cannot find the issue anymore, but typescript omits the information of generics if they are unused. It is a design limitation.
Comment: I don't have better answer for your problem, you've hit the limit of TS. FYI I wrote an answer about [higher kinded type in TS](https://stackoverflow.com/questions/55683711/replace-generic-interface-type-parameter) years ago. Only remotely related to your problem. If you wanna dig deeper you can take a look.
Comment: Your updated try can take `GetClassParameter`, if that also works for you
Comment: You are right about that. However, passing `GetClassParameter` doesn't seem to work.
Comment: Should be `typeof Foo` uppercase F. `typeof foo` is diff thing.
Comment: Well, I cannot use `typeof Foo` because I need to get information about the lowercase `foo`, which is `foo = Foo` I couldn't get it from `Foo`.

Surely if it's not supported, the workaround is good enough, I need this for 2 classes so I could probably use conditional types or something, but it would be nicer of course if if it was flexible.
Comment: I updated my question to add the workaround with conditionals to get the type for 2 or more different classes.
Answer: Cannot be done yet - purely as a type. There is an open issue that aims to allow passing higher-kind generic types through: https://github.com/microsoft/TypeScript/issues/1213
Its an issue that is a bane to many trying to type highly moddable js-libs
(like levelup).
Just to give you a much easier example of something that doesn't work:
interface Dummy<T> {};

declare function getParam(a: T): P;

let a = getParam(null as Dummy<string>);

here a is unknown
the only real work around is to move the generic parameter into the dummy interface as a fake property - but then everything passed to this will need that fake property defined too - or you're back to unknown
interface Dummy<T> {
  a?: T
};

declare function getParam(a: T): T["a"]

let a = getParam(null as Foo<string>);

a is now string but typescript still has no idea what P is
Comment: Not related but it is possible to do in Flow


How can the US have a positive population growth (0.5%) with a < 2 fertility rate?

Question: Google states that the US has a fertility rate of ~1.73 and a population growth rate of ~0.5%.
It seems like anything less than 2 for a fertility rate should result in population lessening.  Is my understanding of this correct?  If not, what factors am I missing here?
Comment: Could it be immigration?
Comment: ... or lengthening lifetimes.  Or changes in how the Census counts the population.  Or adoptions and *in vitro* conceptions ;-). Because Google doesn't appear to explain what it means by "population growth," it's hard to attach any definite meaning to that figure.
Answer: Fertility rate does not include immigration, which largely makes up for the relatively low fertility rate.
Back of the napkin calculations: the US has 330 million people. Assume half are women. That's 165 million women. With a fertility rate of 1.73, they would be expected to have roughly 285.5 million children.
The immigration rate to the United States as of right now is roughly half a million per year. But the average reproductive lifespan of a woman is roughly 30 years, so that's 15 million immigrants. We're up to 300 million when you combine a generation of births plus immigrants. That still isn't growth.
But life doesn't end when we stop reproducing. People live on past 45... And lifespan is increasing. That probably explains the rest of the growth. For example, the fertility rate is only 1.73, but in 2019, there were about 1 million more births than there were deaths despite the fertility rate being less than the amount needed to replenish the population. This is because lifespan wasn't constant for the last few generations, it has been increasing consistently for decades. Seems confusing, doesn't it?
This isn't a definitive answer, but I think it is enough to show that simply looking at fertility rate can be misleading when you're interested in explaining population growth at a given time.


Serilog console outputs doesn't show up during Integration Testing with WebApplicationFactory

Question: The log entry shows up fine in the test console when I call Log.Information("Test") from my integration test file. If I call the same static function from within the controller being tested with a WebApplicationFactory, nothing will show up in the test console.
Oddly enough, Console.WriteLine("Test") also doesn't show up in the test console when called from a controller created with a WebApplicationFactory
Is there a way to display in the test console log entries dispatched from controllers being tested using a WebApplicationFactory? Or simply a way to redirect console output from the created WebHost to the test output?
Answer: I found the answer here: https://stackoverflow.com/a/74574304/1057436
In ASP 6 you can set PreserveExecutionContext like this:
public BasicTests(WebApplicationFactory<Program> factory)
{
    _factory = factory;
    _factory.Server.PreserveExecutionContext = true;
}

Code from this example: https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-7.0#basic-tests-with-the-default-webapplicationfactory


DS Views Block Field page visibility settings

Question: I have a Views block Sectors. I have created a DS block field that renders this view and I have configured it to be available only for specific bundle|view_mode. It gets displayed on every bundle|view_mode page after that.
I wan't to configure this block to be visible only on a certain page(s) and not in all bundle|view_mode specified. Basically, I need a Show block on specific pages settings as in D7.
Comment: Have you tried configuring the block in `/admin/structure/block` and make so it visible on certain pages?
Comment: I wanted to but the block doesn't appear there.
Comment: @VladStratulat, did you figure this out?
Answer: Go to /admin/structure/block under the disabled region, click on Place block button and try searching for it on the search box, if you find it, place it and then Configure.
Comment: The DS field doesn't respect the block visibility settings. In D7 there was *Respect Block Visibility* setting to make it work but I can't find this option in D8. So I just replaced the field with normal block.


Start program via ssh in Jenkins and using it in Jenkins build

Question:
Hello people.
I'm using Jenkins as CI server and I need to run some performance test using Jmeter. I've setup the plugin and configured my workspace and everything works ok, but I have to do some steps manually and I want a bit more of "automation".
Currently i have some small programs in a remote server. These programs make some specific validations, for instance (just to explain): validates e-mail addresses, phone numbers, etc.
So, before I run the build in jenkins, I have to manually start the program (file.sh) I want:
I have to use putty (or any othe ssh client) to conect to the server and then run, for instance, the command
./email_validation.sh

And the Jmeter test runs in a correct way, and when the test is done I have to manually "shut down" the program I started. But what I want is trying to start the program I need in Jenkins configuration (not manually outside Jenkins, but in "execute shell" or "execute remote shell using ssh" build step).
I have tried to start it, but it get stuck, because when Jenkins build finds the command
./email_validation.sh

the build stops, it waits for the command to finish and then it will continue the other build steps, but obviously, I need this step not to finish until the test is executed.
Is there a way to achieve this? Thanks
Answer: Run your command as a background process by adding the & symbol at the end of the command and use the nohup command in case the parent process gets a hangup signal, e.g.
nohup /path/to/email_validation.sh &

If the script produces any output, it will go by default to the file nohup.out in the current directory when the script was launched.
You can kill the process at the end of the build by running:
pkill email_validation.sh

Comment: Thanks for your help, but when I execute the "pkill" command the process didn't stop. I had to kill it manually, searching and using the PID
Comment: Ok, I've found how to solve. I had to use "pkill -f" and the name of the process inside "file.sh" (the file.sh is a kind of shortcut, inside this file is a big command line. So instead of execute this big command each time, we just run the file.sh)


How can I solve $4x^2y''-12xy'+(4x^2+15)y=0$?

Question: I tried to solve this equation $4x^2y''-12xy'+(4x^2+15)y=0$ and I used this $y'=yz(x)$ ,then I got equation $z^2+z-\dfrac{3z}{x}+1+\dfrac{15}{4x}=0$ Can anyone help me? I am desperate.
Answer: I do not know why you do it in that way. But one common method could be like this:
The original ODE could be written as :
$y^{'} -\frac{4x^2+15}{12x}y=\frac{x}{3}$
Then you denote $p(x)=-\frac{4x^2+15}{12x}$, $q(x)=\frac{x}{3}$, then you can have
$y = e^{-\int p(x)dx}\{\int q(x)e^{\int p(x)dx}dx+C\}$
You can continue on this and get your result.


Migrating email server

Question: I'm migrating a small company's email from one simple setup to another.
The MX records remain with the original server.
Also, a CNAME points to the original server - I'm not sure why as I didn't set this up in the first place.
I have been able to use both server IP addresses on email clients to send emails.
I have been able to use the server IP addresses on email clients to receive email at the original server and NOT on the new server.  Not too surprising.
I'm wondering if there's a recommended way to test receiving on the new server before I change the MX records?
Or, is it recommended to just change the MX records (and the CNAME entry I suppose?) and then let the results propagate?
Comment: The MX records needs to specify an A record. Where does the CNAME record come into play?
Answer: You have a couple of options based on what kind of software you are able to configure.
If the server that you are sending the test messages from happens to be Exim, you could setup a manualroute that will skip DNS entirely, and send messages directly to your test server. Documentation and example here:
https://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_manualroute_router.html#SECID123
It is very possible that other email servers have a comparable feature to this, but Exim is what I know, so I can't comment on other mail servers.
Your other option is to set up a DNS resolver (BIND for example) with your fake MX records in place. Then configure your sending email server to use your custom DNS resolver to resolve the DNS records. On Linux, you'd be able to edit the <code>/etc/resolve.conf</code> to change the resolver used by your mail server in a lot of cases.
Comment: Well, I'm not much of an expert in how these things work.  I already am addressing the servers using their IP addresses.  So, I've rather assumed that it's the destination email address domain that is steering the traffic to the original server.
Comment: Ah yes, in that case you likely just need to edit the routing on the new email server so that it doesn't route the messages to the original server. For example on a cPanel server this would be done by moving the recipient domain from the /etc/remotedomains file to the /etc/localdomains file.

Migrating email server


fmm, lcprob(m): regress y x

Question: I am wondering if someone would help me to understand the the stata command posted here:
https://www.stata.com/stata-news/news32-4/spotlight-fmm/
the article explains that the command
fmm 2, lcprob(pchol): regress chol wine
"We hypothesize that an individual may inherit a "high cholesterol" gene and that we have two types of individuals in the population—those with the cholesterol gene and those without. However, we do not know who belongs to each group.
We use fmm to probabilistically classify the sample into groups. By adding the fmm prefix followed by 2, we indicate that we want to fit a model for two underlying subpopulations. We use the lcprob(pchol) option to include parents' cholesterol history as the predictor of the unobserved group, also called the latent class."
I am using probit: fmm 2, lcprob(m): probit y x   where m is the predictor of the unobserved group.
My equation is: ln(L)=ln{p_1* Φ(z)+ p_2*[1- Φ(z)]}
where, Φ(z) = cumulative distribution function on of: beta1 *x1 + beta2 * x2 + ..+ ai + ei    (ei ~ iid)    and
a_i  takes k different values corresponding type of physical condition.
Since types are unobserved, the statistical framework assumes that type k occurs with p_k probability, and assuming k=2 the model estimates the following likelihood function of the mixture distribution
ln(L)=ln{p_1* Φ(z)+ p_2*[1- Φ(z)]}
BUT WHEN WE DO fmm 2, lcprob(m): probit y x     HOW TO WRITE THIS lcprob(m) IN EQUATION?
Maybe, I am not understanding this clearly.
Answer: The likelihood can be written as
$$\mathcal{L}(\beta) = \sum_{j=1}^{2} \pi(m_i) \prod_{i=1}^{N} f_{ij}(y_{ij},x_{ij},\beta)$$
where $\pi$s are the "mixing" probabilities for each latent class.
Comment: Hello Dimitriy, thank you so much for your help. Just to clarify, the π(m_i): is "m_i" the predictor variable same as "pchol"  in this stata command: "fmm 2, lcprob(pchol): regress chol wine"?
Comment: Yes, I was using your probit command as an example.
Comment: Thank you, Dimitriy.
Comment: @Mahmood If this answered your original question, could you select this as the answer? If not, please let me know what remains unclear.
Comment: Yes, this does answer my original question, certainly. I don't know how to select, any button I have to click (I tried with vote). Just one quick question: this specific technique (with predictor in lcprob) - is there any technical name of this or just probit mixture?
Comment: It's a checkmark on the left below the counter. They are both probit mixtures, but with lcprob you are explicitly modeling the mixing probabilities as a function of m.

fmm, lcprob(m): regress y x


Linux server equivalent of Cisco Discovery Protocol (CDP)?

Question: I am wondering if there are any Linux tools out there which might aid in identification of hosts directly connected to each other (much like Cisco Discovery Protocol on switches)?
I have found http://sourceforge.net/projects/lcdpd/ which searching. But it appears to be a dead project and the patch is only for older kernels.
I am just trying to alleviate the tedious task of ethernet interface to ARP MAC address to hostname lookup. A bonus would be something that also announced its own neighbors so you could have a 2 hop view of the rest of network.
Comment: What's the use case here?
Comment: So you have a bunch of servers connected directly? Sound very painful.
Comment: To help remotely identify port to port mapping of Linux machines connected to each other without a switch.
Answer: Are you looking for LLDP?
Agent software is out there for Linux, and many network devices support it.
Comment: Yep, this looks like what I was after. Actually, the Intel LLDP agent doesn't provide much information at all. With some more searching about LLDP I discovered https://github.com/vincentbernat/lldpd which does a simple output of the LLDP neighbors, their interface, MAC, hostname, IP address, and more. This becomes very helpful information when there are no switches to provide a MAC table.
Comment: The LLDP information also led me to http://www.netdisco.org/ which appears to be exactly what I was looking for.


Como atribuir o retorno de um forEach a uma variável

Question: Olá! tenho a seguinte situação, recebo como retorno de um get a uma api um array de objetos, para obter os dados que preciso uso um forEach.
esse e o get:
 getData = async ( ) => {
    const response = await axios.get("https://restcountries.com/v3.1/all")
    const data = response.data
    return data
    }

Esse e o ForEach que estou usando:
     getData().then(data => {
        data.forEach(element => {
        name = [element.name.common];
        console.log(name); // aqui recebo todos os itens selecionados.
        });

        console.log(name); // aqui recebo [ 'Greenland' ], esse é o primeiro item do array.
       })

Quando acesso a variável fora do forEach tenho como retorno apenas o primeiro item. Como consigo atribuir todo o retorno a uma variável acessível fora do forEach?
Answer: Se quer guardar múltiplos valores sob uma mesma referência pode usar um Array.
Array é um tipo de dado que representa uma coleção de elementos associados a um índice numérico inteiro. É semelhante a listas e pode ser alterado a qualquer momento.
O método Array.prototype.push() adiciona um ou mais elementos ao final de um array.
Um reparo imediato para o seu código seria declarar um Array antes do laço de iteração e durante a iteração ir preenchendo o array declarado:

const getData = async() => {
  return (await axios.get("https://restcountries.com/v3.1/all")).data;
};

getData().then(data => {
  const names = [];             //Declara um Array onde serão armazenados os nomes dos países.
  data.forEach(e => {
    names.push(e.name.common);  //Adiciona ao final do array names o nome do país.
  });
  console.log(names);
});

No seu caso específico essa não é a melhor das abordagens pois a resposta de https://restcountries.com/v3.1/all já é um Array possibilitando a aplicação direto de uma função de transformação para cada elemento da resposta com o método Array.prototype.map().
O método Array.prototype.map() invoca uma função callback passada por argumento a cada elemento do Array e devolve um novo Array como resultado.
No seu exemplo apenas passe para Array.prototype.map() uma função retornando o nome de cada país:

const getData = async() => {
  return (await axios.get("https://restcountries.com/v3.1/all")).data;
};

getData().then(data => {
  const names = data.map(e => e.name.common);  //Para cada elemento da resposta retorne a propriedade name.common.
  console.log(names);
});


Explicar para um iniciante a query "if (! achou)" no código

Question: Tenho um exercício que pesquisa um número em um vetor pré-determinado; e responde "foi encontrado e qual posição do vetor" ou responde que "o número não está no vetor". Queria a explicação de porque usar o boolean achou = false e da query if (!achou). Eu sei que o programa tem que exibir 2 resultados se achou ou não achou o número, mas não entendi direito o que o uso do boolean e da negação dele no if estão fazendo.
public static void main(String[] args) {

    int vetor[] = { 1, 3, 5, 7, 9};  // Cria o vetor com valores pré-definidos
    int numero;
    boolean achou = false;  // Variável para armazenar o resultado da procura

    System.out.println ("Qual número deseja procurar? ");
    numero = Integer.parseInt(JOptionPane.showInputDialog(null,"Qual número deseja procurar?"));

    for (int posicao = 0; posicao < 5; posicao++)
    {
        if (vetor[posicao] == numero)
        {
            System.out.println ("Encontrado na posição: "+ posicao+ "\n");
            achou = true;
        }
    }

    if (! achou)
    {
        System.out.println ("O número não está no vetor\n");
    }
}

}
Comment: `!achou` é a mesma coisa de `achou == false`, só é um jeito mais chique de escrever
Comment: Esse `achou` existe porque no caso de não ter achado só dá pra saber após ter percorrido todo o vetor. Concordo que é desnecessário, um `break` eliminaria isso e resolveria uma ineficiência (se já achou pra que continuar percorrendo?). Na verdade (sendo um pouco chato porque volta e meia cometo esse pecado) o design não está bom, deveria haver uma função que só percorre e retorna se achou ou não, e outra que usa isso para dar essa informação ao usuário. O `!` é o operador de negação lógica que vem da álgebra de Boole (conceito ótimo para um iniciante em programação estudar).
Comment: Falei `break`? Quis dizer `return true`. :P A lógica deu uma falhada agora rs
Answer: Primeiro, isso não é uma query.
Segundo, esse código é ineficiente, se achou ele deveria parar de procurar, e feito de forma eficiente e organizada, portanto a busca feita em uma função separada, essa variável nem seria necessária.
Esse tipo de variável chama-se flag, ou seja, ela só existe como uma bandeira para indicar um estado, e quase sempre tem um jeito melhor de fazer.
Então o código apenas controla se conseguiu achar o que estava procurando ou não. Ele começa considerando que não achou, então achou é falso. Quando ele achar (entrou no if) então muda o estado da variável (o ideal seria parar a busca ali mesmo), e mudando o estado a variável indica que ele achou o que estava procurando.
No fim ele verifica se achou ou não e decide se deve apresentar a mensagem dizendo que não achou. Obviamente ele só deve entra nesse if se o achou é falso, mas para entrar em um if o resultado deve ser verdadeiro, então como fazer um falso virar verdadeiro? Aplicando o operador booleano de NÃO (NOT), que é a exclamação, ou seja esse operador inverte o valor da variável booleana. Se não achou então ele entra ali.


Fetch data from size table by getting id from mapping table in django?

Question: I am creating a printing ordering service website in django and i am stuck on order page.
I have three tables named "product" ,"size" and "sizeProductMap" table.
model.py
This is my product table.
class Product(models.Model):
    prod_ID = models.AutoField("Product ID", primary_key=True)
    prod_Name = models.CharField("Product Name", max_length=30, null=False)
    prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
    prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
    prod_img = models.ImageField("Product Image",upload_to='productImage/', null=True)

This is the size table.
class Size(models.Model):
    size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
    prod_size = models.CharField("Product Size", max_length=20, null=False)

This is the sizeProductMapping table.
class SizeProductMapping(models.Model):
    size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True)
    size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID")
    prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")

The sizeProductMap tables stores primary key of product table and size table as foreign key, now i want to get those sizes which has mapping with a particular product.
I want to get all those sizes from size table releted to a particular product here a single product can have different sizes.
Comment: Can you paste your model.py code showing how the relationships were setup?
Comment: i have added the models now can you help me ? I am a newbie at project development so needed help i don't know how to fetch the all the sizes releted to a product . Suggest he cde i should try in views.py  .
Answer: In above code, there are many sizes are available for a single products so when i visit the product page i want all the sizes listed their so i can choose one of them, In example think i have a product "Envelop" it may have different sizes so i need all those options.
so i tried something lit me share with you:
views.py
    def product(request, id):
        ''' using id I am getting the product here'''

        products = Product.objects.get(prod_ID=id)
        print(products)

        '''According to foreign key relationship here I am getting all the mappings available to that product'''

        sizesmap = SizeProductMapping.objects.filter(prod_id=id)
        for data in sizesmap:
            ''' Here storing all the sizes id in "sizes" variable'''
            sizes = data.size_id

        '''Here I am getting all the sizes related to that product and printing it now I can pass it in context and use it in the page'''
            print(sizes.prod_size)
        return HttpResponse(sizesmap)

Comment: Yes, this thing is working for me correctly. I thank you for giving your precious reply to me.
Answer: I'm going to assume you can modify with your models and database.  If you are using an existing database with data you don't want to lose, then there are things you can do.  But I'm not listing them here.
The Django way of doing what you want is to use one of the built-in relationship constructs Django provides. There are two that could fit your needs. Either a One-To-Many or a Many-To-Many.  I'll provide examples of both.
Depending on the possible values for size, you may just want a One-to-Many:
class Product(models.Model):
    prod_ID = models.AutoField("Product ID", primary_key=True)
    prod_Name = models.CharField("Product Name", max_length=30, null=False)
    prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
    prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
    prod_img = models.ImageField("Product Image",upload_to='productImage/', null=True)

class Size(models.Model):
    size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
    prod_size = models.CharField("Product Size", max_length=20, null=False)
    product = models.ForeignKey(Product)

This will create a One-To-Many relationship with Product and size.  Then to get all of the sizes for a given product:
p = Product.object.get(prod_id=<whatever>)
for size in p.size_set.all():
   print('{} - {}'.format(p.productName, size.prod_size))

Here is an interactive shell example of getting multiple sizes for a single product.
>>> p = Product.objects.create(prod_Name='test', prod_Desc='test2')
>>> p.size_set.create(prod_size='Medium')
<Size: Size object (1)>
>>> p.size_set.create(prod_size='Large')
<Size: Size object (2)>
>>> for size in p.size_set.all():
...    print(size.prod_size)
...
Medium
Large

Your example uses a ManyToMany relationship, which Django can create and manage that middle table for you as well.
class Product(models.Model):
    prod_ID = models.AutoField("Product ID", primary_key=True)
    prod_Name = models.CharField("Product Name", max_length=30, null=False)
    prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
    prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
    prod_img = models.ImageField("Product Image",upload_to='productImage/', null=True)
    sizes = models.ManyToManyField("Size2")

class Size(models.Model):
    size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
    prod_size = models.CharField("Product Size", max_length=20, null=False)

Then to query it
for sizes in product.sizes.all():
   print(product.prod_Name, sizes.prod_size)

Some interactive shell done with the ManyToMany example:
>>> p = Product.objects.create(prod_Name='foo', prod_Desc='bar')
>>> p.sizes.create(prod_size='medium')
<Size: Size object (1)>
>>> p.sizes.create(prod_size='small')
<Size: Size object (2)>
>>> for s in p.sizes.all():
...    print(s)
...
Size object (1)
Size object (2)
>>> for s in p.sizes.all():
...    print(s.prod_size)
...
medium
small
>>>

Comment: Thanks, for your reply,  but it didn't worked for me cause there are different sizes available for a single products so whenever i click on a product i want all the sizes which are related to that product so the mapping table is necessary .
Comment: I'm sorry it didn't work.  But both examples with the ManyToMany and the OneToMany  provide you with different sizes available for a single product from a database.  I'll edit with some code to populate the database.


Usar ou não usar barra no final de uma URL?

Question: Sempre que eu vou criar um novo site e pensar no .htaccess me bate aquela dúvida: forçar ou não forçar o uso de barra no final da URL.
Por exemplo:
http://meusite.com seria 301-redirecionado para http://meusite.com/.
Fazendo esse  redirecionamento, o tempo de  carregamento pode demorar um pouco mais, pouco eu sei, mas cada bit conta num site de grandes proporções.
Não adicionando a barra final, porém, pode ocasionar conteúdo duplicado nas listagens do Google, e prejudicar o SEO do site.
Então,  definitivamente, deve-se ou não usar a barra no final de uma URL? E quais as principais razões?
Answer: A ideia de que fazer um redirect 301 causa perda de pagerank é um mito, e você não tem com o que se preocupar. Qualquer resposta além disso vai ser provavelmente uma questão de opinião pessoal. Desde que as suas urls sirvam o mesmo conteúdo, tanto faz ter ou não a barra no final.
Comment: +1 pelo tanto faz.
Answer: Usando o rel="canonical", fica a seu critério. Exemplo:
Insiro ele no head da página, com o nome da página original no "href":
<link rel="canonical" href="http://www.exemplo.com.br" />

Aí o google vai ler, e se o conteúdo for igual, ele vai jogar todo o ranking na url que está no href, então nestas páginas abaixo eu tenho o rel="canonical" direcionado ao http://www.exemplo.com.br:

http://exemplo.com.br
http://www.exemplo.com.br
http://www.exemplo.com.br/
http://www.exemplo.com.br/index.html
Comment: Interessante! Acho que isso é bom ser utilizado de uma forma ou outra, mesmo com ou sem a barra no final.
Answer: Tratando-se da URL principal do domínio, acho desnecessário colocar a barra no final, uma vez que alguns navegadores como o Chrome já removem a barra automaticamente da barra de endereços:
Veja o comportamento ao digitar no barra de endereços do Chrome:

http://localhost/

é automaticamente simplificado para

localhost

Porém existe uma ressalva quanto ao sistema que estiver rodando do lado do servidor, que pode interpretar de maneiras diferente a URL solicitada.
Por exemplo um sistema pode estar usando a URL e separando as barras para algum uso interno.
Exemplo em PHP:
<?php print_r(explode('/', $_SERVER['PATH_INFO'])) ?>

http://localhost/index.php/modulo/

Imprimirá um primeiro ítem 'modulo' e um segundo ítem vazio

http://localhost/index.php/modulo

Imprimirá somente um primeiro ítem 'modulo'.
Ou seja, por conta de SEO não acho necessário, a nível sistêmico depende de cada caso.


"Void" type not allowed here (Java)

Question: I have 2 class the EmpresaTest(Main) and the Empresa. When I save the return statement of a metod, is returned a error: "Void type not allowed here". I noticed in some foruns that could be 'cause the metod is "void" type, but, in this case, is not void, it is boolean.
Código/CODE: Código - Error
Comment: Welcome, I know it's a pain and I'm truly very sorry, but this is a English based forum
Comment: You are looking for http://pt.stackoverflow.com/
Comment: Check out pt.stackoverflow.com too
Comment: @Blorgbeard eddited post
Comment: Can you post only the relevant code? (The part with the error)
Comment: @MarcoAcierno the error is in just line 25            t = Booelan.parseBoolean(e1.adicionaEmpregado(f1));
        System.out.println("T: " + t);
Comment: You mispelled Boolean: it should be

t = Boolean.parseBoolean(e1.adicionaEmpregado(f1));
Comment: @nem sry! But i want to save the return result on the variable T. The method  boolean contemFuncionario(Funcionario f) returns me the valor of func. But Why i can't save this valor on T?
Comment: Look at @MadProgrammer's answer
Comment: @JacquelineCosta Welcome to Stack Overflow! It's good to see that your problem has been solved, but the way to show that is to either click the checkmark next to the answer that helped you, or to "answer your own question" and click the checkmark next to your answer if you figured it out on your own.
Answer: adicionaEmpregado is declared as void, meaning it does not returning anything...
public void adicionaEmpregado(Funcionario f) {

This means that it can't be used in this situation...
t = Booelan.parseBoolean(e1.adicionaEmpregado(f1));

As it makes no sense, the method returns nothing...
Either, you will need to change the method to return a String or provide another method which can return the result of the current state accordingly...
Comment: You're sure! I changed the method ;x the correct is        t = e1.contemFuncionario(f1);
Answer: Solved!
The problem was I was declaring a method that not returns nothing.
    t = Booelan.parseBoolean(e1.adicionaEmpregado(f1));
    System.out.println("T: " + t);

Changed to
    t = e1.contemFuncionario(f1);
    System.out.println("T: " + t);

"Void" type not allowed here (Java)


Como usar subpasta como pasta principal sem alterar URL (site em joomla)

Question: Tenho um site que estou refazendo.
O antigo foi feito em wordpress (na raiz do site) e o novo em joomla (na pasta "novo")
Quero que ao acessar o dominio.com.br seja redirecionado para o dominio.com.br/novo, mas que o usuario veja dominio.com.br
Usei esse codigo no htaccess que funciona na pag inicial, mas quando entra no site novo, todos os links aparecem com o /novo, por exemplo, fica dominio.com.br/novo/contato
RewriteEngine On
rewritecond %{http_host} ^(www.)?paratodosacessibilidade.com.br$
rewritecond %{request_uri} !^/novo/
rewriterule ^(.*)$ /novo/$1
rewritecond %{http_host} ^(www.)?paratodosacessibilidade.com.br.com$
rewriterule ^(/)?$ novo/index.php [l]

Answer: Resolvido.
Na Raiz criar o htacess com:
# Redirecionamento .htaccess do domínio principal para um subdiretório
# Não modifique a linha abaixo
RewriteEngine on
# Mude exemplo.com.br para o seu domínio.
RewriteCond %{HTTP_HOST} ^(www.)?exemplo.com.br$
# Mude 'subdiretorio' para aquele onde está instalado o Joomla
RewriteCond %{REQUEST_URI} !^/novo/
# Não modifique as linhas abaixo
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Mude 'subdiretorio' para aquele onde está instalado o Joomla
RewriteRule ^(.*)$ /novo/$1
# Mude exemplo.com.br para o seu domínio, de novo.
# Mude 'subdiretorio' mais uma vez
# seguido por / e o arquivo principal do seu site: index.php
RewriteCond %{HTTP_HOST} ^(www.)?exemplo.com.br$
RewriteRule ^(/)?$ novo/index.php [L]

E no configuration.php da instalação do joomla alterar as variáveis abaixo para:
var $live_site = 'http://www.exemplo.com.br';
var $log_path = '/home/username/public_html/logs';
var $tmp_path = '/home/username/public_html/tmp';
var $ftp_root = 'public_html'


Compile errors after adding V8 to my project (C2143, C2059, ..)

Question: i've recently added Google's V8 to a MSVC2005 project which is also using Qt and i haven't been able to compile it since.
The defines are giving me a lot of problems, for example
in V8's token.h there is
#define T(name, string, precedence) name,
enum Value {
TOKEN_LIST(T, T)
NUM_TOKENS
};

The line TOKEN_LIST(T, T) yields an error C2143 ('}' missing before '{'), also error C2059 (syntax error '{'), also C2334 (token before '{'; visible function text is skipped). This repeats itself a couple of times.
I have searched through SO and through Microsoft's database and tested various things, for example using /clr, which broke Qt. I also used #undef before including the "v8.h" file for possibly existing definitions to be removed.
Can anyone help with this? Is there a standard procedure to fix errors like this?
Thanks.
Answer: You can find the conflicting macro definitions by searching for differences between the preprocessed code generated for token.h with and without the #include <windows.h>.
For example, for "token.h", the errors occur at the definition of the enum Value so you have to look at the preprocessed definition of that enum in both cases. So with
    #include <windows.h>
    #include <token.h>

you get:
enum Value {
    ...
    INSTANCEOF, , NOT, BIT_NOT, (0x00010000L), TYPEOF, void, BREAK,
    ...
    SWITCH, void, THROW,
    ...
    FUTURE_STRICT_RESERVED_WORD, const, EXPORT,
    ...
};

instead of:
enum Value {
    ...
    INSTANCEOF, IN, NOT, BIT_NOT, DELETE, TYPEOF, VOID, BREAK,
    ...
    SWITCH, THIS, THROW,
    ...
    FUTURE_STRICT_RESERVED_WORD, CONST, EXPORT,
    ...
};

with only #include <token.h>.
Comment: How can i explicitly remove the windows.h include? I did not add it and it's not in the token.h. Sorry for my lack of knowledge and thanks.
Comment: @Traveller: You could for example create a new .cpp file, with only 2 lines `#include ` and `#include `, and run that file through the preprocessor.
Comment: Thank you. Unfortunately the files match.
Comment: They didn't when I tried... By comparing the `Value` enum in both cases, I found 5 macros that were replaced by something else: `IN`, `DELETE`, `VOID`, `THIS`, `CONST`. Maybe you have to disable precompiled headers for the file.
Comment: So i cleaned the project, disabled precompiled headers and used windows.h + token.h one time and only token.h the other, but the generated .i-files match completely. Hmm
Comment: @Traveller I retested starting with an empty Win32 project in Visual C++ 2010 (I was using "gcc -E" + wine's windows.h on linux before) and it seems to work, so I'm not sure what you did differently...