How can I make sure my mix is not "bricked" before sending it to be professionally mastered?

Question: In the instructions provided to me by the service I'm using to have my album mastered, the engineers include this advice:

Include any desired processing, such as compression and equalization, but be sure to avoid using any peak limiting, 'normalizing', clipping, or any tools used for approximated mastering, such as Finalizer.
The maximum level of your non-limited track should peak around -3dBfs. (If your track is already "bricked", it limits our options.)

I do use compressors on my master output track, and I have turned on the limiter function on those compressors for most of my tracks.  I'm assuming I must turn "limiter" to off.  Is there any sense in me having the compressor running for all the tracks combined at all?  Is this something where the mastering engineers would be better off working with a "clean slate?"
And in particular, how can I be sure my track peaks around -3dBfs and is not "bricked?"
Should I expect my tracks to sound quieter when I remix them and send the files to be mastered, and expect them to be returned sounding louder than when I sent the files?
Comment: @Dekkadeci I had never heard the term before, my understanding based on research I did prior to posting this question indicates that it refers to a mix where there is so much normalization that the audio file has little in the way of dynamics and hence the audio file looks like a rectangle, or "brick."
Comment: What is "bricked"?
Comment: @RaceYouAnytime: It certainly fits with 'looks like a brick', but the origin is from _brick-wall mastering_, so maybe 'looks like a brick-wall' or 'hits you like a wall of bricks'?
Comment: @AkselA interesting.  As anyone who views my profile might note, I enjoy the study of etymology, so I appreciate the clarification! :)
Comment: In this context, it means that the compression has reached saturation, or a brick wall. As the instructions say, the loudest part should be about -3 db.

In the context of mobile phones, 'bricked' means that the phone has been locked against further programming and so physically resembles a brick. You can't phone with it or take pictures or anything, so it's an object which occupies a certain amount of space (once mobile phones were larger than they are now).
Answer: The sentence preceding the use of that term explains exactly what you should do. Give them at least 3dBfs of headroom to work with. As for how to do that, I don't know what DAW you are using but it should keep track of your peaks—or the highest dBfs level that it hit—and remember them until another peak is louder. Look for a number above or around the meter for the master bus. Play through the entire song and make sure that number never goes higher than -3 (the clipping point is 0dBfs and everything below that is negative).
In other words "bricked" means that your peaks are hitting 0dBfs or as loud as they can be without clipping. If that's the case then the mastering engineer has no headroom to work with.

Is there any sense in me having the compressor running for all the
  tracks combined at all?

Sure, a common reason for mix bus compression is to give the mix a bit of "glue" or more of sense that the tracks are sitting well together. Or maybe you want to compress an entire section of a song at the mix level differently than another section. A couple of tips though:

Make sure you aren't trying to fix problems you're hearing on individual tracks on the mix bus. Put a compressor on the problem track itself instead.
Go easy on the ratio and threshold. You usually don't need much compression on the mix bus.
Put the compressor on the mix bus very early in the process and "mix into into it". If you put it on at the end, you're changing and possibly undoing some of the mixing work you just did. Whereas if you put it on early, you'll react to how the compressor is reacting in your mix decisions.
Don't abuse mix bus compression solely to make your mix louder. The mastering engineer can and will do that but they'll do it much better than you. Instead try to only use mix bus compression to control dynamics or add glue.

Is this something where the mastering engineers would be better off
  working with a "clean slate?"

A mastering engineer can and would fix any "glue" issues if it was particularly a problem. But it's fairly common to use a little bit of mix bus compression at the mixing stage. So don't be afraid of to do it, just take it easy and/or have a good reason.
Comment: I would say crest factor is more important and you should give **at least** 20 dB of crest factor!!
Comment: This is a great explanation, thank you.  I should have mentioned that I'm using Logic Pro X, but I think your answer explains exactly what I was wondering about.
Answer: I think the existing answer is good and doesn't go far enough.
First, I would suggest you put zero plugins on your master output track or stereo bus or whatever you want to call it. For two reasons:

It will help you make a better mix, since you'll have to make things work without processing on the stereo bus.
It will let your mastering engineer do what they do best.

Second, when you're looking at your stereo bus levels, one important thing to pay attention to is crest factor. Crest factor is the difference in dB between the average (usually RMS) and peak levels. A recording is "bricked" when it has less than say 6dB for a crest factor, although many recordings you hear have between 3 and 6 dB for a crest factor. The worst examples have close to 0 dB. Feature films are usually delivered with a crest factor of about 20 dB, and that's after they've been mastered. Many of the best sounding music recordings will have a crest factor of about 12 dB, but remember that's what your mastering engineer is going to deliver back to you.
I strongly suggest not spending any time reducing the crest factor on your stereo bus to less than 20 dB. That means since your peaks are supposed to be no higher than -3 dBFS, your RMS levels would ideally be no higher than -23 dBFS. Check your DAW's manual to find out how to configure your meters to show RMS levels. Most can show RMS and peak at the same time.
Critical note about delivering to streaming services
Most of the major streaming services, including YouTube, iTunes, and Spotify have reduced output levels and are recommended crest factors of at least 14 dB when you deliver your master to them. If you or your mastering engineer reduce your crest factor below 14 dB, it will actually sound quieter when streamed, not louder. You should ask your mastering engineer about that if you want to deliver to streaming services and of course your can't create crest factor, only reduce it, so you definitely should send a crest factor of at the very least 14 dB to be mastered.
See: http://productionadvice.co.uk/spotify-reduced-loudness/
Also, one could argue this column by mastering engineer Bob Katz was the first shot fired in ending the loudness wars, and his K-system that he proposes here is now widely used:
http://www.aes.org/technical/documentDownloads.cfm?docID=65
Comment: This is excellent advice, thank you. I will take your advice of using zero plugins on the master output tracks.  I was not aware of the concept of crest factor before either.
Answer: They gave you instructions.  Follow them.  'Bricked' refers to 'brick wall compression', otherwise known as 'hard limiting'.  The waveform amplitude has its peaks flattened, as if they've hit a brick wall.
Yes, most people think 'mastering' involves increasing the perceived loudness. Some think that's ALL it means!   So mastering services  do that.
Answer: When you send stuff for mastering, the only processing you should do yourself is what involves the "signature sound" of a piece.  Usually that is stuff that you would only do to one track in particular, processing that sort-of is a part of a single instrument or voice.  Stuff you'd usually also add when using a live PA.
Making for a compact sound and distribution in general is the job of the mastering engineers.  If you have particular wishes or suggestions, write them down rather than trying to anticipate them in your tracks.


Prove by the divergence theorem that $\int_{\partial \Omega} u\frac{\partial u}{\partial n}dS \ge 0$. For what harmonic function does equality hold?

Question: Let $\Omega\subset R^n$ be a domain with a smooth boundary. Let $u\in C^2(\bar{\Omega})$ be harmonic on $\Omega$.
Prove using the divergence theorem that $\int_{\partial \Omega} u\frac{\partial u}{\partial n}dS \ge 0$
where we recall $\frac{\partial u}{\partial n} = N · \nabla u$ is the outward normal derivative of u and N is the unit outward normal vector along the boundary ∂Ω.
For what harmonic function $u$ does the equality hold?
Well the diveregence theorem states that $\int_\Omega \nabla ·F dV = \int_{\partial \Omega} F·n dS$. If we let $F=u$ in the theorem, then $\int_{\partial \Omega} u\frac{\partial u}{\partial n}dS=\int_{\partial \Omega} F(N·\nabla F)dS$. I am not sure where to go from here.
Answer: Since $\Delta u = 0$ on $\Omega$, therefore by Green's identity, we have
$$
\int_{\partial\Omega}u\dfrac{\partial u}{\partial\mathbf{n}}dS
= \int_{\Omega} u\Delta udx
+ \int_{\Omega} |\nabla u|^2dx
= \int_{\Omega} |\nabla u|^2dx \ge 0
$$
The equality holds if and only if $|\nabla u| = 0$, hence $u$ is a constant function.
NOTE: You can use Divergence Theorem to prove Green's identity
$$
\int_{\Omega}v\Delta udx
= \int_{\partial\Omega} v\dfrac{\partial u}{\partial\mathbf{n}}dS
- \int_{\Omega}\nabla u\cdot\nabla vdx
$$


Multiple conditions in IF formula to add end character

Question: Each cell in column F contains a word. For values in column G, I am looking to add an 'm' to the end of each word that ends with a vowel and leave it unchanged if it ends in a consonant. In the example below, F2 holds the word I want to add to.
Any help would be greatly appreciated!
So far I have had success with doing so for one letter at a time using:
=IF(RIGHT(TRIM(F2),1)="a",F2&"m",F2&"")
But I can't seem to get it to work when adding conditions for all required letters ("a","e","i","o","u") at the same time.
Answer: You can use REGEXREPLACE:
<code>=REGEXREPLACE(TRIM(F2),"(?i)([aeiou]$)","$1m")
</code>
Or with IF:
<code>=F2&IF(SUMPRODUCT(RIGHT(TRIM(F2))={"a";"e";"i";"o";"u"}),"m",)
</code>
Comment: The first works perfectly. Thank you!


como gravar no monolog o resultado do var_dump($_FILES);

Question: Estou precisando salvar no monolog os registro do var_dump($file) para identificar um erro.
Não sei como proceder. Meu monolog em app\config
monolog:
    handlers:
        main:
            type: 'rotating_file'
            path: "%kernel.logs_dir%/producao.log"
            level: debug
            channels: [!event]
        console:
            type:   console
            channels: [!event, !doctrine]

Comment: Se vc quer gravar a saida do `var_dump()`, use a função `var_export()` ex: `$resultado = var_export($var, true);`
Comment: E tem como colocar isso para funcionar no monolog?
Answer: Caso você esteja dentro de um controller, basta pegar o serviço logger e usá-lo para gravar registro no arquivo de logs:
$logger = $this->get('logger');
$logger->info(var_dump($var, true));

Se você estiver tentando gravar um log dentro de um serviço, você precisa injetar o logger dentro dele e depois usá-lo da mesma forma como se fosse em um controller. Segue um exemplo de implementação.
Arquivo services.yml:
services:
    app.services.my_service:
        arguments: [ "@logger" ]
        class: AppBundle\Services\MyService

Classe AppBundle\Services\MyService:
<?php

namespace AppBundle\Services;

use Psr\Log\LoggerInterface;

class MyService
{
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
}


Array Duvida JS

Question:
Estou com dúvidas e apanhando muito para resolver esse exercício alguém poderia me dar um Help?
Comment: Possível duplicata de [Como faço a multiplicação de um array dentro de uma função em JS?](https://pt.stackoverflow.com/questions/363601/como-fa%c3%a7o-a-multiplica%c3%a7%c3%a3o-de-um-array-dentro-de-uma-fun%c3%a7%c3%a3o-em-js)
Comment: `[1, 4, 7].reduce((acc, i) => acc * i)`
Answer: Na próxima vez posta sua tentativa que fica mais fácil te mostrar onde você está errando ao invés de somente darmos a resposta!

function produto(array){
       //inicia resultado com o valor 1
       let resultado = 1;
       //para cada elemento do array
       array.forEach(function(elem){
           //multiplica o resultado * elemento e atribui a variavel resultado
           resultado *= elem;
       });
       //retorna o resultado
       return resultado;
    }

    //chama a funçao
    console.log(produto([1, 4, 7]));
Answer: Você pode utilizar o for e fazer desta forma:

function produto(y){
       var res = 1;
       for(var x = 0; x < y.length; x++) res *= y[x];
       return res;
    }

    console.log(produto([1, 4, 7]));

Espero ter ajudado.
Comment: Obrigado, deu certo

Array Duvida JS


Google chart not displayed through ajax call

Question: I am trying to use Gooogle Chart Tools for showing some statistics. Below is the example code I'm using:
$settings['chart']['chartOne'] = array(
    'header' => array('Apple', 'Banana', 'Mango'),
    'rows' => array(array(12, 6, 8)),
    'columns' => array('Fruit count'),
    'chartType' => 'PieChart',
    'containerId' =>  'content',
    'options' => array(
      'forceIFrame' => FALSE,
      'title' => 'Fruit count',
      'width' => 800,
      'height' => 400
    )
  );
  //Draw it.
  $ret = draw_chart($settings);
  $stats = '
'.$ret.'
';

I am then trying to push $stats to page by ajax.
But all I see in display is 'array'.
I feel I need to render the $ret array , or maybe there is some other problem. Any idea where the problem is and how to correct it?
Answer: This question seems similar to what is described in the issue about Ajax load of chart (current status = needs review).
You may want to try the patch attached to either comment #3 or #11 of that issue.


Pass custom variable to block.html.twig

Question: I have a customer who requires the correct set of responsive classes for his block in a given theme depending on its position and count. In my theme_preprocess_page(&$vars) I can identify the blocks in this region and build up an array for each block using its plugin_id and save it to $variables['highlighted'].
In my page.html.twig I use {{ highlighted }} and the array shows up wonderfully. Because block.html.twig by default is set up to be looking for {{ plugin_id }} I expected that I can test if plugin_id is in_array() and add these classes to that instance of the block.
But {{ highlighted }} in block.html.twig returns null in this theme, suggesting that $variables['page'] works for the page, but not block?
Twig has a way to pass off variables to an arbitrary twig file but I do not know how to do this in Drupal. For instance, my page.html.twig is using {{ highlighted }} to pull in these blocks from $variables.
So my question is how does Drupal 8's adaptation the Twig source determine which variables are passed (plugin_id, content, attributes, id, etc) and how I can add mine? I've looked through the twig.engine and searched the Twig source, but it's not clear to me which class controls what variables are passed to blocks?
My other avenue is to find a way to pass this array of classes to theme_preprocess_block but every attempt I made to try this ends up with theme_preprocess_block returning NULL for this array, suggesting that preprocess_page() and preprocess_block() are working separtely.
Answer: You will need to preprocess the block instead of the page. Preprocessing pages will not pass a variable to the block. See hook_preprocess_block. If you are needing to determine values based on how many times a block is rendered you can look into using drupal_static to store variables that can be reused during the rendering process.
Drupal static example:
$first_row = &drupal_static('first_row');

if ($first_row == 2) {
  // I equal 2
}

// Since I am passed by reference I can alter and will keep my value.
$first_row++;

Comment: OK, reading drupal_static() sounds best because it survives render. It's not clear how to recall the static array in theme_preprocess_block. theme_preprocess_page invokes drupal_static_reset('processor_func'). Then gathers blocks in a region in a page and hands off to processor_func($blocks) which instantiates &drupal_static() and then builds up array of classes after verifying !isset('processor_func'). I don't see what variable I put in theme_preprocess_block() to get this array.
Comment: Your preprocess $variables parameter should be able to be edited and added to a value that you can use in the template $variables['my_new_value'] should be available for use in tht template.

Pass custom variable to block.html.twig


What are some good resources on Bayesian unconditional power analysis, besides John Uebersax's article?

Question: I refer to the article "Bayesian Unconditional Power Analysis" by John S. Uebersax (2007).
I'd like to explore the subject further. I haven't checked yet the references that the Uebersax's article mentions, but I was wondering it there are other good references or resources about the subject.
I'm looking preferably, but not necessarily, for resources that use numerical examples, to check if I do not misinterpret some formulas or algorithms.
Comment: I never got around to reading [Grieve's book](https://www.routledge.com/Hybrid-FrequentistBayesian-Power-and-Bayesian-Power-in-Planning-Clinical/Grieve/p/book/9781032111292) but it seems to cover this topic quite extensively.
Comment: @PBulls From the summary, it looks exactly like what I'm looking for, thanks.
Comment: @PBulls, this should be an answer.
Comment: I wasn't sure (not having read it) but I'll add it as one.
Answer: I would recommend Andrew P. Grieve's Hybrid Frequentist/Bayesian Power and Bayesian Power in Planning Clinical Trials (2022), it contains several worked examples of various Bayesian and hybrid approaches to determining power/assurance in clinical trials.
(disclaimer: I followed his workshop but didn't actually read the book)
Answer: This isn't exactly what you requested but is one of the best examples of unconditional decision making for stopping a sequential study that I have ever seen, due to David Spiegelhalter.  His method uses only observables to decide whether it is futile to continue a study. See this from which the graph is reproduced below.


Sending arrays using ObjectOutputStream in multi-threaded server

Question: I have a client/server program with more than two buttons. When a button is clicked it sends a certain request to the server. According to the request the server has to send a string array back. Im using ObjectOutputStream on the server side and ObjectInputStream on the client side. The problem is that the ObjectInputStreamdoes not allow me to call the readObject() method more than once. Is there maybe a better way to send arrays across socket connections. I use PrintWriter to send the request to the server. My server is multi-threaded.
Client:
public FuncListener2()
    {

        butCheckOutSearchTitle.setEnabled(false);
        String hostName = "";

        try {
            hostName = InetAddress.getLocalHost().toString(); // to get the hostName for the exceptions
            clientSocket = new Socket(InetAddress.getLocalHost(), 1211);
            System.out.println(clientSocket.isConnected());
            printWriter = new PrintStream(clientSocket.getOutputStream());
            objIn = new ObjectInputStream(clientSocket.getInputStream());

            listeners();

            clientSocket.setKeepAlive(true);
        }
        catch (UnknownHostException e)
        {
            System.err.println("Don't know about host "+hostName);
            e.printStackTrace();
        }
        catch (IOException e)
        {
            System.err.println("Couldn't get I/O for the connection to the host "+hostName);
            e.printStackTrace();
        }
        catch(Exception ex)
        {
            System.err.println(ex.getMessage());
        }
    }

    public void listeners()
    {
        System.out.println("in listener");

        butCheckOutSearchSurname.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try
                {

                    System.out.println("surname search");
                    int count = 0;

                    String [] array = null;

                    // the reason for the plus sign is to make sure the correct if statement is executed in the server
                    String query = "Select+ * FROM clientDet WHERE clientSurname = \'" + textCheckOutSearchSurname.getText() + "\'";
                    printWriter.println(query);

                    obj = objIn.readObject();

                    if(obj != null)
                    {
                        array = (String[])obj;
                    }
                    else
                    {
                        System.out.println("object empty");
                    }

                    listCheckOutClients.setListData(array);

                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });

        listCheckOutClients.addListSelectionListener(new ListSelectionListener()
        {
            public void valueChanged(ListSelectionEvent e)
            {
                try
                {
                    butCheckOutSearchTitle.setEnabled(true);

                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });

        butCheckOutSearchTitle.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try
                {

                    listCheckOutAvaliable.removeAll();
                    String [] stringArray = null;

                    // the reason for the plus sign is to make sure the correct if statement is executed in the server
                    String query = "Select- * FROM stock WHERE stockTitle = \'" + textCheckOutSearchTitle.getText() + ",\' AND  (stockStatus = \'available\' OR \'reserved\')";
                    printWriter.println(query);

                    obj = objIn.readObject();

                    stringArray = (String[])obj;

                    listCheckOutAvaliable.setListData(stringArray);

                    objIn = null;

                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
      }

Server:
    public void run()
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/videostore", "root", "IronFire");

        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        try
        {
            System.out.println("Server");
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

            objOut= new ObjectOutputStream(clientSocket.getOutputStream());

            while (running)
            {
                //SELECT+ searching surname
                //SELECT- searching titles
                //SELECT@ searching ####Num column

                String command = in.readLine();
                System.out.println("Query:  " + command);
                if(command.substring(0, command.indexOf(" ")).equalsIgnoreCase("SELECT+"))
                {
                    System.out.println("IN IF +"); // for test
                    surname(command);
                }
                if(command.substring(0, command.indexOf(" ")).equalsIgnoreCase("SELECT-"))
                {
                    System.out.println("IN IF -"); // for test
                    title(command);
                }
                if (command.equalsIgnoreCase("quit"))
                {
                    running = false;
                    System.out.print("Stopping client thread for client : " + clientID);
                }
                else
                {
                    out.println(command);
                    out.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void surname(String query)

    {
        try
        {
            System.out.println("In Surname"); // for test
            int count = 0;
            int whileCounter = 0;
            Statement state = conn.createStatement();

            res = state.executeQuery(query.replace("+", ""));

            while(res.next())
            {
                count++;
            }
            String [] stringResult = new String[count];
            res.beforeFirst();

            while(res.next())
            {
                stringResult[whileCounter] = res.getString(1) +"  "+  res.getString(2) +"  " + res.getString(3)  +"  "+ res.getString(5)  +"  "+ res.getString(10) +"  "+ res.getString(11) +"";
                whileCounter++;
            }

            objOut.reset();
            objOut.writeUnshared(stringResult);
            objOut.flush();

        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }
    public void title(String query)
    {
        try
        {
            int count = 0;
            int whileCounter = 0;

            Statement state = conn.createStatement();

            res = state.executeQuery(query.replace("-", ""));
            System.out.println(query.replace("-", ""));

            while(res.next())
            {
                count++;
            }
            System.out.println(count);
            String [] stringResult = new String[count];

            res.beforeFirst();

            while(res.next())
            {
                stringResult[whileCounter] = res.getString(1) +"  "+  res.getString(2) +"  " + res.getString(3)  +"  "+ res.getString(5) +"";
                whileCounter++;
            }

            for(int a = 0; a< stringResult.length; a++)
            {
                System.out.println(stringResult[a]);
            }

            objOut.reset();
            objOut.writeUnshared(stringResult);
            objOut.flush();

        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

}

The errors this is the only error and it is on the client side:
java.io.StreamCorruptedException: invalid type code: 53
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1374)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
    at FuncListener2$3.actionPerformed(FuncListener2.java:197)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2713)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
    at java.awt.EventQueue.access$000(EventQueue.java:101)
    at java.awt.EventQueue$3.run(EventQueue.java:666)
    at java.awt.EventQueue$3.run(EventQueue.java:664)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:680)
    at java.awt.EventQueue$4.run(EventQueue.java:678)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

Answer: You can call the readObject() as may times as you want.  The problem may be that it block when there is nothing to read.  You can make this reader use a background thread so it doesn't matter that its blocking.
The ObjectOutputStream assumes object are immutable.  If you change an object, it doesn't send it again, instead it send a reference to that object instead.
If you want a new copy of an object to be sent each time you can use writeUnshared() or use reset() between calls.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);

List<String> strings = new ArrayList<String>();
strings.add("hello");

oos.writeUnshared(strings);

strings.set(0, "world");

oos.writeUnshared(strings);

oos.close();

ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));

System.out.println(ois.readObject());
System.out.println(ois.readObject());

prints
[hello]
[world]

Comment: the way my program works is that i must press one button get the array chose from the array using JList. that will then enable the other button. when i press the button the request sends. but it seems to me that the array that the server send back to the client clashes with the first array.
Comment: I assume you are changing an array you have already sent and sending it again, but you see the original both times? See my edit.
Comment: I try using writeUnshared() but it gives me a StreamCorruptedException.
Comment: It sounds like you are not reading and writing the data as one stream.
Comment: I suspect you are getting an error on the sender side, but you are discarding them so all you see is a corrupt stream on the reader. Can you printout exception on the sender side?
Comment: That is on the receiver side is it not?
Comment: Yes that is on the reciever side
Comment: So can you make sure you are printing out, rather than ignoring, any exception on the sender side?
Comment: I use printStackTrace() in all my catch blocks. It does not display any errors on the sender side.
Comment: I just that you don't in your code in the question.  Can you update your code to reflect this?
Comment: Sorry about that did not notice. I fixed it above as well as in my original code. I run the program again and there is no exceptions on the sender side only on the reciever side.
Comment: I can't see what is wrong from the code, the only thing I can suggest it to log everything. Log everything you send and receive and make sure objOut is not being used anywhere but the code you have listed.
Answer:
out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

objOut= new ObjectOutputStream(clientSocket.getOutputStream());

You are registering multiple output streams on the socket, some streams may use buffering, others may get as much bytes there are, or send bytes without you knowing, causing the receiving side receive the bytes out of the correct order, to be sure you don't get these bugs, always register only 1 output stream on the socket, not more.


How can I create a method in order to sum the columns from an array?

Question: I can't figure out how to create a method in order to sum the columns from the array once it has been created. Rows and columns are created randomly, but im trying to add up each column at the end. Method in my code is called sumTotal, any suggestions please? Thanks!
public static void printMonths(String[]months){
    for (int i=0; i<months.length; i++)
        System.out.printf("%-20s", months[i]);
}
public static void startSales (double[][] array){
    for (int row=0; row<array.length; row++)
        for (int col=0; col<array[row].length; col++)
            array[row][col] = (int)(Math.random()*10000);
}
public static void printSales (double [][] array){
    for (int row=0; row<array.length; row++){
        for(int col=0; col<array[row].length; col++)
            System.out.printf("L. %10.2f    ", array[row][col]);

        System.out.println();
    }
}

public static void repeat (char c, int n){
    for(int i=0; i<n; i++)
        System.out.print(c);
}
/* public static void sumTotal(double[][]array){
    for (int i=0; i<row.length; i++){
        for (int j=0; j<col.length; j++)
            System.out.println("");
    }
}*/

public static void main(String[] args) {
   Scanner inputNumber = new Scanner(System.in);
   Scanner inputText = new Scanner(System.in);
   String name;
   int rows = 10;
   double total;
   String [] months = {"January", "February", "March"};

    System.out.print("Type complete name: ");
    name = inputText.nextLine();
    System.out.print("Type number of rows: ");
    rows = inputNumber.nextInt();
    if (rows>0){
        double[][] sales = new double [rows][3];

        startSales(sales);

        System.out.print("\nSales Report\n\n");
        System.out.print("Salesman: " + name + '\n');
        System.out.println();

        repeat('=', 60);
        System.out.println();

        printMonths(months);
        System.out.println();

        repeat('=', 60);
        System.out.println();

        printSales(sales);
        repeat('=',60);

        System.out.println();
    }

Answer: I have not executed and compiled the code but the following code may give you a head start.
Version 1 (Get sum of specific column)
public static int sumTotal(double[][] array, int col)
{
    int total = 0;

    for (int i = 0; i < array.length; i++)
    {
        total += array[i][col];
    }

    return total;
}

int sum = sumTotal(myArray, 3); //sum of only column 4 starting from 0 index

Version 2 (Get sum of all columns)
public static int[] sumTotal(double[][] array, int totalcols)
{
    int[] total = new int[totalcols];

    for (int i = 0; i < total.length; i++)
    {
        total[i] = 0; //initialize to 0
    }

    for (int i = 0; i < total.length; i++)
    {
        for (int j = 0; j < array.length; j++)
        {
            total[i] += array[j][i];
        }
    }

    return total;
}

int[] sum = sumTotal(myArray, 6) //6 is the total columns count you will get 1D array of sum of 6 columns


On "big list" questions

Question: Several times now, the issue of whether questions that solicit some sort of list as an answer (e.g. a list of book recommendations) are valuable here.

This questions has some comments to that effect (but seems to
have generated some useful answers).
This question also has comments to that effect (no answers and a lot
of negative votes).

Do we want to adopt a blanket ban on these kinds of questions, or is there some way to shape them to turn them into a valuable resource?
Answer: My view is that we should adopt a strict position on these kinds of question, but not an outright ban. As I have mentioned elsewhere, my view is motivated by this example from TeX SE, which I think shows what a good resource a list question can become if well-managed (look at the number of up votes/favourites!).
Comparison of that example with some other, less successful cases suggests some rules of thumb for a good list question:

One suggestion per answer. This makes the answers easier to browse, avoids duplication and, most importantly, allows people to vote on individual suggestions. From the TeX example, this has meant that the voting mechanism can serve to promote what the community thinks are the best suggestions.
Standardised format for each answer. For example, a title in standard formatting that states what item this answer is recommending. A standardised bullet-list of metadata (e.g. operting systems supported for software, topics covered for a book, etc.). A standardised image (e.g. screenshot or cover image).
All answers are community wikis. Necessary so that the community can ensure that the list remains an up to date resource.
A fairly well-defined and meaningful scope. Big list of economics books is probably not useful. List of textbooks in industrial organisation is likely to be more useful.

My feeling is that with guidelines like these we can support some very valuable list questions (book recommendations, software recommendations, seminal papers on a topic, etc.)
Comment: I don't think they should be community wikis. If a comment is posted, the original poster can update the link. Worst case: a new link is posted in the comments. Remember, economics has a lot of disputes, so... we'd want to avoid even the possibility of edit wars.
Answer: If we ignore the way that list questions can break normal voting mechanisms, allowing list questions does provide some value to some people, including the original poster. It is also one way to solve what I call the "zero or many" paradox where an disinclination to answer a list question results in none of the good answers being posted.
To discourage 10 or 20 answers to a list question, I would suggest raising the bar a bit by requiring an respondent to explain why the resource is a good one; in a manner beyond personal anecdote. It also allows for some "meat" for the voting mechanism to sift answers.
Answer: Are these examples expert-level questions? No, they're not. So they are off-topic for the private beta.
Do they have objective single answers? No, they don't. So they're unsuitable for the Q&A format.
Is there a place for them? Yes there is. We have tag wikis. As the name indicates, they are wikis: they are designed to be collaborations, with multiple contributors. They are a resource to provide broad information about a subject, outside the constraints of the Q&A format. So book lists belong in tag wikis.
Comment: Firstly, refusing to think beyond the private beta (likely to end within ~1 week) is incredibly myopic. Secondly, to the extent that experts ask each other for, e.g., book/paper recommendations, and that *only* experts can recommend good graduate+ level texts means that they *are* expert level questions by definition. Thirdly, the objective single answer criterion is too narrow because it rules-out a whole range of potential questions about economic modelling, where there is seldom a single right way. Other SE communities have found such questions useful, so why adopt a per se prohibition?
Comment: @Ubiquitous if you're interested in the status of this in the public beta, then the time to ask is in the public beta, not now.

On "big list" questions


Biblio module: importing ris files, titles not importing even though mapped correctly

Question: I have ris files of citations to upload, and despite having titles mapped correctly at admin/config/content/biblio/iomap/edit/ris -- T1 goes to Title, I get nothing but "untitled" nodes. I am using version 7.x-1.0-rc7. Some other data seems to populate appropriately, but looking at logs, many things aren't, so it's more than just titles. I have a large number of errors for a number of fields along the lines of:
<code>Notice: Undefined property: stdClass::$title in _biblio_ris_parse_line() (line 357 of C:\wamp\www\mysite\sites\all\modules\biblio\modules\RIS\biblio_ris.module).
</code>
Thinking there might be something wrong with the data, I created my own simple ris file and tried an example file that I found online. I had the same problems with all of them.
I tried the dev version and have the same problem.
Any help would be appreciated.
Answer: after finding this comment, I changed two lines in biblio_ris.module:
339 from
<code>$node->biblio_pages .= ($tag == "SP") ? $data : " - " . $data;
</code>
to
<code>$node->biblio_pages = ($tag == "SP") ? $data : " - " . $data;
</code>
and 357, from:
<code>$node->$field .= $data;
</code>
to
<code>$node->$field = $data;
</code>
It works.


Um programa desktop pode ser considerado client-side?

Question: Sempre quando eu escuto/leio sobre server-side e client-side é referente a aplicações web, mas estes termos podem ser aplicados para programas desktop? Por exemplo se tenho uma aplicativo que consome um web-service ou até mesmo um Notepad (offline) posso considerá-los client-side, ou esta nomenclatura é apenas para aplicações web?
Answer: Quaisquer aplicações de qualquer tipo que sirva para acessar algo que é servido externamente à aplicação "principal" pode ser considerado um cliente, não precisa estar nem em outra máquina.
O Outlook é uma aplicação desktop, certo? Ele é um cliente de e-mail. O navegador é um cliente HTTP que renderiza páginas e ele é desktop.
Acho que uma aplicação que não faz comunicação com outra coisa não deveria ser chamada de cliente, mas dá o que pensar. Uma aplicação que acessa um arquivo está sendo servida pelo menos pela file system, portanto ela é cliente da FS, certo? No mínimo é cliente dessa API.
Uma aplicação não precisa ser cliente de apenas uma coisa. E não precisa toda ela ser cliente de algo, só alguma parte dela.
Um computador que roda em uma rede e pega informações de algum lugar é um cliente de rede, certo? Não precisa sequer ser aplicação para chamarmos de cliente.
O conceito de cliente e servidor é ortogonal ao que a aplicação faz no geral. Algo nela é cliente de algo externo que fornece o que ela precisa.
Se tudo o que importa à aplicação é o acesso externo então podemos até dizer que a a aplicação é um cliente de forma geral.
Se você tiver uma aplicação web que carrega no seu navegador e a partir daí não acessa mais nada externo, ela é um cliente? Do que?
Termos existem para explicar um conceito adotado. Se ele é irrelevante em certa situação, não tem porque usar o termo. Se vai usar o termo tem que entender completamente o que ele é, porque comunicação errada é pior que não comunicação, em grande parte das vezes, e em geral a pessoa só sabe tarde demais se importa ou não.
Informação útil: Usar validação via cliente é suficiente?.
Coloquei no GitHub para referência futura.


Should I log transform a right skewed continuous variable in Weibull AFT model?

Question: Suppose I have a Weibull AFT Model or any other AFT models such as:
survreg(Surv(time, censor) ~ a right skewed continuous variable,
        data =  sub, dist = "weibull")

Should I log transform this right skewed continuous variable?
I found that the AIC and BIC are still the same after transformation. However, I have not yet seen any AFT models actually have any transformed covariates. However, the response variable is like Y = log(T).
Answer: You don't need to because the Weibull pdf can be skewed depending on the values of the location and scale parameters.  AFT regression packages will determine the maximum likelihood values of location and scale, which will represent the underlying hazard rate over time.


Converting db_query from Drupal 6 to Drupal 7: Invalid parameter number: number of bound variables does not match number of tokens

Question: I have a custom localisation function in a Drupal 6 module that I would like to convert to Drupal 7 but I have hit a wall with the db_query function. I have the following code (in d6 and d7):
<code>// Drupal 6
db_query("REPLACE INTO {locales_target} (lid, translation, language) VALUES ((SELECT lid FROM {locales_source} WHERE source = '%s' LIMIT 1), '%s', 'sv')", $name['eng'], $name['swe']);

// Drupal 7 (not working)
db_query("REPLACE INTO {locales_target} (lid, translation, language) VALUES ((SELECT lid FROM {locales_source} WHERE source = :source_eng LIMIT 1), ':source_swe', 'sv')", array(':source_eng' => $name['eng'], ':source_swe' => $name['swe']));
</code>
I get the following error message when I try to use the d7 version:

PDOException: SQLSTATE[HY093]: Invalid parameter number: number of
  bound variables does not match number of tokens

D7 API for db_query
Could somebody help me out figuring why the db_query isn't working?
Comment: looks like it should work, what are the values of the $name[''] variables?
Answer: You've quoted one of the parameters when you shouldn't have.
PDO interprets this:
<code>':source_swe'
</code>
as a string, and it (correctly) doesn't try to change it.
What you're looking for is simply
<code>:source_swe
</code>
So that parameter replacement can occur. As in,
<code>db_query("REPLACE INTO {locales_target} (lid, translation, language) VALUES ((SELECT lid FROM {locales_source} WHERE source = :source_eng LIMIT 1), :source_swe, 'sv')", array(':source_eng' => $name['eng'], ':source_swe' => $name['swe']));
</code>


In Hindemith's terms, how do I classify this melodic gesture?

Question: I am attempting to analyze the G note in the melody pictured below using Paul Hindemith's terminology/framework set out in his Book 2.
From what I can gather, the melodic formulae Hindemith is considered with include the:

Repeat tone;
Passing tone;
Suspension;
Anticipation;
Unprepared or free suspension;
Neighbor tone approached by skip;
Neighbor tone left by skip;
Accented free tone; and
Unaccented free tone.

As you can see, the G is a non-chord tone that is approached and left by skip. So, I believe that would make it some sort of free tone.  That being said, the G, on beat 2.5, is not in a weaker or stronger metric point than the note which follows it, the C on beat 3.5.  Because of this, I don't see how it could be classified as either an accented or unaccented free tone.
How would you classify this melodic operation?  I would like to stick to the terms and definition found in the book I am referencing, so please let me know if I can provide any further information from the text.
Comment: Scary? are you joking? The question is about NCT classification, the concern is about the melody. I wanted to know if Hindemith gave it as an example to go with the list.
Comment: I think that to answer this, the harmonization for the entire measure is required.
Comment: Please see the OP--the F major covers all beats in this measure.
Comment: Cool. Is there a measure before and/or after? Those also could influence the interpretation.
Comment: Please see OP for a more complete image.  Thanks
Comment: What piece is this excerpt from? Honestly, the chord names for the entire first measure and the second chord name of the second measure (the one for the note you're asking about) look completely unbelievable (at least to me).
Comment: I'm curious of the origin of the example too. Is it supposed to exemplify Hindemith's teaching?
Comment: is the dominant to subdominant movement scary to you?  its from my own composition--no relation to Hindemith whatsoever
Comment: @MichaelCurtis yeah, i'm joking.  wasn't sure if you were use to seeing "retrogressions" in this context
Answer: TL;DR
In my interpretation, the best fit for the G is neighbor tone both approached and left by skip. I would also say it's part of an incomplete double-neighbor gesture, along with the preceding E.

Here is my thinking for each of the options given
Preferred answers are in bold; "okay" answer is in italic

Repeat tone

Obviously not, since the G only occurs once.

Passing tone

Again, obviously not, since the G is approached and left by skips in opposite directions.

Suspension

Again, no, since the G isn't held over from the previous harmony.

Anticipation

No, since the G is not part of the following harmony.

Unprepared or free suspension

Also no, for the same not-a-suspension reason given above. (However, it's interesting to consider that, since the harmony in the previous measure is G, perhaps this tone could be perceived as a suspension under the right circumstances. Not here, though.)

Neighbor tone approached by skip

To my ear, the G clearly functions as an (incomplete) upper neighbor to the preceding F. This becomes more clear by omitting the E — the overall sound of the melody is not significantly changed.

Neighbor tone left by skip

Obviously, since I consider the G a neighbor tone, it is left by skip, thus....

Accented free tone

If I were grading an exam that gave this as the answer, I would accept it. The G is accented by virtue of being both a syncopation and by being longer that the E. I find the "free tone" interpretation less convincing than the "neighbor" interpretation, but not unreasonable.

Unaccented free tone

I would consider the G accented because of the notes that come before, but even excluding that, it's clearly not unaccented for the same reasons I consider it accented.
Answer:
...that being said, the G, on beat 2.5, is not in a weaker or stronger metric point than the note which follows it...

Why does it matter what the following note is? Does Hindemith define accent differently than the standard?
The G is off the beat. It's unaccented.
You might say two syncopated notes creates a kind of accent, shifting things to the off beat, but a least in terms of non-chord tone classification, accent is on the beat, unaccented is off the beat.
Comment: Hindemith is concerned with the relative strength of tones, be it the tonal or metric significance.  I suppose this dynamic most relevant in suspensions, anticipations, and the like
Comment: It appears that you and @aaron have different definitions for accented/unaccented notes?
Comment: @286642, the context of the accent is the difference. Syncopation is accenting a weak beat. But in non chord tone definitions, all I have ever seen, syncopation is _not_ included, it's a different context, and in that context accent is about on/off the beat.
Comment: Actually, Hindemith points out this changing context at the end of chapter IV, book I. Essentially when the rhythm is syncopated, the normal strong/weak beat accents are reversed.


Character is stored inplace of an integer

Question: Character is stored in place of an integer
    /* C program to find strong number using Structure and Pointers*/

#include<stdio.h>
#include<stdlib.h>

struct strg {
    long int a;
}*strgvar;

int strong(int);

int main() {
    int result;
    strgvar = (struct strg*) malloc(sizeof(struct strg));
    printf("Enter the number ...\n");
    scanf("%ld", &strgvar -> a);
    result = strong(strgvar -> a);
    if(result == strgvar->a) {
        printf("Its a strong number !");
    }
    else {
        printf("Its not a strong number !");
    }
    return 0;
}

int strong (int a) {
    int fact, r, n, sum = 0;
    while(a != 0) {
        r = r % 10;
        for(int i =0; i <= r; i++) {
            fact = fact * i;
        }
        sum = sum + fact;
        n = n/ 10;
    }
    return sum;
}

While running this program , the input integer is not storing in the variable.But while entering any character it prints "Its a strong number!"
Example:

case 1:
Enter the number... 234
2
178
er
fg yu8 . case 2: Enter the number ...e

Its a strong number!
Comment: First check the result of `scanf`. It returns the number of successful conversions. If the result is 0, something is wrong and `strgvar->a` remains uninitialized.
Comment: Also you are doing `r = r % 10;` with an uninitialized `r`. The result of `strong` is undefined. What exactly is `strong` doing?
Answer: The loop in strong is obviously infinite unless a==0 to start.  If scanf fails, strgvar->a is left uninitialized, so your program has undefined behavior.  One "reasonable" possibility is that the value is read as 0, which produces the observed result.


Carpet under guitar amp or on floor

Question: I've seen a lot of carpets in studio and live sessions. Sometimes there are on the floor and sometimes directly under guitar amp. What's their purpose?
Answer: Bare floors can cause extra reflection of sound, sometimes causing unwanted reverb or reinforcement of high frequencies. The carpets mute the reflective surface.
An amp sitting on a hard surface may produce some vibration between the feet and the surface, so a carpet can help with that. They also slide around more, so if you bump them they may skid, or in the case of tilt-back like the photo, fall over. Also, if the metal feet or corners have scratches in the metal, they can leave marks or scratches on unprotected wood floors.
Comment: They also reduce the sound of big clompy boots, if the guitarist forgot to wear soft trainers.

Carpet under guitar amp or on floor


javascript get value of html radio button input selected

Question: i have a simple form like this :
<form id="formSearch">
<input type="radio" name="number" value="1">singular

<input type="radio" name="number" value="2">plural

<INPUT type="Submit" Value="Show" name="show" ></INPUT>
</form>

I want to get the "radio-value" of the selected button with javascript :
var account = document.getElementsByName("number").value;

do not give the correct response. if I give a trap :
alert(account);

the result is : undefined.
I do not know where the harm, is there who is willing to help me, thanks
Answer: Using javascript:
document.querySelector('[name=number]:checked').value;

Answer: In jquery, you can use the checked attribute selector for that
$("[name='number']:checked").val()

Answer:

function test() {

  var checkedRadioBtnList=new Array();

  var account = document.getElementsByName("number");

  for(i=0; i<account.length;i++){
    if(account[i].checked){
      checkedRadioBtnList.push({value:account[i].value});
    }
  }

  console.log(checkedRadioBtnList);
}
<form id="formSearch">
<input type="radio" name="number" value="1">singular

<input type="radio" name="number" value="2">plural

<INPUT type="Submit" Value="Show" name="show" onclick="test()" ></INPUT>
</form>

getElementsByName will return an array.
EDIT
I had simply answer the question, how to get checked value using javascript.
There are lots of option to store values as per application. I have improve my answer to store checked radio button values in an Array using JSON Object.
Comment: But how do you know which element is selected? Simply accessing the first radio is not a solution.
Comment: @RoryMcCrossan check my updated answer.
Comment: alerts false if i choose plural.
Comment: @Jitendra Tiwari : This way right if there are only two choices ( singular and plural ), what if there are more than two options ?
Comment: @Jai, @agus I have update my answer. please check my comment on `EDIT` part.


How to redirect user to an url when node is flagged?

Question: My problem is related to the Drupal 8 versions of these two modules: rules and flag.
What I want to achieve

Some node types on my site are offering a global flag as a link (for e.g. "report error" flag)
If the user clicks on it, he should be redirected to a special contact form. The flagged node URL should be submitted to an entity reference field automatically on the contact form too.

How I solved it in Drupal 7
In Drupal 7 there was a rules event "node is flagged" to trigger the redirect action. The flagging URL I could pass via Drupal 7 module "entity reference prepopulate" (which functionality is merged into core reference field in Drupal 8).
In Drupal 8 the rules event "node is flagged" seems not to exist.
Any idea how to realise a behaviour like described above in Drupal 8?
THX in advance,
Phil
Answer: You need to use the event, After saving new flagging
Add Condition of Flag, and enter flag machine name
Add action of Page redirect, enter the url where you want to redirect. Ex: <code>/node/1</code>

Important
In your flag settings, you need use a link type of Normal link, because it won't work with AJAX


If $|z|=1$ and $\arg(z)=\theta$, $0<\theta<\frac{\pi}{2}$, find $\arg(\frac{2}{1-z^2})$.

Question: $\newcommand{\cis}{\operatorname{cis}}$If $|z|=1$ and $\arg(z)=\theta$, $0<\theta<\frac{\pi}{2}$, find $\arg(\frac{2}{1-z^2})$.
First, because $|z|=1$, then I can express $z$ as $z=\cis(\theta)$. Then I need to get rid of the one in the numerator: $1-z^2=1-(\cis(\theta))^2=1-\cis(2\theta)=[\cdots]=-2i\sin(\theta)\cis(\theta)$ (after some transformation).
Then $\displaystyle \frac{2}{1-z^2}=\frac{2}{-2i\sin(\theta)\cis(\theta)}=\frac{i}{\sin(\theta)(\cis(\theta)}=\frac{1}{\sin(\theta)}\cdot\frac{\cis(\frac{\pi}{2})}{\cis(\pi)}=\frac{1}{\sin(\theta)}\cdot\cis\left(\frac{\pi}{2}-\theta\right)$.
So the argument should be $\frac{\pi}{2}-\theta$. However, my textbook gives the answer $\theta-\frac{\pi}{2}$. It also says that the mod is $\csc(\theta)$, which agrees with $\frac{1}{\sin(\theta)}$, but the argument is different - what am I doing wrong?
Answer: It amounts to finding the argument of $\displaystyle\frac1{1-z^2}$. Now, if $\def\I{\mathrm i\mkern 1mu}\def\E{\mathrm e}z=\E^{\I\theta}$, then
$$\frac1{1-z^2} =\frac1{1-\mathrm e^{2\I\theta}}=\frac{-\E^{\I\theta}}{\E^{\I\theta}-\E^{-\I\theta}}=\frac2{\sin\theta}(-\I\E^{\I\theta})=\frac2{\sin\theta}\E^{\I(\theta-\tfrac\pi2)}.$$
Hence
$$\arg\frac2{1-z^2}\equiv\theta-\frac\pi2\mod2\pi.$$
Answer: $$1-z^2=1-(\cos2\theta+i\sin2\theta)=2\sin^2\theta+i2\sin\theta\cos\theta=2i\sin\theta(\cos\theta-i\sin\theta)$$
$$\dfrac2{1-z^2}=\dfrac2{2i\sin\theta(\cos\theta-i\sin\theta)}=\dfrac{-i(\cos\theta+i\sin\theta)}{\sin\theta}=1-i\cot\theta$$
If $\tan A=\dfrac{-\cot\theta}1=\tan\left(\dfrac\pi2+\theta\right)$
$A=n\pi+\dfrac\pi2+\theta$ where $n$ is any integer
As $0<\theta<\dfrac\pi2,n\pi+\dfrac\pi2<A<n\pi+\dfrac\pi2+\dfrac\pi2$
If $A\in\left(-\dfrac\pi2,\dfrac\pi2\right); n=-1\implies A=(-1)\pi+\dfrac\pi2+\theta=\theta-\dfrac\pi2$
Using this,
 arg$\left(\dfrac2{1-z^2}\right)=\theta-\dfrac\pi2$
Answer: So $\;z\in S^1\;$ and on the arc in the first quadrant, thus $\;z=\cos\theta+i\sin\theta\;\implies\;$
$$\frac2{1-z^2}=\frac2{1-\cos2\theta-i\sin2\theta}=\frac{2-2\cos2\theta+2i\sin2\theta}{2(1-\cos2\theta)}=$$
$$=1+\frac{\sin2\theta}{1-\cos2\theta}i\implies\arg\left(\frac2{1-z^2}\right)=\arctan\frac{\cos\theta}{\sin\theta}=$$
$$=\frac\pi2-\arctan\frac{\sin\theta}{\cos\theta}=\frac\pi2-\theta$$
and I can't see how the textbook gives the additive inverse of this since the argument of the arctangent is positive, so I'd say you're right and the textbook is wrong.


Combining ArrayList without duplicates

Question: import java.util.ArrayList;
import java.util.Collections;

public class SmartCombining {
    public static void main(String[] args) {
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        ArrayList<Integer> list2 = new ArrayList<Integer>();

        Collections.addAll(list1, 4, 3);
        Collections.addAll(list2, 5, 10, 4, 3, 7);

        smartCombine(list1, list2);
        System.out.println(list1);
        System.out.println(list2);
    }

    public static void smartCombine(ArrayList<Integer> first,
            ArrayList<Integer> second) {
        first.addAll(second);
    }
}

So, I want to combine two lists into one, but if the second list contains a number from the first it won't be added. So far my method adds them all together.
Comment: Just call it `extend()`. That is what Python calls it. :-p
Comment: If you don't want duplicate values use a set, e.g. a TreeSet
Comment: Don't use a `List`. This is what a `Set` is for.
Answer: Well, one way to do it is to iterate through the second list while checking if each element exists in the first list. If it doesn't, add it.
public static void smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
     for(Integer num : second) {      // iterate through the second list
         if(!first.contains(num)) {   // if first list doesn't contain current element
             first.add(num);          // add it to the first list
         }
     }
}

Another way would be for you to hold your values inside a set (like HashSet) which doesn't allow any duplicates. Then you can combine them like:
first.addAll(second);

One more way you could do it is to first remove all elements from the first list that exist in the second list (the ones that would be duplicated). Then you add all elements of the second list to the first list.
public static void smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
    first.removeAll(second); // remove elements that would be duplicated
    first.addAll(second);    // add elements from second list
}

Comment: I don't think OP wants to modify the second list, only the first. Flip that logic around.
Comment: @Mr.Polywhirl yes, you are right, minor change, just did it
Answer: The simple, no brains solution:
Set<Integer> joinedSet = new HashSet<Integer>();
joinedSet.addAll(list1);
joinedSet.addAll(list2);

Answer: Remove duplicates, then merge both lists:
list1.remove(list2);
list1.addAll(list2);

If you dont want to alter the original list, then first create a backup:
list1BP = new ArrayList(list1);

Another approach is to use HashSet, see other answers.
Comment: Looks like people agree with you: [List intersection in java](http://stackoverflow.com/questions/4349369/list-intersection-in-java).
Answer: Use Set, it has been created for that purpose. A Set cannot contain 2 identical elements, based on the equals method.
Set<Integer> list1 = new HashSet<Integer>();
Set<Integer> list2 = new HashSet<Integer>();

Using a combination of ArrayList and contains method is an antipattern here.
Comment: The whole point of using lists is to have ORDERED collections. If you switch to HashSet, you loose that. Maybe your answer would be better with LinkedHashSets or something.
Answer: There are two easy way you can combine two Lists and duplicate will be removed.
1) First and very easiest way you can get your output, by creating equivalent HashSet object of your ArrayList. Since HashSet does not allow duplicates.
public static void main(String[] args) {
    ArrayList<Integer> list1 = new ArrayList<Integer>();
    ArrayList<Integer> list2 = new ArrayList<Integer>();

    Collections.addAll(list1, 4, 3);
    Collections.addAll(list2, 5, 10, 4, 3, 7);
    System.out.println(smartCombine(list1, list2));
}
public static HashSet<Integer> smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
    first.addAll(second);
    HashSet<Integer> hs = new HashSet<Integer>(first);
    return hs;

2) There is another way using advanced for loop. Iterate the second list  and check if the current element is not in first list and then add the current element.
public static void main(String[] args) {
    ArrayList<Integer> list1 = new ArrayList<Integer>();
    ArrayList<Integer> list2 = new ArrayList<Integer>();
    Collections.addAll(list1, 4, 3);
    Collections.addAll(list2, 5, 10, 4, 3, 7);
    smartCombine(list1, list2);
    System.out.println(list1);
}
public static void smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
    for (Integer num : second) {
        if (!first.contains(num)) {
            first.add(num);
        }
    }
}

Note: The second way will work fine only if first list has no duplicates.
Answer: use contains(Object) method in ArrayList
public static void smartCombine(ArrayList<Integer> first,
        ArrayList<Integer> second) {
    for(Integer i :second){
       if(!first.contains(i)) { // if first list doesn't contain this item, add item to the first list.
          first.add(i);
       }
    }
}

Answer: Have you tried ArrayList.addAll()
Look at this java doc
As pointer out this would not handle duplicates which can easily be removed using a Set
Comment: Does not handle duplicates.
Comment: i agree it does not. Logic for that will have to be written separately

Combining ArrayList without duplicates


$_SESSION nao persiste em outras paginas na aplicaçao

Question: boa noite pessoal,
estou utilizando o codeigniter e session nativa do php $_SESSION, acontece que so consigo utilizar a session quando instancio em um controller de login que redireciona para uma outra pagina, mas se eu quiser utilizar as informaçoes dessa session em outra pagina nao consigo, diz q a session nao existe. ja quebrei a cabeça aki ja tentei de tudo um pouco mas nao consigo prosseguir na minha aplicaçao sem antes resolver essa questao, gostaria mto da ajuda do pessoal que manja um pouco mais. obrigado a todos!
controller (essa parte funciona de boa ea view admin recebe tranquilo a session o problema eh se eu quiser utilizar as informaçoes dessa session em outras views informa q nao existe)
public function check_login()
{
    $login = $this->input->post('login');
    $pass =  md5(md5(md5($this->input->post('pass'))));

    $user = $this->login_model->checkLogin($login, $pass);

    if(!$user)
    {

        $data['msg_erro'] = "Login ou senha inválido.";
        $this->load->view('index', $data);

    }
    else{

        if($user->cod_user == 1)
        {

            $_SESSION['ci_session'] = $user->name;
            $this->load->view('admin');

        }
        else if($user->cod_user == 2)
        {
            $_SESSION['vendedor'] = $user->name;

            $this->load->view('vendedor');
        }
    }

}

Comment: Mesmo que não vá usar especificamente nenhum método dela, carregue a [Session Library](https://www.codeigniter.com/user_guide/libraries/sessions.html#using-the-session-class).
Answer: Então amigo, antes de você poder cria ou pegar o valor de uma super variável $_SESSION, e preciso primeiro inicia a sessão session_start(), uma unica vez em cada pagina que for necessário criar ou pegar uma $_SESSION.
Particularmente eu acho mais recomendável usar a librarie session do CI.
para você cria uma sessão com a librarie session do CI, seria:
$this->session->set_userdata('nameSession', 'valueSession');

e para pegar uma session,seria:
$this->session->userdata('nameSession');

lembrando que você deve carregar a librarie antes de usar, que pode ser feito tanto no autoload como no controller.
carregando librarie no autoload do CI: Application/config/autoload.php
$autoload['libraries'] = array('session');

carregando librarie no controller:
$this->load->library('session');

se você carregar uma librarie no autoload, ela estará disponível em toda a aplicação, já se você carregar ela no controller, elá estará disponível somente no controller carregado, caso você precise usar ela em outro controller sera preciso carregar ela novamente.
seu código ficaria assim usando a librarie do CI:
public function check_login()
{
    $login = $this->input->post('login');
    $pass =  md5(md5(md5($this->input->post('pass'))));

    $user = $this->login_model->checkLogin($login, $pass);

    if(!$user)
    {
        $data['msg_erro'] = "Login ou senha inválido.";
        $this->load->view('index', $data);
    }
    else{

        if($user->cod_user == 1)
        {
            $session['admin'] = $user->name;
            $this->session->set_userdata($session);
            $this->load->view('admin');
        }
        else if($user->cod_user == 2)
        {
            $session['vendedor'] = $user->name;
            $this->session->set_userdata($session);
            $this->load->view('vendedor');
        }
    }
}

você pode conferir mais detalhes na documentação do CI: https://www.codeigniter.com/user_guide/libraries/sessions.html
Answer: Olá, não sei se sua session está inicializada no arquivo autoload, se não estiver, pode tentar. No meu caso estava e não funcionava. Retirei de lá efiz o seguinte:
   session_start();
   $_SESSION['user'] = $user;

Já no controller onde precisava receber:
  session_start();
  print_r($_SESSION);
  die();

Espero que ajude!


Looking for specific enumeration of the rationals

Question: We are asked if there exists an enumeration $\{r_n\}$ of the rationals such that the set $\displaystyle \bigcup_{n=1}^{\infty}(r_n-\frac{1}{n}, r_n+\frac{1}{n})$ has a non empty complement.
I believe the answer is yes. Consider an enumeration $\{r_1,r_2,\dots\}$ where if $i$ is not a power of $2$, then $r_i \in (0, 1)$. In that case, $\displaystyle \bigcup_{n\text{ is not power of 2}}(r_n-\frac{1}{n}, r_n+\frac{1}{n})\subseteq(-\frac{1}{3},\frac{4}{3})$ and so the measure of this union (which is measurable since it is a countable union of measurable sets) is at most $\frac{5}{3}$.
Now look at $\displaystyle \bigcup_{n = 1}^\infty(r_{2^n}-\frac{1}{2^n}, r_{2^n}+\frac{1}{2^n})$. Specifically, look at its measure. Again this is a measurable set, and its measure is less or equal to the sum of the measures of the subintervals in the union, meaning $\displaystyle m(\bigcup_{n = 1}^\infty(r_{2^n}-\frac{1}{2^n}, r_{2^n}+\frac{1}{2^n})) \leq \sum_{n=1}^{\infty}\frac{1}{2^{n-1}}= 2$
To sum up, in this enumeration of the rationals, the union we are originally asked about is a measurable set of measure at most $2+\frac{5}{3}$, hence its complement is also measurable and has infinite measure, so it's for sure not empty.
Is this solution correct? And furthermore, can we actually find such an enumeration of the rationals?
Answer: Yes.
There are $\aleph_0$

powers of $2$ and
non-powers of $2$ in $\Bbb N$
and rationals inside
and outside your chosen interval

If you desire to be more specific: Let us assume you have an enumeration of $\Bbb Q=\{q_1,q_2,\ldots\}$. Then you can let
$$a_n=n\text{th rational in }(0,1)= q_{\min\{\,k\in\Bbb N\colon\left|(0,1)\cap\{q_1,\ldots, q_k\}\right|=n\,\}}$$
and
$$b_n=n\text{th rational not in }(0,1)= q_{\min\{\,k\in\Bbb N\colon\left|\{q_1,\ldots, q_k\}\setminus(0,1)\right|=n\,\}}$$
and notice that $\Bbb N\to \Bbb Q\cap (0,1)$, $n\mapsto a_n$ and $\Bbb N\to \Bbb Q\setminus (0,1)$, $n\mapsto b_n$ are bijections. Finally, let
$$r_n=\begin{cases}a_k&\text{if }n=2^k\\
b_{n-\lfloor\log_2 n\rfloor}&\text{otherwise}\end{cases} $$
Comment: So there is no need to specifically find such an enumeration in order to prove the statement? It's enough to explain that it exists


Definition of complex differentiable

Question: I wonder why the definition of complex differentiable at $z$ is
$f(z+h)-f(z)=f'(z)h+o(|h|)$
instead of
$f(z+h)-f(z)=f'(z)h+o(h)$
It seems the same... But in real analysis, it usually drops the absolute.
Is there any special reason for doing this?
Thank you in advance.
Comment: It should be $f'(z)\cdot h$. -- Check the definition of $o(f(h))$, the absolute value is part of it.
Answer: Definition: $f$ is holomorphic at $z_0$ if there exists $\xi_{z_0} \in \mathbb{C}$ such that $f(z) = f(z_0) + \xi_{z_0}(z-z_0) + o(|z-z_0|)$. One writes $\xi_{z_0} := f'(z_0)$.
The module is needed otherwise it doesn't really make any sense depending on your definition of $f(x) = o(g(x))$. Remember $\mathbb{C}$ can be thought like $\mathbb{R}^2$, so you're really doing multivariable calculus here.
Comment: If $g$ tends to zero, after multiplying $g$ with a unit complex $\frac{|\Delta z|}{\Delta z}$ it still tends to zero, and vice versa. Is that right?
Comment: @gžd15 If $g$ is a function that tends to $0$ as $z \rightarrow z_0$, then $ag$ tends to $0$ as $z \rightarrow z_0$ given any constant complex number $a$ indeed; what's your point?
Comment: Then for the remainder $g(z)=o(|z-z_0|)$, isn't it equivalent to say that $g(z)=o(z-z_0)$?
Comment: It does not really matter. We usually put the module to put emphasis on the objects we're working on, but you're fine writing $o(z-z_0)$ if you prefer, as long as you realize it doesn't really matter ;)
Comment: Understood. Thanks ;)
Answer: It is a matter of taste and definitions. In a Banach space $X$ if $g$ is defined in a neighborhood of $x\in X$, I am used to saying that $g(x+h) = g(x) + o(h)$  iff
 $$ \lim_{h\rightarrow 0} \frac{\|g(x+h)-g(x)\|_X}{\|h\|_X} = 0 $$
Using that definition you don't need the abs value in the case of the complex plane ${\Bbb C}$. A more precise notation is
  $$ g(x+h)=g(x)+o_x(h)$$
making precise that the remainder actually depends upon $x$.
Personally I don't see any advantage of putting an abs sign (or norm) inside the "o".

Definition of complex differentiable


Is this hand position a bad practice for practicing piano?

Question: I included some drawings to illustrate what I mean. If it's still unclear, I will try and take a picture to show the situation.

I just started learning piano this year by following some lessons online. One of them emphasised on how important it was to have the curved fingers shape as if you are holding a round object or have your hands on your knees.
Although getting my hand into the correct shape is simple enough, in practice I can't do it because of the fingernail hitting the key before my finger does. Since I wanted to feel the touch of the key, I unconsciously started shifting my fingers into pressing the keys with my fingerprint instead (I don't know whether or not that still counts as pressing with the tip of the finger).
The shape my fingers are supposed to take:

The shape my fingers started taking after practicing for a while:

Up until now, I only practiced simplified short musics so I didn't have much trouble and kept pressing the keys like that. From what little I could read, having fingernails is at most cumbersome but does not prevent practicing piano.
However, after practicing Hanon exercise No. 1 for a few dozen minutes, I realised that I was feeling fatigue on various area depending on the situation (sometimes the middle of the hand, sometimes the wrist, sometimes somewhere along the forearm). Upon practicing it a lot, I sometimes realise that my arms are dropping below the height of the piano keys (which means my hands are on the same level as the keys instead of above). That, and the fatigue also makes me press the keys out of rhythm too when I try to play faster.
Since I read somewhere that the body usually feels when something is wrong, and I have no private teacher, I could only make hypothesis of what I think it means:

Feeling fatigue after practicing only means I should take a break.
Since it's a digital piano with simulated action, I just have to practice until my fingers are strong enough.
I am doing something wrong and the fatigue happens much faster than it should.
It could become a Repetitive Strain Injury if I force myself too much, considering I already spend the whole day on a computer as a techie.

Is it a bad practice if I still try to learn piano by pressing the keys like that?
Comment: If your fingernails are longer that 2 or 3 mm, then to play like figure 1, they'll need cutting. That's a problem for classical guitarists, plucking hand, as they prefer them to be longer. You also need to consider your sitting height. Lowest part of elbow 2-3" above top of piano keys works for me.
Comment: Find a teacher or at least a pianist and have them help you with the basics of posture.
Comment: After playing a bit on my upright piano, I can safely say: my sound setting was way too low on the digital keyboard, so I was unconsciously trying to press stronger to compensate, when in fact it's difficult to play pianissimo on acoustic (if you don't press strong enough, then the hammer simply won't hit the strings at all). That, and it feels so comfortable to play with the nails cut.
Answer: Curved is good.  Flat is OK. Do you need the nails, perhaps for guitar playing?  Then you'll need to compromise, but otherwise trim them.  The fingers shouldn't collapse like in your drawing.
Arms shouldn't drop below keyboard level.  Is your stool at the right height?
Fatigue is fine.  Strain isn't fine.
It might help to think of drawing the sound out of the key rather than hitting it into it.
Consult a teacher.
Comment: "Flat" is not fine as it introduces tension in the back of the hand. Hand position should most closely resemble the natural curves shape of a relaxed hand.
Comment: Really.  Consult a teacher.   Even if it's only for one consultation lesson.
Comment: It would be a lot better than nothing!
Comment: Maybe I unconsciously lean forward (because of back fatigue), or the bench is indeed too low (or my arm is too long in which case I should also increase the height of the bench). Come to think of it, I never paid attention to whether my forearm is naturally at the same height or if I lift it into "floating" at the same height.
Comment: This might sound stupid but... I guess remote consulting wouldn't cut it (considering the current sanitary situation)?
Answer: Short answer: that hand position could definitely be bad, and you should work towards a hand position that's both healthier and allows you to play more easily (less fatigue and more agility).
Definitely cut your nails if you don't need them to be that long. That way you'll be able to feel the keys when your hand is in a more curved position! And none of that slippery clacking, haha. Personally I keep my nails cut really short so there's barely any white, but it depends on what you're comfortable with.
Early on my teacher told me to imagine I was holding a ball in my palm, and to use that shape, but that's little exaggerated. It should be a more natural curve like Laurence said. You could also imagine pressing down the keys as sinking your fingers into a pillow. Speaking from experience of having to improve bad technique, you really have to have a lot of discipline because it won't be easy at first (path of least resistance and all that). That's another thing that a teacher can help with.
Finger strength will probably come naturally as you play.
Final tip: shake out your hands and arms if they feel too tense or even clenched, you want to reduce tension to expand mobility.


Path connected sets (How to intutively find which set is path connected before attempting a formal proof )

Question: I have been preparing for an objective masters exam and  general topology is in the syllabus. The instructor in undergrad course was not interested in teaching and so I self studied and managed to do average level understanding of topology.
Problem arises in path connected set . Proving a set  path connected by definition is not easy and questions are often asked in exam whether a set is path connected or not? But rigorious proof is not asked as I have to just mark the correct options. So, I am asking for if there is some intution .  Consider that  I am given a set and  I have to see whether it's path connected or not , then I can use that intutive method which is less rigorious and time saving also.
If yes , can you tell me by using it on this question : Let A be the following subset of $\mathbb{R}^2$ : A={$(x,y)$:${(x+1)}^2+y^2 \leq  1$} $\bigcup $ {$(x,y): y = x sin(1/x), x>0$}. (This was 1 of the question asked in that exam).
I will apply your method/explanation/intution to other asked question for practice.
I shall be really thankful for any help received!
Comment: I will recommend doing tons of examples and then you will grow that intuition. It is hard to explain precisely what that intuition really is! If you have a visual way of thinking your job will be easier.
Answer: The crucial step is to get a clear idea of the set in question. In your example it can easily be sketched and seen to consist of a unit disk centred at $\langle-1,0\rangle$ together with what we might call a shrinking topologist's sine curve. After that it really depends entirely on the set in question; I can't think of any general principles that are genuinely helpful. In this case, however, it's not hard.
The origin stands out, because it's the one point where the disk and the curve meet. If the disk and the curve are both path connected, the whole set should be: for any $p$ and $q$ in the set we should be able to get from $p$ to $q$ by concatenating a path from $p$ to the origin with one from the origin to $q$. (This is inefficient if $p$ and $q$ are on the same side of the origin, but it still works.)
It's intuitively clear that there is a path from any point of the disk to the origin, since the line segment between the two points lies entirely within the disk. (It wouldn't even be hard to write the equation of such a path.) And the shrinking sine curve itself provides a path from any point on the right to the origin, so the whole set is indeed path connected.
Comment: @Tim: Just use the straight line path between the point and the origin.
Comment: @CSquared: There is no problem. The origin is in the set $A$, so $A$ contains the graph of the continuous extension of the shrinking sine curve, and the obvious path from any point on the graph to the origin works.
Comment: I am unable to follow why there is a path from any point of the disk to origin?
Comment: aren't the sets that make up $A$ disjoint sets? since $-2\leq x\leq 0$ for the disk and $x>0$ for the shrinking sine curve. unless i am missing something with limit as $x\to 0$ for $f(x)=x\sin(x)$. it goes to $0$, but it is not defined there, so i just don't see how you can have a path from the right side of the plane to the origin on the sine curve
Comment: @CSquared: the shrinking sine can be continuously extended to $0$, and the corresponding point on the graph is the origin. The question isn't "does there exist a path in the sine curve connecting a point in the curve to the origin?", but rather "does there exist a path in $A$ connecting a point in the curve to the origin". Such a path exists: it's the continuous extension of $(0,T]\to\mathbb R^2,~t\mapsto (t,t\sin(1/t))$.
Comment: @Vercassivelaunos I agree with you, but the continuous extension  of such a path isn't defined in the definition of the sets right now. We would need $y=x\sin(1/x)$ if $x>0$ and $y=0$ if $x=0$ for that to work out, right? so that $\lim\limits_{x\to 0}y(x)=y(0)=0$, or am i still missing the point?
Answer: Here's a very vague intuition for it: Being connected means that you can't pull apart the space into several pieces. Being path-connected means that you can actually travel from any one point to any other.
You can see this quite easily with the topologist's sine curve; the two path-connected components can't be pulled apart without changing the topology, but there's no way to move continuously from one to the other. Similarly, with the one-point compactification of the long line, the point at the end can't be pulled away, but it's "too far away" to actually reach from anywhere else on the long line.
It's worth mentioning that manifolds are connected if and only if they are path connected. So any distinguishing example is going to be somewhat not intuitive.
Answer: Let $E = \bigg\{ (x,y)\bigg|y=x\sin\ \frac{1}{x},\ 0<x\leq 1\bigg\}$. We have a claim that $E'=\{(0,0) \} \bigcup E$ is path-connected,
i.e. we must construct a continuous map $c : [0,1] \rightarrow
(\mathbb{R}^2,|\ |)$ where $|\ |$ is Euclidean distance s.t.
$$c(0)=(0,0),\ c(1) =(1,\sin\ 1)$$ and $c([0,1])$ is in $ E'$.
Define $c_n : [0,1]
 \rightarrow
(\mathbb{R}^2,|\ |)$ s.t. $c_n(t)=(t,t\sin\ \frac{1}{t}),\
\frac{1}{n}\leq t$, $$ c_n(s) =  \frac{s}{\frac{1}{2n}}
\bigg(\frac{1}{n},0\bigg) ,\ 0\leq s\leq \frac{1}{2n} $$ and $$ c_n(s) =
\frac{ \frac{1}{n}  -s }{\frac{1}{2n} }  \bigg(\frac{1}{n},0\bigg)
 + \frac{s- \frac{1}{2n}}{\frac{1}{2n}} \bigg(\frac{1}{n},\frac{1}{n}\sin\ n\bigg),\ \frac{1}{2n}<s<\frac{1}{n}
$$
Define $c(0)=(0,0),\ c(t)=(t,t\sin\ \frac{1}{t})$ so that
$|c_n(t)-c(t)| \leq  \frac{2\sqrt{2}}{n}
 $ for all $t$.
Hence $c$ is a uniform limit of continuous curves
$c_n$. That is $c$ is continuous.


How to show "incoming search terms"

Question: a lot of blogs have a feature to show the "incoming search terms" - it's great for SEO.
I looked up and down drupal.org but couldn't find a module.
Any recommendations on how to tackle this (I'm new to D7 and haven't built a module yet).
Answer: It looks like the Google Analytics Reports module is very close to what you need, except it's currently only for Drupal 6. There is an issue open about porting it to Drupal 7, but it doesn't look very active.

How to show "incoming search terms"


Select usando um array?

Question: Eu tenho o seguinte array:
var arr = ['A', 'B', 'C'...];

E no meu banco de dados eu tenho a coluna categoria onde os valores são salvos no seguinte modo: 'A,B,C...', como eu poderia fazer um SELECT pegando cada categoria do arr e encontrando os correspondentes valores do meu banco? Como são tantas categorias, eu gostaria de evitar o uso de um loop no arr.
Eu tentei algo tipo:
var categorias = ["A", "B", "C", "D", "E"];
var sql = "SELECT id_item, titulo, resumo, tipo FROM series WHERE categoria IN ('"+categorias.join()+"')";

Porém não funciona como em PHP.
Comment: O correto é `('"+categorias.join()+"')`
Comment: Corrigi o código, esqueci de escrever as aspas
Comment: Se os valores são textos, então cada um dentro do `IN` deve vir dentro de aspas, sendo que no caso iria ficar `IN ('A','B','C','D','E')`. Para tal pode usar `map` ou várias outras funções.
Comment: @Isac poderia me fazer um exemplo de como seria?
Answer: Uma vez que os valores que está a usar para o IN são textos (varchar) eles tem de vir dentro de aspas, cada um individualmente, que não é o que acontece no momento para a sua variável sql.
Veja por si mesmo:

var categorias = ["A", "B", "C", "D", "E"];
var sql = "SELECT id_item, titulo, resumo, tipo FROM series WHERE categoria IN ('"+categorias.join()+"')";

console.log(sql);

Quando eles deveriam ficar assim: ('A','B','C','D','E')
Para fazer esta transformação pode utilizar o método map por exemplo, para colocar as aspas, antes de fazer o join com:
categorias.map(cat => `'${cat}'`).join(",")

Veja o exemplo a funcionar:

var categorias = ["A", "B", "C", "D", "E"];
var sql = "SELECT id_item, titulo, resumo, tipo FROM series WHERE categoria IN ("+categorias.map(cat => `'${cat}'`).join(",")+")";

console.log(sql);

Note que tive que tirar a aspa inicial e final que tinha colocado manualmente dentro do IN. Aproveitei e coloquei o caratere do join para tornar mais claro que está a fazer join por ,.

Select usando um array?


How to use sed or awk for editing really long Java class

Question: I am implementing a Decorator pattern for the class which has a lot of methods. I created this Decorator class and just put all the methods that should be here.
Now I have a class with 2000 lines where every part like:
@Override
public String getCapadCode()
{
    return null;
}

should be replaced with:
@Override
public String getCapadCode()
{
    return origin.getCapadCode();
}

Is it possible to somehow automate this process with sed or awk?
Comment: Have you consider other options like lombok? https://projectlombok.org/features/Delegate.html
Comment: search replace in your IDE, with some regexp
Comment: Why do you have a class with 400 methods anyway? That's a bit of a red flag in and of itself.
Comment: I really don't think it can be easily done, maybe write some script (in perl for instance) instead, anyway are you sure it's a good idea? Have you ever heard about SOLID and the Single Responsibility Principle?
Comment: @all I intentionally put this question to `sed` category instead of `java`, because the design is approved here and hasn't been changed in 8 years and probably will never be changed. I know that this code has code smells, but still, the question is how to edit such a big file
Comment: I think this would be far easier in something like awk (or perl). `$1 == "public" {clname = $3} ...etc...`
Comment: This code doesn't have *smells*, it *stinks to high heaven*.
Answer: Here's a bit of perl:
perl -pe '
    m{public .* (.+)\(} and $methodName = $1;
    s{(?<=return )null;}{origin.$methodName();};
' File.java

If you are satisfied it works, call it with perl -i -pe to write-in-place.
Comment: Using perl for this. That's wild :)
Answer: you can use search and replace with regular expression like this:
search:
get(.*)\(\)\R\{\R    return null;\R\}
replace:
get$1\(\)\R\{\R    return origin\.$1;\R\}
I use Eclipse Find/Replace for that.
Answer: Use at your own risk:
$ awk '/^public/{name=$3} /return/{sub(/null/,"origin."name)} 1' file
@Override
public String getCapadCode()
{
    return origin.getCapadCode();
}

Comment: This is the result of the run return origin.GcrRecordWithRoundedAmounts
Comment: I don't know what that means but are you saying the script doesn't do what you want? When you run the script I posted on the sample input you provided it produces the output you said you wanted as you can see in my answer. If there's some other format of input that you haven't included in your example then of course you should not expect the script to know what you want to do with that format. If you want a completely robust solution that will work for any input then you need a parser for whatever language you input files are written in.


How can I build a render array that results in a string rather than a Drupal\Core\Render\Markup object?

Question: I'd like to use Twig Tweak's drupal_view() to render a view in my paragraph template. I have a couple entity reference fields on the paragraph and need the IDs of the referenced entities passed as contextual filter arguments.
I built a Contextual Filter String field formatter to format the contextual filter string with the hope that it could be passed directly as the argument's value. The formatter will return all if the reference field is empty, otherwise it will return the referenced entity IDs as a string with AND/OR separators, e.g. 1,2,3 for AND or 1+2+3 for OR.
Inside my template, I'm attempting to render the view with the following twig:
{% set arg1 = content.field_arg1|render %}
{% set arg2 = content.field_arg2|render %}

{{ drupal_view('my_view', 'my_display', arg1, arg2) }}

But this does not work!
Rather than strings, my arg variables are actually Drupal\Core\Render\Markup objects so the arguments are not passed correctly to the view.
After researching, I've found that I can workaround this issue by filtering my arg variables with a php filter that returns a string. For example, using the trim filter works:
{% set arg1 = content.field_arg1|render|trim %}
{% set arg2 = content.field_arg2|render|trim %}

{{ drupal_view('my_view', 'my_display', arg1, arg2) }}

If possible, I would like to build a render array that doesn't require any fancy footwork in the template to pass the values to the drupal_view() function. I.e. a render array where I can pass content.field_arg1 or content.field_arg|render directly as the arguments. Is this possible?
Render arrays I've tried that did not work:
$inline_template = [
  '#type' => 'inline_template',
  '#template' => '{{ contextual_filter_string }}', // also tried with |trim filter here
  '#context' => [
    'contextual_filter_string' => '1+2+3',
  ],
];

$markup = [
  '#markup' => '1+2+3',
];

$plain_text = [
  '#plain_text' => '1+2+3',
];

Note: not shown in the above render arrays is cache metadata (tags) for the entities referenced in the field.
Yes, there are alternate ways to get these field values and pass them to drupal_view(), however that's not what this question is about. I would like to use a Field Formatter to return a render array (I think I have to return a render array) that results in a string ready to be passed directly to drupal_view(). This allows me to configure the format of the argument in the UI without touching code. I suspect this is impossible.
Some alternative approaches that I've considered:

I could preprocess my paragraph and add these filter strings to the
$variables array.
I could build my own twig function to generate these contextual filter strings.
I could get the values directly from the entity in my template, e.g. paragraph.field_arg1.target_id as Les Lim answered, but this doesn't work cleanly for multi-value fields.

Edit: It seems that this is impossible so accepting Les Lim's answer as the best alternative.
Comment: For PHP see https://drupal.stackexchange.com/questions/207699/how-to-get-an-array-of-referenced-entity-ids-from-an-entity-reference-field. If you use the current Drupal Twig version 2.14 this is also possible in Twig. See https://twig.symfony.com/doc/2.x/filters/column.html
Comment: I edited my answer, and then refreshed to see your addendum to the question at the bottom. I'm not sure I have a direct answer for you; I think what you're discovering is that the field formatter system wasn't designed to be used in the way that you're trying to use it. It assumes that it should be returning filtered/escaped HTML markup, not raw unescaped strings that you'd want to use as a View argument.
Comment: @LesLim - Yes, thank you, that's my impression too. I really wanted the formatter to work cleanly because it would make it so easy to configure and reuse without much PHP or Twig knowledge. Your edits are helpful, even though it ultimately does not answer my question.
Comment: @4k4 Thanks for the tip about Twig's column filter! I edited my answer again.
Answer: Original response, assuming you only need a single value from each field:
Instead of using the rendered field output that you get with items in the {{ content }} array, you should probably use raw values directly from the entity. Raw values are much more likely to be what your Views arguments are looking for in the first place.
In Drupal 8/9, if the raw entity is available to the Twig template (and it is for Paragraph templates), you can use Entity API notation to get exact raw values from your entity:
{% set arg1 = paragraph.field_arg1.target_id %}
{% set arg2 = paragraph.field_arg2.target_id %}

Addendum, for needing multiple raw field values joined together
After re-reading the question, I realize you need all the raw values from a field joined together with a string. The contrib module Twig Field Value gives you handy generic tools for exactly this purpose. In this case, you would use its field_raw filter:
{% set arg1 = content.field_arg1|field_raw('target_id')|safe_join('+') %}
{% set arg2 = content.field_arg2|field_raw('target_id')|safe_join(',') %}

Edit: Join multiple raw field values without Twig Field Value (thanks 4k4 for the tip)
You don't actually need Twig Field Value to get the target_id values from a multiple-value field - you can extract multiple values from a raw entity field using Twig's built-in column filter.
{% set arg1 = paragraph.field_arg1|column('target_id')|safe_join('+') %}
{% set arg2 = paragraph.field_arg2|column('target_id')|safe_join(',') %}

Comment: Throw a `|default('all')` at the end and you can even get `all` as a value if the field is empty.


How can I search for the options for a particular property of a plotly figure?

Question: The question
In the figure below, the jagged shape of the line is set using 'hvh' as an argument for the shape property of the line. As a specific example for a more general case, let's say that I've forgotten which porperty (or properites) that take 'hvh' as an argument. How can I search through the entire plotly figure to find it?
Plot:

Code:
#imports
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot

import numpy as np
import pandas as pd
# Notebook settings
init_notebook_mode(connected=True)

# Some sample data
x = np.random.normal(50, 5, 500)
binned = np.histogram(x, bins=25, density=True)
plot_y = np.cumsum(binned[0])

# Line
trace1 = go.Scatter(
    x=binned[1],
    y=plot_y,
    mode='lines',
    name="X",
    hoverinfo='all',
    line=dict(color = 'rgb(1255, 0, 0)', shape='hvh'
    )
)

data = [trace1]

# Layout
layout = dict(title = 'Where is hvh?',
    legend=dict(
        y=0.5,
        traceorder='reversed',
        font=dict(
            size=16
        )
    )
)

# Make figure
fig = dict(data=data, layout=layout)

# Plot
iplot(fig, filename='line-shapes')

The details:
The shape is obtained using line=dict(color = 'rgb(1255, 0, 0)', shape='hvh'. And if you simply run fig, it will return a dict where you can see where the argument is applied to the figure:
{'data': [Scatter({
      'hoverinfo': 'all',
      'line': {'color': 'rgb(1255, 0, 0)', 'shape': 'hvh'},
      'mode': 'lines',
      'name': 'X',
      'x': array([35.36954648,
[...]

Let's say that I'd like to know what other propoerties of a an iplot figure that can take 'hvh' or any other string as an argument, how can I search for that? I happen to know that 'hvh' shows up in the output from help(trace1['line'])
shape
 |      Determines the line shape. With "spline" the lines are drawn
 |      using spline interpolation. The other available values
 |      correspond to step-wise line shapes.
 |
 |      The 'shape' property is an enumeration that may be specified as:
 |        - One of the following enumeration values:
 |              ['linear', 'spline', 'hv', 'vh', 'hvh', 'vhv']

But if 'hvh' were to occure for several shapes, It would be extremely hard to look through the output from help() for every possible property. If I was looking for 'shape' itself, I could just run a search on plot.ly/python/reference/ and get:

But that is not the case for 'hvh' or hvh:

Thank you for any suggestions!
Answer: You can always use your in-browser ctl-F to search within the page at https://plot.ly/python/reference/ if the search box isn't giving you what you need.
That said, I've just updated our search index to include the list of accepted values in enumerated attributes, so as of 2 minutes ago, searching for "hvh" gives: