text:
Q: Can someone help me find the bug in my IBM speech to text code/ I am using websockets to send request to IBM's speech to text api, and I am getting a constant pipe break error. The documentation for IBM speech to text api says it can take up 4mb in frames, but I can only give it seventy kb without it breaking. https://www.ibm.com/watson/developercloud/doc/speech-to-text/websockets.html#WSopen
Also, if I give a file under 70kb (5 secs), it works at the cost of not return me anything.
    import websocket
    from requests import get
    import user_info
    import json
    import time
    import threading

    api_token = "https://stream.watsonplatform.net/authorization/api/v1/token"
    s2t_url = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize"
    s2t_model = 'es-ES_BroadbandModel'
    mb_chunk = 1024*50
    # https://pypi.python.org/pypi/websocket-clien*
    # https://www.ibm.com/watson/developercloud/doc/speech-to-text/websockets.html

    # -------
    # on_open
    # -------
    def on_open(ws):
        """
        Called by the websocet after it is
        opened and sends metadataabout the sound file
        """
        print("--------------WebSocket is open--------------")
        message = {
            'action': 'start',
            'content-type': 'audio/wav'
        }
        #def send_binary(*args):
        ws.send(json.dumps(message))
        i = 0
        with open("Deepak2_hwv4122_uncompressed.wav", "rb") as wav:
            # while True:
            piece = wav.read(mb_chunk)
            ws.send(piece)
            print(i)
            i+=1
            if not piece:
                #break
                pass
            wav.close()
            # ws.close()
        #t = threading.Thread(target=send_binary)
        #t.start()

# ----------
# on_message
# ----------
def on_message(ws, message):
    print("------------------MESSAGE------------------")
    print(message)

# --------
# on_error
# --------
def on_error(ws, error):
    print(error)
    print("------------------ERROR------------------")
# --------
# on_close
# --------
def on_close(ws):
    print("------------Connection is Closed-----------")
    ws.close()

# ----------------
# get_token
# ----------------
def get_token():
    """
    REST request to get the watson voice service API token
    """
    url = api_token + "?url=" + user_info.AUTH['url']
    print("URL: " + url)
    res = get(url, auth=(user_info.AUTH['username'], user_info.AUTH['password']))
    print('Auth Token: ' + res.text)
    return res.text

# ----
# main
# ----
if __name__ == "__main__":
    global ws_url
    cur_token = get_token()
    ws_url = s2t_url + '?watson-token=' + cur_token + '&model=' + s2t_model
    print("ws_uri: " + ws_url)

    # Start WebSocket Connection
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(ws_url, on_message=on_message, on_error=on_error, on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()

The error I am getting is  [Errno 32] Broken pipe   File
  "/home/dell/rahmi/env/lib/python3.5/site-packages/websocket/_app.py",
  line 268, in _callback
      callback(self, *args)   File "watson-test.py", line 35, in on_open
      ws.send(piece)   File "/home/dell/rahmi/env/lib/python3.5/site-packages/websocket/_app.py",
  line 117, in send
      if not self.sock or self.sock.send(data, opcode) == 0:   File "/home/dell/rahmi/env/lib/python3.5/site-packages/websocket/_core.py",
  line 234, in send
      return self.send_frame(frame)   File "/home/dell/rahmi/env/lib/python3.5/site-packages/websocket/_core.py",
  line 259, in send_frame
      l = self._send(data)   File "/home/dell/rahmi/env/lib/python3.5/site-packages/websocket/_core.py",
  line 423, in _send
      return send(self.sock, data)   File "/home/dell/rahmi/env/lib/python3.5/site-packages/websocket/_socket.py",
  line 116, in send
      return sock.send(data)   File "/usr/lib/python3.5/ssl.py", line 861, in send
      return self._sslobj.write(data)   File "/usr/lib/python3.5/ssl.py", line 586, in write
      return self._sslobj.write(data)

A: I took a quick look at your code and saw that there is a missing part, you are not signalling the end of the audio stream after pushing all the audio in the on_open method. You can signal the end of audio by sending an empty binary message or a text message with the string {'action': 'stop'}, as described here: https://www.ibm.com/watson/developercloud/doc/speech-to-text/websockets.html I believe that is why you do not get any result. Also please make sure you do not close the websocket until the server replies with the final result.
Thank you for the answer Sayuri Mizuguchi, I actually wrote the code hosted in https://github.com/watson-developer-cloud/speech-to-text-websockets-python , which is a simple example of interacting with Watson STT via websockets. That project is being integrated into the Watson Python SDK here: https://github.com/watson-developer-cloud/python-sdk
Regarding conversion to base64, you just need to make sure that the audio is sent as a binary message, websocket stacks usually come with the ability to send either a text message or a binary message.

A: I have the same problem when I use websockets too. I really recommend this project for what you're trying. Check here.
Did you convert base x64 before sending the audio file?
ws.send(sound, { binary: true, mask: true});

Try did the following steps within this project from IBM Developer's
Check:
class WSInterfaceFactory(WebSocketClientFactory):

    def __init__(self, queue, summary, dirOutput, contentType, model,
                 url=None, headers=None, debug=None):

        WebSocketClientFactory.__init__(self, url=url, headers=headers)
        self.queue = queue
        self.summary = summary
        self.dirOutput = dirOutput
        self.contentType = contentType
        self.model = model
        self.queueProto = Queue.Queue()

        self.openHandshakeTimeout = 10
        self.closeHandshakeTimeout = 10

        # start the thread that takes care of ending the reactor so
        # the script can finish automatically (without ctrl+c)
        endingThread = threading.Thread(target=self.endReactor, args=())
        endingThread.daemon = True
        endingThread.start()


text:
Q: How to make live chat like facebook in my web application? I want to build web applications with simple chat like facebook have, but If I wanna make a chat self service what will I have to accomplish that?
I just newbie and don't know the architecture of chat applications. The purpose is just I can to record the history of chat to my database..
If the resource is high, Can you suggest the free service online chat that I can integrate in my applications??
Any help regards..

A: Phponlinechat is a free chat support service. It is offering a online live chat as a service and as a software.You can download free live chat tool from here.

A: you can using AJAX or Socket...
but i recommend you using Socket, because Socket is lighter than AJAX in your browser...
this socket example http://socket.io/demos/chat/

A: If you want chat recording and a system that is very easy to integrate, you can look at www.focalscope.com. It is a help desk system, but it has a chat module and best of all, it's free for startups (no feature limitations). I've been using it for my online business and the web chat was configured by me in 5 mins.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OOP for parsing equations in java i have that code for parsing 1st and 2nd degree polynomial equations and I need help to make them at the same class and OOP.
this code for 1st:
 public class DegreeEquation {

  public static String coeff(String str, String regex) {
    Pattern patt = Pattern.compile(regex);
    Matcher match = patt.matcher(str);
    // missing coefficient default
    String coeff = "+0";
    if(match.find())
        coeff = match.group(1);
    // always have sign, handle implicit 1
    return (coeff.length() == 1) ? coeff + "1"
        : coeff;
}

public static String[] quadParse(String arg) {
    String str = ("+" + arg).replaceAll("\\s", "");
    String a = coeff(str, "([+-][0-9]*)x(?!\\^)");
    String b = coeff(str, "([+-][0-9]+)(?!x)" );

    double a1 = Double.parseDouble(a);
    double b1 = Double.parseDouble(b);
    double X = -b1/a1;
    String root1 = Double.toString(X);
    return new String[]{root1};
    }

public static void main(String[] args) throws IOException {
    BufferedReader r = new BufferedReader (new InputStreamReader (System.in));
    String s;
    while ((s=r.readLine()) != null) {
    String[] pieces = quadParse(s);
    System.out.println(Arrays.toString(pieces));
 }
}

and this method for 2nd degree:
public static String[] quadParse(String arg) {
    String str = ("+" + arg).replaceAll("\\s", "");

    String a = coeff(str, "([+-][0-9]*)x\\^2" );
    String b = coeff(str, "([+-][0-9]*)x(?!\\^)");
    String c = coeff(str, "([+-][0-9]+)(?!x)" );
    double a1 = Double.parseDouble(a);
    double b1 = Double.parseDouble(b);
    double c1 = Double.parseDouble(c);

   double dis = (Math.pow(b1, 2.0)) - (4 * a1 * c1);
   double d = Math.sqrt(dis);
   double X = 0,Y = 0; //root 1 & root 2, respectively

   if (dis > 0.0 || dis < 0.0 ) {
       X = (-b1 + d)/(2.0 * a1 );
       Y = (-b1 - d)/(2.0 *a1);
       String root1 = Double.toString(X);
       String root2 = Double.toString(Y);
       return new String[]{root1,root2};
   }
   else if (dis == 0.0){
       X = (-b1 + 0.0)/(2.0 * a1);//repeated root
       String root2 = Double.toString(X);
      return new String[]{root2};
   }

I want the program to know when the equation 1st degree (doesn't have x2) to run its method and same for 2nd degree at the same class.
Feel free to write any code as an example. Any help would be greatly appreciated.

A: How about this: create interface Equation
interface Equation {
    double[] solve();
    void fromString(String arg);
}

and 2 implementations FirstDegreeEquation and SecondDegreeEquation.
class FirstDegreeEquation implements Equation { ... }
class SecondDegreeEquation implements Equation { ... }

Then write class Equations with static method to get desired implementation by input string
class Equations {
        static Equation fromString(String str) { ... }
}

So later you read string, call Equations.fromString and solve it with solve method.
Here is the example code, where you will need to implement toString methods and condition that will identify degree of equation.
class FirstDegreeEquation implements Equation {
    double a = 0;
    double b = 0;

    public static String coeff(String str, String regex) {
        Pattern patt = Pattern.compile(regex);
        Matcher match = patt.matcher(str);
        // missing coefficient default
        String coeff = "+0";
        if(match.find())
            coeff = match.group(1);
        // always have sign, handle implicit 1
        return (coeff.length() == 1) ? coeff + "1"
            : coeff;
    }

    public void fromString(String arg) {
        String str = ("+" + arg).replaceAll("\\s", "");
        String a = coeff(str, "([+-][0-9]*)x(?!\\^)");
        String b = coeff(str, "([+-][0-9]+)(?!x)" );

        this.a = Double.parseDouble(a);
        this.b = Double.parseDouble(b);
    }

    public double[] solve() {
        return new double[]{ -b / a };
    }

    public String toString() {
        /* convert to string */
        return "";
    }
}

class SecondDegreeEquation implements Equation {
    double a = 0;
    double b = 0;
    double c = 0;

    public static String coeff(String str, String regex) {
        Pattern patt = Pattern.compile(regex);
        Matcher match = patt.matcher(str);
        // missing coefficient default
        String coeff = "+0";
        if(match.find())
            coeff = match.group(1);
        // always have sign, handle implicit 1
        return (coeff.length() == 1) ? coeff + "1" : coeff;
    }

    public void fromString(String arg) {
        String str = ("+" + arg).replaceAll("\\s", "");
        String a = coeff(str, "([+-][0-9]*)x\\^2" );
        String b = coeff(str, "([+-][0-9]*)x(?!\\^)");
        String c = coeff(str, "([+-][0-9]+)(?!x)" );
        this.a = Double.parseDouble(a);
        this.b = Double.parseDouble(b);
        this.c = Double.parseDouble(c);
    }

    public double[] solve() {
        double dis = (Math.pow(b, 2.0)) - (4 * a * c);
        double d = Math.sqrt(dis);
        double x = 0, y = 0; //root 1 & root 2, respectively

        if (dis > 0.0 || dis < 0.0 ) {
            x = (-b + d)/(2.0 * a);
            y = (-b - d)/(2.0 * a);
            return new double[]{x, y};
        } else if (dis == 0.0){
            x = (-b + 0.0)/(2.0 * a);//repeated root;
            return new double[]{x};
        }
        return null;
    }

    public String toString() {
        /* convert to string */
        return "";
    }
}

class Equations {
    static Equation fromString(String str) {
        Equation e = null;
        /* try to find ^2 */
        if(/*  */) {
            e = new SecondDegreeEquation();
        } else {
            e = new FirstDegreeEquation();
        }
        e.fromString(str);
        return e;
    }
}

class EquationsExample {
    public static void main(String args[]) throws IOException {
        BufferedReader r = new BufferedReader (new InputStreamReader (System.in));
        String s;
        while((s=r.readLine()) != null) {
            Equation e = Equations.fromString(s);
            double[] solutions = e.solve();
            /* print solutions */
        }
    }
}


text:
Q: Linear system least-squares solution having a given number of sign changes Given a vector $x \in \mathbb{R}^{m}$, let $\theta(x)$ be the number of sign changes in the sequence:
$$x_{1},x_{2}...x_{m}$$
For example, vector $x = \left [1,3,-1,2,4 \right ]^{T}$ has $\theta(x)=2$.
Given a full column rank matrix $A \in \mathbb{R}^{m\times n}$ and a vector $b \in \mathbb{R}^{n}$, I seek for the least squares solution $x_{N}$ of the linear system $Ax=b$ on the set defined by $\theta(x)=N$.
Equivalently, for a given number $N$ of sign changes in $x$, which is the element $x_{N}$ that minimizes $\left \| Ax-b  \right \|$ ?
If $m$ and $n$ are small, a brute-force solution is feasible, by solving all combinations of the QP optimization $\min \left \| Ax-b  \right \|^{2}$ on $x_{1}\lessgtr0,x_{2}\lessgtr0,etc$ for a given $N$. However, when the system gets bigger (in my situation I have $m,n>100$) the number of cases grows with a binomial coefficient and the brute-force solution becomes computationally unfeasible.
Is there a more efficient way to solve this problem?
Thank you!


text:
Q: How to reduce the size of a MediaWiki 'text' table I administer a small MediaWiki wiki that has recently been subject to quite a lot of spam. I've deleted all of the spam accounts and pages and, thanks to the help provided at How to permanently delete a page from a MediaWiki wiki?, I've been able to clear out the 'archive' table in the wiki's database so that it's not full of all of the spam pages that I've deleted.
The database is still huge, though, relative to the actual size of the wiki. The 'text' table is running in at 2.7GB, and the 'searchindex' table is a sizeable 302.9MB. What's the best way to go about reducing the size of these tables, particularly the 'text' table? I'd be open to the idea of exporting all of the public-facing parts of the wiki and importing them into a clean install, if this is necessary.

A: Just run php maintenance/deleteArchivedRevisions.php --delete.

A: I solved this (practically, at least) by optimizing the offending table. This reduced its size to between 200 and 300 MB. This still seems large, considering the amount of data present in the wiki, but at least it's manageable.


text:
Q: Why do I get an Unbound value Error even though it works in the Terminal in Ocaml There has to be a minor error in my code because it works in the VSC-Terminal but not in the editor but I do not understand what it could be,
I get the Unbound value Error for the avg_grade and get_grades functions
Let studentlist be a list which safes student records. Each student has a (int*float) grades-list which safes a numeration as a int and the actual grades as floats.
My aim is to calculate the average grade of a single student with the function avg_grade.
I call the single student-record with the age with the get_student function.
type student = {
  name : string;
  age : int;
  grades : (int*float) list;
}

let studentlist =
  [ {name="alex"; age=7; grades=[(1,3.)]} ;
    {name="bianca"; age=6; grades=[(1, 2.); (2, 3.)]} ]

(* main-function to calculate the average *)
let avg_grade a lst =
  try
    grades_sum a lst /. length a lst
  with
    Not_found -> 0.0

(* function to add all the float-grades,
   it calls the list with get_grades *)
let grades_sum a lst =
  List.fold_left (fun i (_,b) -> i +. b) 0. (get_grades a lst)

(* calls the grades of a single record which is called per age *)
let get_grades a lst =
  (get_student a lst).grades

(*calls a single student-record*)
let get_student a lst =
  List.find (fun {age;_} -> a = age) lst

(* computes the length of the given grades-list *)
let length a lst =
  float_of_int (List.length (get_grades a lst))

A: You have this:
let avg_grade a lst = try grades_sum a lst /. length a lst with Not_found -> 0.0

But grades_sum isn't defined until after that line of code, so you get:
Error: Unbound value grades_sum

Additionally, a style suggestion. The |> operator may be useful for cleaning up some of your code. For better understanding of how it works:
let (|>) x f = f x

This allows something like f (g (h x)) to be written h x |> g |> f. Doing this lets us see that h x is being evaluated first. The result of that is sent to g, and then finally to f.
Both do the same thing, but the latter may be more expressive of what the code is doing.
You could use this to rewrite:
let length a lst =
  float_of_int (List.length (get_grades a lst))

As:
let length a lst =
  get_grades a lst |> List.length |> float_of_int


text:
Q: Write two dataframes to two different columns in CSV I converted two arrays into two dataframes and would like to write them to a CSV file in two separate columns. There are no common columns in the dataframes. I tried the solutions as follows and also from stack exchange but did not get the result. Solution 2 has no error but it prints all the data into one column. I am guessing that is a problem with how the arrays are converted to df? I basically want two column values of Frequency and PSD exported to csv. How do I do that ?
Solution 1:
df_BP_frq = pd.DataFrame(freq_BP[L_BP], columns=['Frequency'])
df_BP_psd = pd.DataFrame(PSDclean_BP[L_BP], columns=['PSD'])

df_BP_frq['tmp'] = 1
df_BP_psd['tmp'] = 1
df_500 = pd.merge(df_BP_frq, df_BP_psd, on=['tmp'], how='outer')
df_500 = df_500.drop('tmp', axis=1)

Error: Unable to allocate 2.00 TiB for an array with shape (274870566961,) and data type int64
Solution 2:
df_BP_frq = pd.DataFrame(freq_BP[L_BP], columns=['Frequency'])
df_BP_psd = pd.DataFrame(PSDclean_BP[L_BP], columns=['PSD'])

df_500 = df_BP_frq.merge(df_BP_psd, left_on='Frequency', right_on='PSD', how='outer')

No Error.
Result: The PSD values are all 0 and are seen below the frequency values in the lower rows.

Solution 3:
df_BP_frq = pd.DataFrame(freq_BP[L_BP], columns=['Frequency'])
df_BP_psd = pd.DataFrame(PSDclean_BP[L_BP], columns=['PSD'])

df_500 = pd.merge(df_BP_frq, df_BP_psd, on='tmp').ix[:, ('Frequency','PSD')]

Error: KeyError: 'tmp'
Exporting to csv using:
df_500.to_csv("PSDvalues500.csv", index = False, sep=',', na_rep = 'N/A', encoding = 'utf-8')

A: You can use directly store the array as columns of the dataframe. If the lengths of both arrays is same, the following method would work.
df_500 = pd.DataFrame()
df_500['Frequency'] = freq_BP[L_BP]
df_500['PSD'] = PSDclean_BP[L_BP]

If the lengths of the arrays are different, you can convert them to series and then add them as columns in the following way. This would make add nan for empty values in the dataframe.
df_500 = pd.DataFrame()
df_500['Frequency'] = pd.Series(freq_BP[L_BP])
df_500['PSD'] = pd.Series(PSDclean_BP[L_BP])

A: From your question what I understood is that you have two arrays you want to store them into one dataframe different columns and save that dataframe to csv with separate columns .
Creating two Numpy arrays of equal length .
import numpy as np
n1 = np.arange(2, 100, 0.01)
n2 = np.arange(3, 101, 0.01)

Creating an empty dataframe and storing the above arrays as columns of the dataframe
n = pd.DataFrame()
n['feq']= n1
n['psd'] = n2

Storing into Csv
n.to_csv(r"C\:...\dataframe.csv",index= False)

If they are unequal dataframes convert them as series and then store them in empty  dataframe .


text:
Q: matrix of all possible differences I need to compute the matrix of differences of a vector, just like here in section "Matrix of differences". Is that actually correct? I thought that, in order to add up (or subtract) two vector/matrices they had to have the same dimensions.

A: That's not a "real" matrix/vector difference. It's just a particular operation, a non-standard way to represent inside a matrix all the differences between the components of two vectors.
If you want to write it using correct/standard matrix operations, you could write
$A = u x^t - y u^t $
where $u^t = (1, 1, 1... )$ is an all-ones vector, and $x$, $y$, are your vectors, represented as column matrices.

A: It is correct as written, but it's a notational problem. Usually one uses a symbol to denote that we are interested in the matrix of differences, perhaps something like $(u,v)_{diff} = $ some matrix.
On the other hand, you are correct - when adding or subtracting matrices, they should be of the same dimension. I would say that his use of the simple minus sign is a slight abuse of notation here, but that happens from time to time.

A: You are not "really" taking the difference of two matrices, at least not in the sense of addition of matrices (which usually requires the two matrices to be the same size).
Instead, the "$-$" symbol here represents a different operation (alas for the confusion), in which you consider to $n$-tuples and construct a matrix whose entries are all possible differences. So the $-$ symbol you are seeing is not the symbol that represents subtraction of matrices in the usual sense.
If we use a different symbol, say $\ominus$, it might be clearer. We define $\ominus$ as an operation that takes an $n\times 1$ vector and a $1\times n$ vector, and whose result is an $n\times n$ matrix, as follows:
$$\left(\begin{array}{c}a_1\\ \ldots\\ a_n\end{array}\right)\ominus \left(b_1,\ldots,b_n\right) = \left(\begin{array}{cccc}
a_1-b_1 & a_1-b_2 & \cdots & a_1-b_n\\
a_2-b_1 & a_2-b_2 & \cdots & a_2-b_n\\
\vdots & \vdots & \ddots & \vdots\\
a_n-b_1 & a_n-b_2 & \cdots & a_n-b_n
\end{array}\right);$$
that is, the $ij$th entry of $\mathbf{v}\ominus \mathbf{w}$ is $v_i-w_j$.


text:
Q: Boostrap modal goes dark when clicked on Hyperlink I have a web page developed in Service Portal (ServiceNow Application) with  Angularjs 1.x and Bootstrap 3. The bootstrap modal contains some data and hyperlink to the full page(shown below). The expected behaviour is when user clicks on hyperlink it should take him to different page. But, browser takes him to different page and shows the information faded/dark window.
HTML Code:

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

 Potential Indicator

        <form name="indicatorModal" class="form-horizontal">

              Indicator #:

              Indicator Status:

                Indicator Type:

             Urgency Ranking:

             Completed Enrich Count:

              Enrich Start Timestamp:

               Enrich End Timestamp:

               Indicator Data :

                            <textarea class="form-control" rows="3" id="indicatorText" ng-readonly="true"> </textarea>

                     Click here for More information

        </form>

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

Angular JS Code:
(function()
{
    "use strict";
    var app=angular.module('indicatorModal',[]);
    app.controller('incidentSummaryCtrl',['$scope',function($scope)
    {
        $scope.passSysId=function(indicatorSysId,indicatorType)
        {
            var ipIndicatorsData = JSON.parse(sessionStorage.getItem('ipIndicatorsData'));
            var domainIndicatorsData = JSON.parse(sessionStorage.getItem('domainIndicatorsData'));
            var hashCodeIndicatorsData = JSON.parse(sessionStorage.getItem('hashCodeIndicatorsData'));
            if(indicatorType == 'IP Address')
                {
                    for(var indicator in ipIndicatorsData )
                        {
                            if(ipIndicatorsData[indicator].sysId == indicatorSysId)
                                {
                                    jQuery("#indicatorId").text(ipIndicatorsData[indicator].indicatorId);
                                    jQuery("#indicatorStatus").text(ipIndicatorsData[indicator].indicatorStatus);
                                    jQuery("#indicatorType").text(ipIndicatorsData[indicator].indicatorType);
                                    jQuery("#urgencyRanking").text(ipIndicatorsData[indicator].urgencyRanking);
                                    jQuery("#completedEnrichCount").text(ipIndicatorsData[indicator].completedEnrichCount);
                                    jQuery("#enrichStartTimestamp").text(ipIndicatorsData[indicator].enrichStartTimestamp);
                                    jQuery("#enrichEndTimestamp").text(ipIndicatorsData[indicator].enrichEndTimestamp);
                                    jQuery("#indicatorText").text(ipIndicatorsData[indicator].indicatorText);
                                    $("#indicatorLink").attr("href", "haloportal/?id=potential_indicator_summary&indicator_id="+indicatorSysId);
                                }
                        }
                }
            else if(indicatorType == 'Full Qualified Domain Name (FQDN)')
                {
                    for(var indicator in domainIndicatorsData )
                        {
                            if(domainIndicatorsData[indicator].sysId == indicatorSysId)
                                {
                                    jQuery("#indicatorId").text(domainIndicatorsData[indicator].indicatorId);
                                    jQuery("#indicatorStatus").text(domainIndicatorsData[indicator].indicatorStatus);
                                    jQuery("#indicatorType").text(domainIndicatorsData[indicator].indicatorType);
                                    jQuery("#urgencyRanking").text(domainIndicatorsData[indicator].urgencyRanking);
                                    jQuery("#completedEnrichCount").text(domainIndicatorsData[indicator].completedEnrichCount);
                                    jQuery("#enrichStartTimestamp").text(domainIndicatorsData[indicator].enrichStartTimestamp);
                                    jQuery("#enrichEndTimestamp").text(domainIndicatorsData[indicator].enrichEndTimestamp);
                                    jQuery("#indicatorText").text(domainIndicatorsData[indicator].indicatorText);
                                    $("#indicatorLink").attr("href", "/haloportal/?id=potential_indicator_summary&indicator_id="+indicatorSysId);
                                }
                        }
                }
            else if(indicatorType == 'Hash Code')
                {
                    for(var indicator in hashCodeIndicatorsData )
                        {
                            if(hashCodeIndicatorsData[indicator].sysId == indicatorSysId)
                                {
                                    jQuery("#indicatorId").text(hashCodeIndicatorsData[indicator].indicatorId);
                                    jQuery("#indicatorStatus").text(hashCodeIndicatorsData[indicator].indicatorStatus);
                                    jQuery("#indicatorType").text(hashCodeIndicatorsData[indicator].indicatorType);
                                    jQuery("#urgencyRanking").text(hashCodeIndicatorsData[indicator].urgencyRanking);
                                    jQuery("#completedEnrichCount").text(hashCodeIndicatorsData[indicator].completedEnrichCount);
                                    jQuery("#enrichStartTimestamp").text(hashCodeIndicatorsData[indicator].enrichStartTimestamp);
                                    jQuery("#enrichEndTimestamp").text(hashCodeIndicatorsData[indicator].enrichEndTimestamp);
                                    jQuery("#indicatorText").text(hashCodeIndicatorsData[indicator].indicatorText);
                                    $("#indicatorLink").attr("href", "haloportal/?id=potential_indicator_summary&indicator_id="+indicatorSysId);
                                }
                        }

                }

        };
    }]);

})();

A: This is because the modal backdrop is still present in the HTML even after the route change. You can remove the backdrop with the following in route change.
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();

Add this too if required $('div.modal-dialog').remove();
I'm not sure whether this is the correct way of solving this problem; but it works :)

A: $('body').removeClass('modal-open').end().$('.modal-backdrop').remove();


text:
Q: Java split sentence into a multi dimensional array I currently have a multidimensional array with 5 columns that gets its elements filled via a sentence from another array (names array) My problem is that everything is getting stored in the first column. For example,
word[][] = [25  Jackson 11,693   Nevaeh     6,345] [] [] [] []

However I want it to get stored like this
word[][] = [25][Jackson][11,693][Nevaeh][6,455]

.
        String [] names = topNames.toArray(new String[topNames.size()]);
        String[][] words = new String[names.length][5];

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

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

A: You mean something like this?
String[] names = new String[]{
        "25 Jackson 11,693 Nevaeh 6,345",
        "26 Jackson 44,444 Nevaeh 3,56"
};
String[][] words = new String[names.length][5];

for (int i = 0; i < names.length; i++) {
    words[i] = names[i].split("\\s+");
}

Arrays.stream(words).map(Arrays::toString).forEach(System.out::println);

And why not use Collections instead of arrays?
List<String> names = Arrays.asList(
        "25 Jackson 11,693 Nevaeh 6,345",
        "26 Jackson 44,444 Nevaeh 3,56"
);

List<List<String>> words = names.stream()
        .map(sentence -> sentence.split("\\s+"))
        .map(Arrays::asList)
        .collect(Collectors.toList());

words.forEach(System.out::println);


text:
Q: Show all RowNumber records for duplicates? I have a table of string resources :
;WITH cte AS
(
    SELECT 1 AS id , 'john' AS name, 10 AS age
    UNION
    SELECT 2 AS id , 'john' AS name, 10 AS age
    UNION
    SELECT 3 AS id , 'john' AS name, 12 AS age
    UNION
    SELECT 4 AS id , 'paul' AS name, 6 AS age
    UNION
    SELECT 5 AS id , 'paul ' AS name, 6 AS age
    UNION
    SELECT 6 AS id , 'paul different' AS name, 7 AS age
    UNION
    SELECT 7 AS id , 'ringo' AS name, 2 AS age

)

So the name "john" has age of 10.
Later on  , someone else (not me) also added "john" with age 10.
So I want to clean all duplicates.
But that's not the problem. Before I delete I want to see all duplicates.
So I did this :
SELECT *
FROM   (
           SELECT ID,
                  name,
                  age,
                  ROW_NUMBER() OVER(PARTITION BY name, age ORDER BY id) AS rn
           FROM   cte

       ) a  WHERE a.rn>1
ORDER BY
       name,
       age,
       a.rn

Result :

Which basically shows me duplicates. But I want to see also where rn=1 only if there's more version for the current value.
Question
In other words : How can I enhance my query so :

*

*Show all versions for a record ( all row numbers , rn) only if there are versions for this record

Desired result :
ID  name    age rn
1   john    10  1
2   john    10  2
4   paul    6   1
5   paul    6   2

Sql online  - demo
NB I  know i can do it with rescanning the table for the same name and age . bUt I thought if there's more elegant way of doing it.

A: Use exists operator to find the name which are duplicated. Try this.
;WITH cte AS
(
    SELECT 1 AS id , 'john' AS name, 10 AS age
    UNION
    SELECT 2 AS id , 'john' AS name, 10 AS age
    UNION
    SELECT 3 AS id , 'john' AS name, 12 AS age
    UNION
    SELECT 4 AS id , 'paul' AS name, 6 AS age
    UNION
    SELECT 5 AS id , 'paul ' AS name, 6 AS age
    UNION
    SELECT 6 AS id , 'paul different' AS name, 7 AS age
    UNION
    SELECT 7 AS id , 'ringo' AS name, 2 AS age

)
, cte1
         AS (SELECT ID,
                    name,
                    age,
                    Row_number() OVER(PARTITION BY name, age ORDER BY id) AS rn
             FROM   cte)
    SELECT *
    FROM   cte1 a
    WHERE  EXISTS (SELECT 1
                   FROM   cte1 b
                   WHERE  a.name = b.name and a.age=b.age
                          AND b.rn > 1)
    ORDER  BY name, age, a.rn

or use Inner Join
    SELECT a.id,a.name,a.age
    FROM   cte1 a
           JOIN cte1 b
             ON a.name = b.name
                AND a.age = b.age
                AND b.rn > 1
    ORDER  BY a.name, a.age, a.rn

Or To do it in single table scan use Dense_Rank plus window function
    ;WITH cte AS
    (
        SELECT 1 AS id , 'john' AS name, 10 AS age
        UNION
        SELECT 2 AS id , 'john' AS name, 10 AS age
        UNION
        SELECT 3 AS id , 'john' AS name, 12 AS age
        UNION
        SELECT 4 AS id , 'paul' AS name, 6 AS age
        UNION
        SELECT 5 AS id , 'paul ' AS name, 6 AS age
        UNION
        SELECT 6 AS id , 'paul different' AS name, 7 AS age
        UNION
        SELECT 7 AS id , 'ringo' AS name, 2 AS age

    )
    , cte1
             AS (SELECT ID,
                        name,
                        age,
                        count(age) over (partition by name,age) cnt,
                        dense_rank() OVER(PARTITION BY name ORDER BY age) AS rn
                 FROM   cte)
                 SELECT *
                 FROM   cte1
                 WHERE  rn = 1
                        AND cnt > 1


text:
Q: How to check whether the shift key is being held in C#? I was writing a method which should handle lower/uppercase letters by receiving virtualcodes (as you know the virtualcode always returns a code and can not render uppercase or lowercase letters by itself). If anyone is interested, I found a solution by using the Control.IsKeyLocked and Control.ModifierKeys classes:
bool isCapsLockOn = Control.IsKeyLocked(Keys.CapsLock);
bool isShiftOn = Control.ModifierKeys == Keys.Shift;

The first solution I was trying to implement was to handle the shift key using Control.IsKeyLocked(), not long after I found out that IsKeyLocked should be used ONLY for keys which can be actually locked like numlock, capslock, etc. The following code DID NOT WORK:
bool isLShiftOn = Control.IsKeyLocked(Keys.LShiftKey);
bool isRShiftOn = Control.IsKeyLocked(Keys.RShiftKey);

Okay I actually found the solution to my problem by handling whether the caps lock is on/off and whether the shift is actually pressed using Control.IsKeyLocked and Control.ModifierKeys combined with an if statement (to handle lowercase when caps lock is on/shift is pressed and upper case when caps lock is off/shift is pressed, etc and vice-versa). I am now curious why the above code DID NOT WORK and actually even the code below it did not execute. Why the compiler didn't throw an error?. I suppose that this throws the application somehow in a "waiting" state waiting for the shift key to be locked down which can not happen.


text:
Q: Regarding refs in react JS / Can I use a ref to set component's state? In the code below I'm unable to use this.setState({name: this.nameRef.current.value}). Can someone please tell why is this happening? Once I've something in ref's current value, why can't I use it to update the component's current state? Also, Is it a wrong practise? However it doesn't matter If it doesn't work.
class App extends React.Component {
  constructor(){
    console.log('constructor');
    super();
    this.state = {name : '', password: ''}
    this.nameRef = React.createRef()
    this.pwdRef = React.createRef()
  }

  handleLogin = (val) =>{
      val.preventDefault();
      this.setState({name: this.nameRef.current.value}) //Not working
      alert("Welcome"+this.nameRef.current.value);
      console.log(this.state.name); //Outputs empty string
  }
    render(){
      return(
        <React.Fragment>
          <form>

              Username:
              <input style={{width: '60%', display: 'inline'}} name="name" type="text" className={"form-control"} placeholder="Enter name" ref={this.nameRef}/>

              Password:
              <input style={{width: '60%', display: 'inline'}} type="text" name="pass" className={"form-control"} placeholder="Enter password" ref={this.pwdRef}/>

            <button type="submit" className={"btn btn-primary"} onClick={this.handleLogin}> Login </button>
          </form>
        </React.Fragment>
        )
    }
}

export default App;

Thanks in advance!

A: Not the best practice.  Add an onChange prop to your inputs, like:
onChangeName = e => this.setState({ name: e.target.value });

...

<input ...other things... onChange={this.onChangeName} value={this.state.name} />

This way, whenever a user types into an input, that automatically updates the state.  Refs should be used sparingly, as React usually has better ways to accomplish most things.

A: Before answering your question, what you should be doing is tracking each input's value to the corresponding state variable. You can do this with the onChange listener (you get the value via the event.target.value)
However, to address the question, what you are asking is if you can use refs to get the value from a component and use it. You can, and you should be seeing the value, what I think it's happening is that the input isn't updating 'value' (which you will when you control it with onChange and value={this.state.variableName}). After implementing the onChange and stuff try to log the input value using ref, see if it changes

A: Well, I don't know why can't I set the state when I click Submit but onChange() solved my issue. This works just fine :
class App extends React.Component {
  constructor(){
    console.log('constructor');
    super();
    this.state={name: '',password: ''}
    this.nameRef = React.createRef()
    this.pwdRef = React.createRef()
  }

  setStat1 = () =>{
    this.setState({name: this.nameRef.current.value})
  }

  setStat2 = () =>{
    this.setState({password: this.pwdRef.current.value})
  }

  handleLogin = (val) =>{
    console.log(this.state.name+" : "+this.state.password)
      val.preventDefault();
      alert("Welcome"+this.nameRef.current.value);
  }
    render(){
      return(
        <React.Fragment>
          <form>

              Username:
              <input style={{width: '60%', display: 'inline'}} name="name" type="text" className={"form-control"} onChange={this.setStat1} placeholder="Enter name" ref={this.nameRef}/>

              Password:
              <input style={{width: '60%', display: 'inline'}} type="text" name="pass" className={"form-control"} placeholder="Enter password" onChange={this.setStat2} ref={this.pwdRef}/>

            <button type="submit" className={"btn btn-primary"} onClick={this.handleLogin}> Login </button>
          </form>
        </React.Fragment>
        )
    }
}


text:
Q: FragmentStatePagerAdapter return wrong position but right fragment I have an Activity called MainActivity which has a ViewPager and a TabLayout. The ViewPager has 4 (four) fragments that bound there. I have a problem about (maybe) FragmentStatePagerAdapter
I have my code run
public class MainPagerAdapter extends FragmentStatePagerAdapter {

    Fragment[] fragments;

    public MainPagerAdapter(FragmentManager fm) {
        super(fm);
        fragments = new Fragment[]{
                new FragProfile(),
                new FragScore(),
                new FragMoney(),
                new FragOther()
        };
    }

    @Override
    public Fragment getItem(int p) {
        Log.w("Fragment", String.valueOf(p));

        switch (p){
            case 0:
                return fragments[0];
            case 1:
                return fragments[1];
            case 2:
                return fragments[2];
            case 3:
                return fragments[3];
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return 4;
    }
}

on first tab, i got this log came out
09-10 20:05:29.683 17034-17034/ampersanda.elsys W/Fragment: 0
09-10 20:05:29.684 17034-17034/ampersanda.elsys W/Fragment: 1

on second
09-10 20:11:03.970 17034-17034/ampersanda.elsys W/Fragment: 2

on third
09-10 20:11:54.534 17034-17034/ampersanda.elsys W/Fragment: 3

but on fourth i got nothing logged, and I back to the third i got this
09-10 20:14:07.373 17034-17034/ampersanda.elsys W/Fragment: 1

Back to second
09-10 20:14:50.241 17034-17034/ampersanda.elsys W/Fragment: 0

and I back to the first, i got nothing logged again
my code doesn't run well, but I got Fragment shows like its switch() but not about code inside it

A: In your case you should use FragmentPagerAdapter because when you use FragmentStatePagerAdapter the pages may get destroyed, so you will need to recreate them in getItem().

This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment.


text:
Q: Is it possible to replace android's browser default copy paste on text? I am wondering if I could replace android's browser default copy paste on text. In which, user can long touch the text and then the toolbar will display the button of copy or paste. What I wanted to do is, whenever user long touch the text, my app will popup the menu under the selected text and they will be a button of copy and paste.
If the user click on copy, it will save into text file or sqlite for future reference. So that, all copied item won't lost.

A: You need to write  OnLongClickListener for your element in which your text resides that you want to be copied/pasted.
Example:
myTextView.setOnLongClickListener(listener);

A: Yes totally possible.  On your edittext, just use
textview.setCustomSelectionActionModeCallback(callback)
where your callback will be a class the implements the

ActionMode.Callback
On each of the callback methods that return a boolean simply return false.  This will prevent the default android behaivor of showing a copy/paste actions bar on long click.  Proceed to implement a textview.setOnLongClickListener(listener). In your listener, put your custom code to implement your custom menu.  This can be a context menu, or whatever you desire.


text:
Q: How do I fix " ValueError: Argument Z must be 2-dimensional" error I'm trying to plot a 3D surface passes through a set of (X,Y,Z) 3D point and I got raise ValueError("Argument Z must be 2-dimensional.")
ax = Axes3D(fig)
X = df.index.values
Y = np.where(df['trans_count'].values>0,np.ma.log(df['trans_count'].values), 0)

X, Y = np.meshgrid(X, Y)

Z = np.where(df['gpu_trans_count'].values>0, np.log(df['gpu_trans_count'].values), 0)

print(X.shape) #(37,37)
print(Y.shape) #(37,37)
print(Z.shape) #(37,)

ax.plot_surface(X, Y, Z)

ValueError: Argument Z must be 2-dimensional

A: You can expand the dimensions of Z using np.expand_dims().
You have not specified which axis to expand.
Hence I have given code snippets for both. Just uncomment as your wish.
ax = Axes3D(fig)
X = df.index.values

Y = np.where(df['trans_count'].values>0,np.ma.log(df['trans_count'].values), 0)

X, Y = np.meshgrid(X, Y)

Z = np.where(df['gpu_trans_count'].values>0, np.log(df['gpu_trans_count'].values), 0)

#If you want to expand the x dimensions
#From (n,) to (1,n)
Z=np.expand_dims(Z,axis=0)
print(Z.shape) #(1,37)

# If you want to expand the y dim
# from (n,) to (n,1)
#Z=np.expand_dims(Z,axis=1)
#print(Z.shape) #(37,1)

print(X.shape) #(37,37)
print(Y.shape) #(37,37)

ax.plot_surface(X, Y, Z)


text:
Q: If I don't log in right away on my 14.04 LTS system, the login hangs My newly dual booting system is working great with this one annoyance scenario:

*

*I boot the system, but don't touch anything.

*The screen eventually goes dark.

*I touch a key and get the login screen.

*I enter my password and hit enter.

*The login screen disappears, but I never get the desktop.  It just hangs.

I am able to ssh in and reboot the system.  If I log in promptly then it's fine.
I'd settle for an answer telling me how to make the power saver never kick in and make the login screen go dark.  Or, a fix for the root cause.
More info:
It's stock Ubuntu 14.04 so I assume it's Unity. Graphics are "Gallium 0.4 on AMD CEDAR" according to System Settings/Details.
Logs will be posted next time it happens.
***Update - this hasn't happened since I posted the bounty.

A: I was also on the Same Boat when I had 14.04 Now I am on Velvet !
Here is the solution script that I has worked for me:
#!/bin/bash
echo
echo Install BleachBit
echo
apt-get install bleachbit -y
echo
echo Clean
echo
apt-get autoclean
apt-get clean
echo
echo Update & Upgrade
echo
apt-get update
apt-get upgrade
apt-get dist-upgrade
echo
echo
echo BleachBit Cleaning
echo
bleachbit -c adobe_reader.*
bleachbit -c apt.*
bleachbit -c chromium.*
bleachbit -c deepscan.*
bleachbit -c epiphany.*
bleachbit -c evolution.*
bleachbit -c filezilla.*
bleachbit -c firefox.*
bleachbit -c google_chrome.*
bleachbit -c kde.*
bleachbit -c java.*
bleachbit -c system.cache
bleachbit -c system.clipboard
bleachbit -c system.custom
bleachbit -c system.desktop_entry
bleachbit -c system.localizations
bleachbit -c system.memory
bleachbit -c system.recent_documents
bleachbit -c system.rotated_logs
bleachbit -c system.tmp
bleachbit -c system.trash
bleachbit -c opera.*
bleachbit -c thumbnails.*
bleachbit -c transmission.*
bleachbit -c x11.*
bleachbit -c vlc.*
bleachbit -c wine.*
echo
echo Clean Up
echo
apt-get clean
apt-get autoclean
echo
echo BleachBit ReBleach System
echo
bleachbit -c system.cache
bleachbit -c system.clipboard
bleachbit -c system.custom
bleachbit -c system.desktop_entry
bleachbit -c system.localizations
bleachbit -c system.memory
bleachbit -c system.recent_documents
bleachbit -c system.rotated_logs
bleachbit -c system.tmp
bleachbit -c system.trash
echo
echo Processes Complete
echo


text:
Q: Python If Else Loop My code is pretty much this:
Rate = input ("Enter Desired Rate of Charge: ") #User will be prompted to enter the charge rate of the system
if Rate < 0.5:
#If the charge rate entered is less than 0.5 kWhs
    print "Charge Rate Too Low: Please consider revision" #Tells the user the rate is too low
elif Rate > 2.0:
#Also, if the charge rate entered is greater than 2.0 kWhs...
    print "Charge Rate Too High: Please consider revision" #Tells the user the rate is too high
else:
#Otherwise, for any number entered between the bounds of 0.5 and 2.0 kWhs...
    print '\n' #Page break for new conditions.

I need it to reprompt the user if the integer entered is less than 0.5 or greater than 2, and when the user does that, then save that integer as Rate and move on. Thank you.

A: I think this is a bit cleaner than avasal's answer. This solution assumes that the user knows how to exit an application using CTRL+C though, otherwise you should add support for quitting the program when the user inputs Q or something.
rate = 0

while True:
    rate = input("Enter desired rate of charge: ")

    if not 0.5 < rate < 2:
        print "Rate must be between 0.5 and 2."
    else:
        break

A: Add a while loop till rate is less than 0.5 or rate is greater than 2.0
Rate = 0
while (Rate < 0.5) or (Rate > 2.0):
    Rate = input ("Enter Desired Rate of Charge: ") #User will be prompted to enter the charge rate of the system
    if Rate < 0.5:
    #If the charge rate entered is less than 0.5 kWhs
        print "Charge Rate Too Low: Please consider revision" #Tells the user the rate is too low
    elif Rate > 2.0:
    #Also, if the charge rate entered is greater than 2.0 kWhs...
        print "Charge Rate Too High: Please consider revision" #Tells the user the rate is too high
    else:
    #Otherwise, for any number entered between the bounds of 0.5 and 2.0 kWhs...
        print '\n' #Page break for new conditions.


text:
Q: How to find the exact name of the output node in .pb file? I was trying to freeze a pb file for using in the OpenVino. For freezing, i need to know the output node name. For that, i tried loading the pb file and reading the output names, but, it got an error. Then i tried to get the output name from the model summary and it was dense_7 (Dense).
I followed the command in https://docs.openvinotoolkit.org/latest/_docs_MO_DG_prepare_model_convert_model_Convert_Model_From_TensorFlow.html#freeze-the-tensorflow-model to freeze the model. But when i try the output node name as dense_7 (Dense), I'm getting the following error:

AssertionError: dense_7 (Dense) is not in graph

I'm attaching the model summary along with this.
Is there any way to read the correct output name?

A: *

*Question 26 in the 'Model Optimizer Frequently Asked Questions' page addresses the error that you are facing. See https://docs.openvinotoolkit.org/2020.3/_docs_MO_DG_prepare_model_Model_Optimizer_FAQ.html

*I would suggest you try the following potential methods that have been shared in Github, available at the following links:
https://github.com/tensorflow/tensorflow/issues/3986#issuecomment-304619868
https://github.com/tensorflow/tensorflow/issues/3986#issuecomment-368282326
https://github.com/tensorflow/tensorflow/issues/3986#issuecomment-470083664
https://github.com/tensorflow/tensorflow/issues/3986#issuecomment-508897579

*Do let us know if any of these works for you.


text:
Q: If date is between two dates, find value using shared reference I am new to R and having a hard time with something. I have a data frame containing, among other things, dates and the name of an advertising placement.
I have another table containing start date, end date, the name of the ad placement, and a rate.
I basically need to reference the rate key and apply a vlookup (left_join) to my data frame based on the date and placement name, considering the different rates that might occur for diff date ranges in my reference table.
So far I've been using dplyr pretty extensively to move things around, but this is the hardest thing I've come across so far. Initial thought is that I might need to make every possible date range it's own table and apply a left_join to the df, but I'm not sure.
Example:
Reference table
placement             start        end          rate
NewYorkTimes_iPhone   2018-06-01   2018-06-25   5
NewYorkTimes_iPhone   2018-06-26   2018-06-30   7

Desired Outcome
placement           date        rate
NewYorkTimes_iPhone 2018-06-15  5

Basically in the dataframe the rate column would be missing. I need it to search the reference table for the shared placement and see if the date is between the range in the key
Any help is appreciated! This is my first r project and I've learned everything online through DataCamp.
Thank you!!
Tyler

A: > ref_tbl <-
+     tibble(
+         placement = c("NewYorkTimes_iPhone","NewYorkTimes_iPhone"),
+         start = c("2018-06-01","2018-06-26"),
+         end = c("2018-06-25","2018-06-30"),
+         rate = c(5,7)
+     ) %>%
+     mutate_at(vars(start, end),as.Date)
> des_tbl <-
+     tibble(
+         placement = "NewYorkTimes_iPhone",
+         date = "2018-06-15",
+         rate = 5
+     ) %>%
+     mutate(date = as.Date(date))
> ref_tbl
# A tibble: 2 x 4
  placement           start      end         rate
  <chr>               <date>     <date>     <dbl>
1 NewYorkTimes_iPhone 2018-06-01 2018-06-25     5
2 NewYorkTimes_iPhone 2018-06-26 2018-06-30     7
> des_tbl
# A tibble: 1 x 3
  placement           date        rate
  <chr>               <date>     <dbl>
1 NewYorkTimes_iPhone 2018-06-15     5
>
> ref_tbl %>%
+     left_join(des_tbl, by = c("placement","rate")) %>%
+     mutate(
+         ifelse(date %within% interval(start,end),1,0)
+     )
# A tibble: 2 x 6
  placement           start      end         rate date       `ifelse(date %wit~
  <chr>               <date>     <date>     <dbl> <date>                  <dbl>
1 NewYorkTimes_iPhone 2018-06-01 2018-06-25     5 2018-06-15                  1
2 NewYorkTimes_iPhone 2018-06-26 2018-06-30     7 NA                         NA
>

Here is some comments.
For the left joined table, we need get the results where date is between start and end.
Here the function %within% and interval from lubridate package is a solution.


text:
Q: Using ImageMagick to efficiently stitch together a line scan image I'm looking for alternatives for line scan cameras to be used in sports timing, or rather in the part where placing needs to be figured out. I found that common industrial cameras can readily match the speed of commercial camera solutions at >1000 frames per second. For my needs, usually the timing accuracy is not important, but the relative placing of athletes. I figured I could use one of the cheapest Basler, IDS or any other area scan industrial cameras for this purpose. Of course there are line scan cameras that can do a lot more than a few thousand fps (or hz), but it is possible to get area scan cameras that can do the required 1000-3000fps for less than 500€.
My holy grail would of course be the near-real time image composition capabilities of FinishLynx (or any other line scan system), basically this part: https://youtu.be/7CWZvFcwSEk?t=23s
The whole process I was thinking for my alternative is:

*

*Use Basler Pylon Viewer (or other software) to record 2px wide images at the camera's fastest read speed. For the camera I am
  currently using it means it has to be turned on it's side and the
  height needs to be reduced, since it is the only way it will read
  1920x2px frames @ >250fps

*Make a program or batch script that then stitches these 1920x2px frames together to, for example one second of recording 1000*1920x2px
  frames, meaning a resulting image with a resolution of 1920x2000px
  (Horizontal x Vertical).

*Finally using the same program or another way, just rotate the image so it reflects how the camera is positioned, thus achieving an image
  with a resolution of 2000x1920px (again Horizontal x Vertical)

*Open the image in an analyzing program (currently ImageJ) to quickly analyze results

I am no programmer, but this is what I was able to put together just using batch scripts, with the help of stackoverflow of course.

*

*Currently recording a whole 10 seconds for example to disk as a raw/mjpeg(avi/mkv) stream can be done in real time.

*Recording individual frames as TIFF or BMP, or using FFMPEG to save them as PNG or JPG takes ~20-60 seconds The appending and rotation
  then takes a further ~45-60 seconds
  This all needs to be achieved in less than 60 seconds for 10 seconds of footage(1000-3000fps @ 10s = 10000-30000 frames) , thus why I need something faster.

I was able to figure out how to be pretty efficient with ImageMagick:
magick convert -limit file 16384 -limit memory 8GiB -interlace Plane -quality 85 -append +rotate 270 "%folder%\Basler*.Tiff" "%out%"

#%out% has a .jpg -filename that is dynamically made from folder name and number of frames.

This command works and gets me 10000 frames encoded in about 30 seconds on a i5-2520m (most of the processing seems to be using only one thread though, since it is working at 25% cpu usage). This is the resulting image: https://i.imgur.com/OD4RqL7.jpg (19686x1928px)
However since recording to TIFF frames using Basler's Pylon Viewer takes just that much longer than recording an MJPEG video stream, I would like to use the MJPEG (avi/mkv) file as a source for the appending. I noticed FFMPEG has "image2pipe" -command, which should be able to directly give images to ImageMagick. I was not able to get this working though:
   $ ffmpeg.exe -threads 4 -y -i "Basler acA1920-155uc (21644989)_20180930_043754312.avi" -f image2pipe - | convert - -interlace Plane -quality 85 -append +rotate 270 "%out%" >> log.txt
    ffmpeg version 3.4 Copyright (c) 2000-2017 the FFmpeg developers
      built with gcc 7.2.0 (GCC)
      configuration: –enable-gpl –enable-version3 –enable-sdl2 –enable-bzlib –enable-fontconfig –enable-gnutls –enable-iconv –enable-libass –enable-libbluray –enable-libfreetype –enable-libmp3lame –enable-libopenjpeg –enable-libopus –enable-libshine –enable-libsnappy –enable-libsoxr –enable-libtheora –enable-libtwolame –enable-libvpx –enable-libwavpack –enable-libwebp –enable-libx264 –enable-libx265 –enable-libxml2 –enable-libzimg –enable-lzma –enable-zlib –enable-gmp –enable-libvidstab –enable-libvorbis –enable-cuda –enable-cuvid –enable-d3d11va –enable-nvenc –enable-dxva2 –enable-avisynth –enable-libmfx
      libavutil      55. 78.100 / 55. 78.100
      libavcodec     57.107.100 / 57.107.100
      libavformat    57. 83.100 / 57. 83.100
      libavdevice    57. 10.100 / 57. 10.100
      libavfilter     6.107.100 /  6.107.100
      libswscale      4.  8.100 /  4.  8.100
      libswresample   2.  9.100 /  2.  9.100
      libpostproc    54.  7.100 / 54.  7.100
    Invalid Parameter - -interlace
    [mjpeg @ 000000000046b0a0] EOI missing, emulating
    Input #0, avi, from 'Basler acA1920-155uc (21644989)_20180930_043754312.avi':
      Duration: 00:00:50.02, start: 0.000000, bitrate: 1356 kb/s
        Stream #0:0: Video: mjpeg (MJPG / 0x47504A4D), yuvj422p(pc, bt470bg/unknown/unknown), 1920x2, 1318 kb/s, 200 fps, 200 tbr, 200 tbn, 200 tbc
    Stream mapping:
      Stream #0:0 -> #0:0 (mjpeg (native) -> mjpeg (native))
    Press [q] to stop, [?] for help
    Output #0, image2pipe, to 'pipe:':
      Metadata:
        encoder         : Lavf57.83.100
        Stream #0:0: Video: mjpeg, yuvj422p(pc), 1920x2, q=2-31, 200 kb/s, 200 fps, 200 tbn, 200 tbc
        Metadata:
          encoder         : Lavc57.107.100 mjpeg
        Side data:
          cpb: bitrate max/min/avg: 0/0/200000 buffer size: 0 vbv_delay: -1
    av_interleaved_write_frame(): Invalid argument
    Error writing trailer of pipe:: Invalid argument
    frame=    1 fps=0.0 q=1.6 Lsize=       0kB time=00:00:00.01 bitrate= 358.4kbits/s speed=0.625x
    video:0kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.000000%
    Conversion failed!

If I go a bit higher for the height, I no longer get the "[mjpeg @ 000000000046b0a0] EOI missing, emulating" -error. However the whole thing will only work with <2px high/wide footage.
edit: Oh yes, I can also use ffmpeg -i file.mpg -r 1/1 $filename%03d.bmp or ffmpeg -i file.mpg $filename%03d.bmp to extract all the frames from the MJPEG/RAW stream. However this is an extra step I do not want to take. (just deleting a folder of 30000 jpgs takes 2 minutes alone…)
Can someone think of a working solution for the piping method or a totally different alternative way of handling this?

A: I generated a sample video of 10,000 frames, and did some tests. Obviously, my machine is not the same specification as yours, so results are not directly comparable, but I found it is quicker to let ffmpeg transpose the video and the pipe it into ImageMagick as raw RGB24 frames.
I found that I can convert a 10 second movie into a 20,000x1920 pixel JPEG in 10.3s like this:
ffmpeg -threads 4 -y -i video.mov -frames 10000 -vf "transpose=1" -f image2pipe -vcodec rawvideo -pix_fmt rgb24 - | convert -depth 8 -size 2x1920 rgb:- +append result.jpg

The resulting image looks like this:

I generated the video like this with CImg. Basically it just draws a Red/Green/Blue splodge successively further across the frame till it hits the right edge, then starts again at the left edge:
#include <iostream>
#include "CImg.h"

using namespace std;
using namespace cimg_library;

int main()
{
   // Frame we will fill
   CImg<unsigned char> frame(1920,2,1,3);

   int width =frame.width();
   int height=frame.height();

   // Item to draw in frame - created with ImageMagick
   // convert xc:red xc:lime xc:blue +append -resize 256x2\! splodge.ppm
   CImg<unsigned char> splodge("splodge.ppm");

   int offs  =0;

   // We are going to output 10000 frames of RGB raw video
   for(int f=0;f<10000;f++){
      // Generate white image
      frame.fill(255);

      // Draw coloured splodge at correct place
      frame.draw_image(offs,0,splodge);
      offs = (offs + 1) % (width - splodge.width());

      // Output to ffmpeg to make video, in planar GBR format
      // i.e. run program like this
      // ./main | ffmpeg -y -f rawvideo -pixel_format gbrp -video_size 1920x2 -i - -c:v h264 -pix_fmt yuv420p video.mov
      char* s=reinterpret_cast<char*>(frame.data()+(width*height));   // Get start of G plane
      std::cout.write(s,width*height);                                // Output it
      s=reinterpret_cast<char*>(frame.data()+2*(width*height));       // Get start of B plane
      std::cout.write(s,width*height);                                // Output it
      s=reinterpret_cast<char*>(frame.data());                        // Get start of R plane
      std::cout.write(s,width*height);                                // Output it
   }
}

The splodge is 192x2 pixels and looks like this:

A: I had another go at this to see if I could speed up my other answer by doing things a couple of different ways - hence a different answer. I used the same synthetic videoclip that I generated in the other answer to test with.
Rather than pass the 2x1920 scanlines into ImageMagick for it to append together and write as a JPEG, I did the following:

*

*created the full output frame up front in a C++ program, and then looped reading in a 2x1920 scanline on each iteration and stuffed that into the correct position in the output frame, and

*when the entire sequence has been read, compressed it into a JPEG using turbo-jpeg and wrote it disk.
As such, ImageMagick is no longer required. The entire program now runs in around 1.3 seconds rather than the 10.3 seconds via ImageMagick.
Here is the code:
////////////////////////////////////////////////////////////////////////////////
// stitch.cpp
// Mark Setchell
//
// Read 2x1920 RGB frames from `ffmpeg` and stitch into 20000x1920 RGB image.
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <unistd.h>
#include <turbojpeg.h>

using namespace std;

int main()
{
   int frames = 10000;
   int height = 1920;
   int width  = frames *2;

   // Buffer in which to assemble complete output image (RGB), e.g. 20000x1920
   unsigned char *img = new unsigned char [width*height*3];

   // Buffer for one scanline image 1920x2 (RGB)
   unsigned char *scanline = new unsigned char[2*height*3];

   // Output column
   int ocol=0;

   // Read frames from `ffmpeg` fed into us like this:
   // ffmpeg -threads 4 -y -i video.mov -frames 10000 -vf "transpose=1" -f image2pipe -vcodec rawvideo -pix_fmt rgb24 - | ./stitch
   for(int f=0;f<10000;f++){
      // Read one scanline from stdin, i.e. 2x1920 RGB image...
      ssize_t bytesread = read(STDIN_FILENO, scanline, 2*height*3);

      // ... and place into finished frame
      // ip is pointer to input image
      unsigned char *ip = scanline;
      for(int row=0;row<height;row++){
         unsigned char *op = &(img[(row*width*3)+3*ocol]);
         // Copy 2 RGB pixels from scanline to output image
         *op++ = *ip++; // red
         *op++ = *ip++; // green
         *op++ = *ip++; // blue
         *op++ = *ip++; // red
         *op++ = *ip++; // green
         *op++ = *ip++; // blue
      }
      ocol += 2;
   }

   // Now encode to JPEG with turbo-jpeg
   const int JPEG_QUALITY = 75;
   long unsigned int jpegSize = 0;
   unsigned char* compressedImage = NULL;
   tjhandle _jpegCompressor = tjInitCompress();

   // Compress in memory
   tjCompress2(_jpegCompressor, img, width, 0, height, TJPF_RGB,
          &compressedImage, &jpegSize, TJSAMP_444, JPEG_QUALITY,
          TJFLAG_FASTDCT);

   // Clean up
   tjDestroy(_jpegCompressor);

   // And write to disk
   ofstream f("result.jpg", ios::out | ios::binary);
   f.write (reinterpret_cast<char*>(compressedImage), jpegSize);
}

Notes:
Note 1: In order to pre-allocate the output image, the program needs to know how many frames are coming in advance - I did not parameterize that, I just hard-coded 10,000 but it should be easy enough to change.
One way to determine the number of frames in the video sequence is this:
ffprobe -v error -count_frames -select_streams v:0 -show_entries stream=nb_frames -of default=nokey=1:noprint_wrappers=1 video.mov

Note 2: Note that I compiled the code with a couple of switches for performance:
g++-8 -O3 -march=native stitch.cpp -o stitch

Note 3: If you are running on Windows, you may need to re-open stdin in binary mode before doing:
read(STDIN_FILENO...)

Note 4: If you don't want to use turbo-jpeg, you could remove everything after the end of the main loop, and simply send a NetPBM PPM image to ImageMagick via a pipe and let it do the JPEG writing. That would look like, very roughly:
writeToStdout("P6 20000 1920 255\n");
writeToStdout(img, width*height*3);

Then you would run with:
ffmpeg ... | ./stitch | magick ppm:-  result.jpg


text:
Q: Фоновый режим работы приложения android У меня написан SIP-клиент, который совершает и принимает вызовы. Однако, при сворачивании приложения оно может выгрузиться из памяти и принимать вызовы соответственно не будет. Как реализовать приложение аналогично скайпу (до недавнего времени), когда по запуску он появляется в строке состояния и работает до тех пор, пока не нажата кнопка выхода? Наверняка существует статья на эту тему, но мои поиски не увенчались успехом.
A: Судя по вашим путаным показаниям речь идет о 3-х разных компонентах приложения:

*

*Notification - компонента отвечающая за появление значка в строке состояния

*Service - некая долгоживущая компонента, в принципе можно сделать ее и невыгружаемой.

*BroadcastReceiver - компонента отвечающая за перехват входящих звонков. Чтобы сделать ее "невыгружаемой", ее надо декларировать в манифесте с флагом exported=true
Композиционно делаем так:

*

*Выставляем нотификацию, так чтобы при клике на нее стартовалась Activity вашего приложения

*Вешаем BroadcastReceiver настроенный на фильтрацию входящих/исходящих SIP звонков. При перехвате звонка - BroadcastReceiver поднимет нужную Activity

*Бизнес-логику приложения, которая должна быть всегда под рукой размещаем в Service, так чтобы из Activity можно было обратиться к Service.

P.S. ИМХО можно обойтись и без Service - но на вкус и цвет...


text:
Q: Facebook, what is WebP format of photo In this reference of the "photo" table on Facebook, there was a new image format, which is called WebP format, any one knows what's the difference between this format and some other formats like JPEG or PNG? Is this kind of image used on handsets?

A: It's a image format created by Google that's around 20% smaller than JPG.
https://developers.google.com/speed/webp/
It's supported in Google Chrome and Android 4.0+


text:
Q: Why aren't there any main Federation battleships in the Star Trek universe? All of the ships seem to have offensive/defensive capabilities as secondary considerations. The galaxy seems to be loaded with fearsome enemies and the promise of even more powerful adversaries yet to be encountered.
When a single Borg ship can wipe out an entire Federation fleet, I would expect the Federation to come up with a Battleship or Ship-Of-The-Line capable of delivering devastating firepower and multiple independent shield generators as defense. Something similar to the ship that the Dowd Kevin Uxbridge created in TNG 'The Survivors'.

(The 'Husnock' ship fires)
WORF: Shields down! Captain, they hit us with four hundred gigawatts
  of particle energy!
PICARD: Damage?
WORF: Superficial -- but I am having trouble reassembling the shields!
(The Husnock ship fires again)
WORF: Shields down! There is thermal damage to the hull!
DATA: The warship is in possession of enormous energy reserves. It is
  capable of striking us with far more powerful bursts.
WESLEY: They're maneuvering to come between the Enterprise and Rana
  Four.
PICARD: Number One, we have been exemplary in our patience.
RIKER: Lieutenant Worf, fire phasers on full with a simultaneous
  spread of torpedoes.
(The Enterprise finally returns fire)
DATA: The vessel appears undamaged. Its defenses are apparently able
  to absorb incoming matter and energy.
RIKER: Commence rapid fire with all weapons on full!
(The Enterprise unloads on the Husnock ship, with a nice display of at
  least a dozen torpedoes and a similar number of phaser blasts. The
  Husnock ship returns fire and numerous bridge consoles erupt in
  showers of sparks)
WORF: Shields are down! There is internal damage -- weapon systems
  control has been lost!
RIKER: Riker to Sickbay. Medical assistance to the bridge!
PICARD: Mister Crusher, move the Enterprise out of range of the
  attacking vessel!
- "Star Trek Canon Database (Queried By Episode 'Survivors')", stardestroyer.net

The Enterprise is the Federation's Flagship and probably the toughest they have, yet it got creamed with 3 shots and couldn't even scratch the paint of the opposing ship.

A: The main purpose of the naval battleships of the 20th Century was power projection. Basically, they were used for shore bombardment in support of amphibious landings (D-Day) and going toe to toe against opposing force battleships and cruisers (Jutland).
The analogous situation in Star Trek would be planetary bombardment in preparation for invasion - hardly what the Federation would put in its mission statement.
Even in our own time though, battleships have become obsolete because they are highly vulnerable to being swarmed with air attacks from aircraft carriers and shore based fighter bombers. Losing such an expensive item to a cheap torpedo is not sensible. Better to make many more lighter ships with more flexible combat roles for the same price.

A: In the canon Star Trek Universe, the threat to the Federation posed by the Borg and the Jem'Hadar forced them to consider for the first time, a ship whose purpose was wholly based on military capability.
Military Considerations
As a former member of the military (US Navy), it makes perfect sense to me for the Federation to avoid creating battleships, i.e. large ships designed primarily for combat. They don't make them for the same reason we don't in the Twenty-first century. The laws of diminishing returns in combat.

*

*While cost of production is not necessarily a factor, time to produce is. If I can make six Defiant-class ships in the same time as it takes to make one Cruiser class ship, I will always take the six ships over the one. Especially if the damage dealing capacity of that one ship is half that of the Defiant class ship. Same number of crew are required, but I have six nimble targets for the enemy to shoot at and six ships capable of attacking opponents.

*Since the weaponry of the Federation is both powerful, and easily able to fit on almost any ship (as long as it has a warp core power plant) there is no rationale for placing weapons on a single ship which might be more effective being spread out over a half dozen ships.

*The factor of size is negated if you are not able to protect that ship from attack effectively. The reason the Borg get away with such immense ships, is their resilience to damage in combat. Alpha Quadrant races depend far more on shields than they do on redundant systems or sheer mass to overcome their enemies.

*Size limits the ability to coordinate technology effectively, the larger the ship and crew, the slower the coordination; Borg ships evidently benefit from their hive mind intellect enhancing their overall combat performance. In this case, a ship is only as effective as the minds coordinating it or the technology protecting it.
Technical Analysis of the Federation

*

*Despite their protestations to the contrary, the average Federation starship was, despite its addition of scientific and exploratory technology, quite a capable weapon of war.

*Armed with multiple phaser arrays or banks, photon torpedoes launchers and effective defensive shielding, the average Federation cruiser was more than a match for any other single type of cruiser from most of the Alpha quadrant races. In groups or small fleets, they were more than equal to most races of the Alpha Quadrant.

This balance of power changed when the Borg arrived.

*

*With their Cube ships, each one was filled with redundant power systems, multiple weapons systems (torpedoes, cutting beams), layered defensive arrays and powerful tractor beams (all systems used by the Federation but with the Borg strategy of filling their ships with multiple and redundant systems).

*Each Borg Cube was strategically capable of destroying entire Federation fleets simply by being able to absorb incredible amounts of fire power and still being able to destroy one ship after another with their increased rates of fire.

*The Borg could also adapt to shield signatures, rendering a ship's shields inoperative, and with their superior firepower tear it apart in seconds. This usually only took one or two attacks unless the ship rotated their shield frequency continuously.

*Add to this their ability to adapt to a particular attack and be unaffected after a time, and you have an enemy whose ability to deal destruction was unmatched in the Alpha Quadrant. No race could have stood against them for long.
To this end, the Federation designed two experimental warships:
Defiant Class Starships: an escort sized vessel with phased cannon arrays, quantum torpedoes and defensive armor as well as enhanced mobility made it more than capable of dealing damage equivalent to that of a Galaxy-class starship. Her armaments included:
Armament

*

*4 x Class I rapid fire phaser pulse cannon

*3 x Phased Beam Emitters, 2 forward, one aft, standard phaser array

*6 x Pulse fire Quantum/Photon torpedo tubes + 100 torpedoes fourforward, two aft

*1 x Probe / Photon torpedo launcher - equivalent to standard photon torpedo tube + 20 torpedoes

Defense Systems

*

*Auto modulated high capacity shield system, total capacity 2,376,000 TeraJoules

*Heavy Duranium/Tritanium double hull plus 20 cm Ablative armour.

*High level Structural Integrity Field

This was a warship, pure and simple, designed to deal out damage in all directions with variable phasers which could vary their frequency preventing the Borg from easily adapting to them and Quantum torpedoes who damage capacity eclipsed the photon torpedo by orders of magnitude; same box, much bigger bang.
Prometheus Class Starships: A slightly larger than cruiser-sized vehicle, the Prometheus was a warship whose full capacities were never shown fully on screen. It was equipped with armaments similar to the Defiant and could split into three separate vessels tripling their firepower and offensive capacity (multi-vector assault mode). It also had multiphasic, regenerative shielding, and ablative armor
Armament, Docked Mode

*

*12 x Type XII Phaser arrays

*2 x Pulse fire quantum torpedo tubes + 290 torpedoes

Armament, Separated Mode
Primary Hull:

*

*6 x Type XII Phaser arrays

*2 x Pulse fire quantum torpedo tubes + 115 torpedoes

Secondary Hull:

*

*4 x Type XII Phaser arrays

*3 x Pulse fire quantum torpedo tubes + 175 torpedoes

Tertiary Hull:

*

*8 x Type XII Phaser arrays

Total:

*

*18 x Type XII Phaser arrays

*5 x Pulse fire quantum torpedo tubes + 290 torpedoes

This also does not invalidate the increasing of firepower on larger Cruiser and Galaxy-class ships with phase cannon arrays, quantum torpedo tubes in addition to photon torpedoes and multiphasic shield arrays. With the addition of the transphasic torpedo (claimed from a future alternative timeline by Admiral Janeway for use against the Borg) the Federation would once again be a power to be reckoned with in the Alpha Quadrant.

A: Everyone here seems to miss one basic advantage of a battleship.  Yes, they can carry an awesome array of firepower, but; since they are so heavily armored and protected (in the case of trek multiple shield generators) they have the capacity to absorb massive damage and stay in the fight longer.  Sometimes this is more important than numbers particularly if you have to deploy force in more than one location.  A single battleship can do this if it carries offensive fighters of it's own.  Just a thought.
Also, one should never underestimate the psychological effects that a huge battleship has on an adversary.  Battleships invoke fear by their sheer force of presence (granted this does not work on the Borg, but he Borg apparently have found it works on almost everyone else).  Fear is a weapon.  Another point is due to a battleships massive size, it could carry weapons systems that are far to large to be carried by smaller vessels.  A good example of this is when Gul Dukat mounted a planetary defense cannon on the cargo vessel he was in command of in an episode of DS9.  You could mount such weapons easily on a much larger battleship.

A: A good rule of thumb that all naval architects follow--and this extends to fictional starship architects as well--is that a ship should only be as big as its designed mission requires it to be. Battleships of the 20th C became as big as they did because that was the size it had to be in order to:

*

*Effectively wield the numerous heavy artillery guns they were required to carry.

*Fit enough power generation/propulsion systems within the hull to generate the speed they were required to achieve.

*Carry enough armor, systems redundancy, and sub-compartmentation to withstand damage as required per design standards laid out when they were ordered.

*Carry enough fuel, ammo, supplies, machinery, manpower and equipment to sustain continuous at-sea operations for however many months required per design standards.

*Carry all their secondary and tertiary weapon batteries and their alternate mission equipment (i.e. adequate communications gear to serve as flagship if so deemed)

In the case of ST Fed ships, their main weapon systems were not very large in size or mass or power-hungry by standards of ST genre ships. Thus, they could easily be built into far smaller vessels than the large, exploration oriented starships of the Fed, hence the Defiant being so much smaller than other Fed ships while being easily a match or outmatch for any of them.
If the Fed were to field any weapon systems that required more power generation, larger size or heavier/sturdier hulls to absorb the recoil from fire/discharge/launch, then you would see dedicated warships of the Fed get bigger as necessary to match the new size requirements of the weapon systems they wield.

A: The main design point of the Dreadnoughts of the 20th Century was above all to outrange smaller vessels in order to destroy them before they could hit back, and be able to withstand the counter fire of other Dreadnoughts. This combination practically guaranteed that a fleet with Dreadnought(s) would always win against another without one if it came to battle. That's also the reason why they became quickly obsolete with the advance of aircraft carriers, as planes and rockets can target ships farther and more precisely that any naval cannon could ever hope to achieve.
In Star-Trek terms, designing a ship analogously to a Dreadnought would mean to place few (or just one) huge phaser cannon(s) on a large and well protected ship that features extremely large (or multiple) warp cores, with a primary focus on extended sensor range, decisive weapons range advantage, and such devastating hitting power that a single shot can reliably destroy anything smaller before it can fire back. Around this, a fleet of smaller vessels would make sure the behemoth cannot be overwhelmed by mass attack. Taken to extremes, that would lead to a Death Star kind of vessel:
http://en.wikipedia.org/wiki/Dreadnought#Long-range_gunnery
If bigger weapons cannot achieve a decisive range superiority, for example if phaser cannon size or range is physically limited, it is indeed tactically disadvantageous to put that many eggs into one basket, and better to build more smaller ships like the Defiant that combine stealth, rapid fire, good defensive capabilities, and enough maneuverability to evade counter fire. That's why the British in the 18th century rightly preferred building more third rates compared to more 1st rate "super ships", which offered no extended weapons range, only marginally more fire power, at excessive costs:
http://en.wikipedia.org/wiki/Third-rate

A: Battleships are typically extremely expensive, offensive vessels that take a lot of resources to build and operate. Not only do they require large amounts of personnel and equipment to run on their own, you also have to crew and supply the requisite supporting fleet of vessels (transports, frigates, destroyers etc). Since Starfleet's stated goal is the peaceful exploration of space and diplomacy, such a vessel, and fleet, would not be in line with that goal.
That is not to say that they have never built offensively oriented vessels. The most famous such example is the Defiant class ship, featured on Deep Space Nine. Originally designed to combat the Borg, the ship featured an oversized warp core, phaser cannons (in addition to phaser arrays), multiple fore and aft torpedo launchers, and as a special case with the USS Defiant, ablative armor.
But keep in mind, even though the Defiant class was arguably a war ship, it was still labeled as an escort vessel (i.e. it's primary purpose was to escort and protect other ships). Starfleet would have had a hard time calling something as large as a battleship an escort.
With that said, there are only two on screen ships I can think of that fit the battleship classification, neither of them Starfleet:

*

*Jem'Hadar battleship

*Scimitar
But all that aside, Starfleet's vessels were well suited to go one-on-one with matching classes of ships from their contemporary adversaries. Although, watching any of the shows may not make that evident as the ship would often be on the brink of destruction to build tension for the plot.

A: They do though, The Sovereign Class is effectively a battleship, especially when compared to any of the ships deployed by the major powers in the alpha quadrant.
The Sovereign is designed and used as might be expected in any setting where arms/armour development is where it's at in Star Trek, which is defensively. There's a few comments here about the cost effectiveness of battleships, but they all presume battleships are and always have been used 100% offensively which is not always the case. They can and were used as fleets in being, especially at time when armour was better than the guns. That is the Sovereign. In all her appearances she never quite has the firepower to completely overwhelm similar ships but she does have the defensive capabilities to engage them, or small fleets of smaller ships and survive.
Now ships like this have limited use, especially for a mostly peaceful and exploratory civilization/fleet like the federation. It makes sense they would only have a few of them, used primarily for "diplomacy" like "putting out diplomatic brush fires" and for internal defense. They are too expensive to have a lot of them, to valuable to afford to risk in all out combat, and too limited in there role to be of much other use.

A: Problems with Battleships that are arguably universal to space, sci-fi/fantasy space, and 20th century, 19th, 18th, 17th, 16th etc. naval warfare that contradict typical strategy/tactics of modern and perhaps futuristic military warfare and/or the goals of Starfleet in general:

*

*It's a lot of eggs in one basket. You can cause a big problem in one place with a battleship. A battleship's worth of smaller craft can cause a whole lot of problems in a whole lot of different places or an almost equally big problem in one place. Smaller more mobile ships even with considerably less firepower if delivered against the same big target are going to tend to be more useful as long as their destructive/defensive capacity is good enough for a wider variety of concerns which they can most certainly achieve through mixed roles. This applies to defense and offense.

*The one thing they've generally been better at than anything else in their respective contemporary armed forces historically speaking is attacking stationary civilian targets on land from very far away. I'm not sure that translates to space battleships necessarily but as a classical weapons platform it's certainly not the sort of weapon of civilian slaughter and infrastructure destruction role Starfleet would want to emulate.

*They're not necessarily slow but they've never been the fastest in the sea and it stands to reason they would never be the fastest in space in any drive system scenario where mass or volume is a non-trivial concern. If I loosely understand the rules of warp drive properly, mass is effectively reduced, not eliminated, and power drain is still relevant. You can't cause immediate problems for something you can't catch.

*The more accurate and rapid-fire that weapons get, the less useful/versatile/cost-effective it is to have a whole lot of hugely expensive ones on one boat/starship. Damage to dollar, the US did serious damage with its PT boats while it was rebuilding replacements for its ships lost at Pearl Harbor. In a lot of ways the Defiant is similar in its focus to the PT boat although perhaps a much tougher bug to squash.

*Battleships in a lot of ways were political weapons in much the same way nukes are today. That's another model one would hope Starfleet wouldn't be a huge fan of.

*They are 100% offensive. You don't defend with a battleship. Smaller craft en masse can easily bypass and attack civilian targets through sheer force of numbers assuming relative costs are still roughly similar to what they would be now and in recent history in naval terms.
Now that said, this is sci-fi. Any one of the concerns I list could be imagined away through virtue of some circumstance or expense. If for instance one warp drive dwarfs all the other costs of building/maintaining a starship, it might make sense to have a lot more eggs in every basket. Star Trek however tends to try and find some level of analogy with modern naval forces I think and in that context we've decided there is no longer a practical use for such vessels either.
Full-Disclosure: I was a total swarmer in Homeword 2. This may inform some of my thoughts.

A:
When a single Borg ship can wipe out an entire Federation fleet, I would expect the Federation to come up with a Battleship or Ship-Of-The-Line capable of delivering devastating firepower

They did. The Defiant:

Development on the Defiant began around 2366 in response to the Borg threat. Although officially classified as an escort vessel, the Defiant was nothing less than Starfleet's first design of warship; intended to fight, and ultimately defeat, the Borg.
From: "USS Defiant (2370)", Memory Alpha

However, it isn't mentioned in The Next Generation (aside from Riker's "tough little ship" one-liner in First Contact). It was revealed in Deep Space Nine's season 3 premiere, The Search, when it was sent on a mission to find the Dominion.
When Sisko introduces it to his senior staff, O'Brien mentions that Starfleet didn't believe in warships. Starfleet's mission is one of peace, exploration, science, and general universal love and understanding. (Why yes, the show was conceived in California in the 1960s. Good guess!) It's harder to convince new species that you want to be friends if you show up in a ship capable of blowing up their planet.
Out-of-universe, the show's premise is an optimistic one about the future of humanity - it assumes we've developed the better aspects of our nature, and prospered as a result. It's not about kicking the crap out of aliens.
(Except for the episodes — mainly in Deep Space Nine — featuring massive space battles where Starfleet kicks the crap out of aliens. They're awesome.)

A: The klingons call the enterprise a battlecruiser in ST:III.
The galaxy class is defined by starfleet as an 'explorer' or 'exploration cruiser'  I would imagine that the klingons and romulans would regard it a battlecruiser, as they did the constitution class before it.  The galaxy class is designed for exploration, not warfare.
The fact of the matter is that the federation design their ships to be multi-purpose.  They don't just do escorts and battles, they explore, they research, they are fleets in being.
The purpose of a starship is not to fight, but to explore our universe.
To seek out new life, not seek new ways to destroy it.
To that end they are equipped for defence, not offence.

A: From my understanding of Star Fleet and the Federation – Humanity is a little more mature than present day humanity. Protecting humanity by beating up or destroying threats isn't the Federation's MO. Granted, there are always outliers (Matthew Dougherty, Admiral Pike, etc.) that see the Federation as vulnerable and want to arm it to the teeth. As I said, though, Humanity is the beating heart of a Federation of widely diverse peoples and cultures. They are an inclusionary force in the universe, not an exclusionary one. Star Trek Enterprise had a new species or faction joining the Federation every other episode. The Federation even tried to bring in species that were overtly hostile by talking them down, e.g., the Romulans. Granted, it worked for only short periods of time, but that is the point, I think. Even though Romulus and the Federation are basically at a nonstop cold war, the Federation is always open to talking with the Romulans. They are almost always willing to take the first step and try to include someone rather than keep them at arm's length with a knife. That is the big picture painting about humanity and more over the universe. This is NOT the grim darkness of the far future where there is only war. This is a universe where bad shit happens for sure. But, more importantly, this is a universe where problems don't NEED to be solved with a fleet of Scimitar. They can more often than not be solved with a heart to heart, and some times that heart to heart is preceded by a shirtless battle on a desert world, because you have to have some action in there, right?
Simply put, the Federation is concerned primarily with exploration and unity/community with a baseline of defense as a deterrent only. It would, however, much rather invite an enemy to be an ally without firing a shot if at all possible. This version of humanity has had much more than its fair share of war, pain, suffering, and injustice thanks to World War III. ("Encounter at Farpoint" is a good example.) Your question comes from the point of 'safety through force of arms,' which is not the way the Federation mindset works.
The Borg in Star Trek are Deus ex Machina. They, by all rights, should have taken over creation by now. But given that Star Trek often misplaces technology or has single use mechanisms that cannot be reproduced, the oversight is forgivable.

A: Because the series isn't about warfare. Essentially the Federation has no strict warships because the writers are not supposed to create arcs about war.
IE the only reason that Deep Space Nine is set on a spacestation where other species come to it, why it had war arks, why it had Cisco, Qwark, and a ship wjich is small, doesn't look like thebEnterprise and shoots puny cannons with slow weak projectiles instead of devasting phaser fire and had a cloaking device is because the creators of yhe show were subversive types.
The Defiant is a poorly designed ship ill suited to any purpose other than scouting.
When youbcan turn energy directlt into force field strength and phaser strength then bigger is better. More power equals more protective shields and stronger phasers. The Defiant could not hope to survive combat against a larger ship with a larger generator as its puny cannons could not penetrate the stronger shields of a larger ship and its own shields could not withstand the phaser fire from a larger ship.  As you increase ship size you can also add multiple generators and multiple shielding systems as we see on large Borg cubes.
In reality the Defiant could not be considered by anyone to be a counter to the Borg as it was technologically and physically outclassed by Borg ships to such an extent that it wouldn't be able to damage a cube or withstand the force from Borg weapons. A proper anti Borg fleet would be a large number of very largw highly automated ships.
A proper warship would be very large in order to field force fields that smaller ships could not bring down and strong phasers smaller ships could not defend against.

A: The USS Vengeance on the film Into Darkness would be classed as a battleship

A: Because they didn't need them.
You only need them if you are at war or you envision conquest.  That's not what the Federation was about.

A: Just in case anyone is still minding this very interesting question- I think Starfleet would be considered quite incompetent if they did not have a war-ready fleet to go at any time if they were such ardent explorers.  In universe they encounter many peaceful races but they also encounter extraordinarily violent ones.  The Klingon ships are all weapons of war.  The Romulan ships are all weapons of war.  Cardassian, Breen, Borg, Dominion, etc etc were all battle ready wartime fleets.  The Federation could have the "exploration" fleet that makes first contact, trades, learns new stuff, etc but they should also have a potent ever adapting and improving fleet in reserve waiting for its usage.  At the moment the USA has no viable enemies on the high seas.  No one can invade us or attack us with anything except nuclear missiles as no one else has the naval capacity or intercontinental bombing fleet that could penetrate NORAD defenses.  We have not dismantled our fleet or mothballed our carriers and present a peaceful front to the world.  The USA realized that instead of pulling a post-WWI style disarmament we realized it would be better to have an active force ready to go at any time.  In universe, it would be a good idea to keep a potent force of ships that had no other usage than killing other starships to protect the Federation from future threats that might emerge.  I would also like to say the idea of a larger ship wouldn't necessarily be more vulnerable as even though all starships have shield technology not all of them appear to have ablative armor.  Very thick armor combined with redundant systems all built around a core structure of a moving gun would be something the rest of the galaxy does not currently appear to have and it would be exactly what could save the Federation from Borg cutting beams that easily sliced open the baddest ship the Federation had at the time.  One other point- the Federation does not operate on a currency based economy.  I'm not sure how they decide what to build and when but it appears they have access to unlimited resources within the Federation.  If they have the industrial capacity to create starships on demand (despite the time it would take to build them) such as the Utopia Planitia Shipyards, then they would be able to keep constructing the necessary ships and it wouldn't seem to be a point of contention- building one big one vs 12 little ones as the Dominion is shown to be constantly constructing new ships and cloning new armies and pilots for those ships.  During plentiful times of peace the Federation could conceivably create fleets in secured locations with certain parts removed like the warp cores to be inserted at will as the situation is required.  Complex holodeck simulations can be used during brief maintenance training periods much like the Reserves we have today where civies gain the experience to act as fully trained personnel when activated.  When you look at what they said the casualties were during the Dominion War alone, tens of thousands of vessels, their crews, dozens of planets conquered, pacified, and that's just on the Alliance side with another near billion Cardassian civilian casualties, and compare that to the cost of creating a reserve battle fleet with a reserve crew force then it doesn't seem to be all that expensive in a civilization that does not use money.  Just my 2¢.

A: If I'm not mistaken the Sovereign Class (Enterprise-E) is considered a Battleship.

A: More Cruisers take the same resources to build as one big Battleship. I'd take 2 or 3 Sovereign or Galaxy class ships over 1 Battleship any day.Besides, they can always be retro-fitted with additional weapons in the case of war.

A: There would be little point to have dedicated battleships, since SF ships already come with mostly 360 degrees coverage for phasers, and forward/aft torpedo launchers (which are also capable of firing seeking torpedoes) ad plethora of powerful and modular technologies.
The Defiant was described as a battleship, but this particular vessel didn't seem impressive because, it had limited firing arcs for one thing and all it managed to do was increase its phaser yield through a relatively simple 'trick' which could be adapted to other SF ships... plus it didn't deal well with speeds above Warp 9.
It also came with quantum torpedoes (again, usable on other Federation ships) and ablative hull armor (which can be added to existing Federation ships).
Even the USS Lakota (an old Excelsior class ship) was upgraded to rival the USS Defiant.
When you have multi-purpose vessels like SF that are highly modular, there is very little need to have ships dedicated purely for combat as you can adjust them to the needed situation (sometimes on the fly, other times by swapping out a module like on the Nebula class ships).
Want a more powerful Galaxy class ship?
Give it a more powerful warp core, shield array, rig the phasers to double the yield using the same method the Defiant has, equip it with Quantum torpedoes, and install Ablative hull armor on it.
Most of the changes the Defiant incorporated were things that crews could probably achieve on the fly.
You don't necessarily need more powerful warp core to increase phaser yield... just modify their properties to make them more destructive by amplifying their forces with other methodologies.
Similar principles can be applied to shields...
Of course, it's a bit trickier to apply ablative hull armor on the ship's hull, but in the 24th century, it should be easily done using replicators and transporters really.