text:
Q: Tooltwist Stack trace after log in to designer: "com.dinaa.xpc.XpcConfigException: Unknown user type: 'phinza'" I am getting this error after I log in and access the ToolTwist designer after deployment:
Stack trace:
com.dinaa.xpc.XpcConfigException: Unknown user type: 'phinza'
at com.dinaa.xpc.backend.XpcSecurityImpl.login(XpcSecurityImpl.java:296)
at com.dinaa.xpc.XpcLogin.login(XpcLogin.java:51)
at com.dinaa.xpc.XpcLogin.login(XpcLogin.java:80)
at tooltwist.basic.LoginServlet.doPost(LoginServlet.java:136)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.myrp.util.XSSFilter.doFilter(XSSFilter.java:22)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:409)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1721)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

What are the possible errors that could lead to these stack traces and how could I fix it?

A: I think you are just missing to include ttsec-standaloneDesigner as projectLayer in your tooltwist.xml. Try to add this line on your tooltwist.xml before the webdesign projectLayer element:
<projectLayer>ttsec-standaloneDesigner</projectLayer>

You should see something like this
    <projectLayer>myrp_t</projectLayer>
    <projectLayer>ttsec-standaloneDesigner</projectLayer>
    <projectLayer>webdesign</projectLayer>

A: ttsec-standaloneDesigner is only one of the plugin that you can use. See "Configuring Security Plugins" for other available plugins and complete documentation about this.

A: If you are running ToolTwist in Eclipse, check that you have the ttsec-standalone project installed alongside tooltwist, ttStd and ttWbd, so the Designer can get access to it's config files.


text:
Q: How to define python pybind11 bindings of "operator()" C++ class method? Say I have a simple C++ class
class MyClass{
     //constructor
     MyClass(int value):_value(value){};

     void operator()(AnotherClass& const b){
     // Do something with b object
     }

    private:
      int _value;
}

I am trying to create Python binding of this class using pybind11. How can I bind the operator() method?
This binding is going to be used to pass objects of this class to functions requiring a callback function as an argument.

A: I figured this out after trying various things. We need to define the __call__ method in our binding. As an example:
.def("__call__", [](MyClass& this, AnotherClass& const b){
                   return this(b);
                 }
    )

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cómo hacer un main en Ruby Estoy aprendiendo Ruby y es la primera vez que hago un programa con clases en este lenguaje.
Me queda hacer el main, pero no sé por dónde empezar

A: Considerando que en C++ y en Java por ejemplo el método main es el punto de inicialización del código; me parece en Ruby varía un poco; pues tenemos que por cada archivo declaramos una clase con sus métodos y atributos y estos mismos serán leídos interpretados y ejecutados de manera secuencial.
Clase Padre.rb
class Padre

  def mensaje
    puts "Soy tu padre SO en español :D"
  end

end

Creamos nuestra primer instancia, que puede estar contenido en el mismo archivo o en otro.
padre1 = Padre.new()
padre1.mensaje()

Lo que nos dará como resultado:

Soy tu padre SO en español :D

Entonces como puedes observar lo que va a ocurrir es que el código se leera desde la declaración de la clase, pero mostrará algún resultado en pantalla hasta que lea la línea donde se realiza la instancia de la clase asignada al objeto padre1
Sin embargo....
Para el caso de C++, citando a la página cplusplus.com1 no importa el orden de los métodos declarados en un programa en C++, siempre el método que se invocará primero es el main
Como puedes observar en este ejemplo2 tomado de la misma página:
// classes example
#include <iostream>
using namespace std;

class Rectangle {
    int width, height;
  public:
    void set_values (int,int);
    int area() {return width*height;}
};

void Rectangle::set_values (int x, int y) {
  width = x;
  height = y;
}

int main () {
  Rectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
  return 0;
}

El método main donde se invoca a la clase Rectangle y al objeto rect donde primero accedemos al método que setea los valores para calcular el área y luego invoca al método área para obtener el resultado de dicho cálculo.
Una aproximación al mismo ejercicio en Ruby pudiera ser de este modo:
class Rectangle
  def initialize(width, height)
    @width = width
    @height = height
  end

  def area
    puts @width * @height
  end
end

rect = Rectangle.new(3, 4)
rect.area();

Explicación

*

*Declaramos una clase de nombre Rectangle

*Creamos un método constructor3 que será el primero en ser llamado una vez que la clase sea instanciada a un nuevo objeto

*Dentro del método constructor pasamos como argumentos 2 propiedades que serán requeridas de darles valores al momento de instanciar la clase a un nuevo objeto

*Creamos un método area que procesará multiplicando los valores que reciba la clase

*En el objeto rect creamos la instancia de la clase y le pasamos 2 valores a los argumentos declarados dentro de la clase en el método constructor

*Con el objeto rect accedemos al método area que nos debería imprimir 12
Referencias

*

*1método main en C++

*2clases en C++

*3método initialize


text:
Q: Nested Json Array constructs un-marshalling in golang I was mainly looking at un-marshalling the below JSON array in golang.
{
 "status":{"code":"SUCCESS"},
 "result": {
              "total_records":1,
              "records": [{
                            "last_modified_timestamp":1501209015807,
                            "dns_servers":null,
                            "is_secured":false,
                            "nis_domains":null,
                            "storage_platform_resource_key":"e1ee32f9-6576-11e7-82a8-00a098697714",
                            "name":"vs1",
                            "nis_servers":null,
                            "created_timestamp":1501208944094,
                            "dns_domains":null,
                            "key":"f59dacca-7379-11e7-82a8-00a098697714"
                         }]
            }
 }

I am looking to extract the "key" field here. Tried the below syntax but not able to successfully get what i want.
var dat map[string]interface{}

// Unmarshall the JSON body
if err := json.Unmarshal(body, &dat); err != nil {
    fmt.Println(err)
}
svmRecordsMap := dat["result"].(map[string]interface{})["records"]
fmt.Printf("%+v", svmRecordsMap)

result := (svmRecordsMap["key"].([]interface{})[0]).(map[string]interface{})

Any help here would be very much appreciated. Note that i am not looking at defining corresponding structs and making a copy.
Thanks!

A: I think this solution can give you a hint what you suppose to do to extract keys from this JSON without any additional type creation.

A: I let you an example: https://play.golang.org/p/tReMMtGA2V
package main

import (
    "encoding/json"
    "fmt"
)

func main() {

    txt := `{
 "status":{"code":"SUCCESS"},
 "result": {
              "total_records":1,
              "records": [{
                            "last_modified_timestamp":1501209015807,
                            "dns_servers":null,
                            "is_secured":false,
                            "nis_domains":null,
                            "storage_platform_resource_key":"e1ee32f9-6576-11e7-82a8-00a098697714",
                            "name":"vs1",
                            "nis_servers":null,
                            "created_timestamp":1501208944094,
                            "dns_domains":null,
                            "key":"f59dacca-7379-11e7-82a8-00a098697714"
                         }]
            }
 }`

    var dat map[string]interface{}

    if err := json.Unmarshal([]byte(txt), &dat); err != nil {
        fmt.Println(err)
    }
    svmRecordsMap := dat["result"].(map[string]interface{})["records"]
    fmt.Printf("%+v", svmRecordsMap)

    result := (svmRecordsMap.([]interface{})[0]).(map[string]interface{})

    fmt.Println(result)

}

In your example have to remove the "[key]" when you access to svmRecordsMap


text:
Q: How to use Google Analytics in a Firefox addon?
Possible Duplicate:
Google Analytics to track FireFox extension use

I tried injecting a script tag on the page with analytics code, but it is reporting 200+ absolute unique visitors from me alone...
Is there a way to use the script that will provide me a more accurate result?

A: Depending on what you want to track you may not need Google Analytics. Mozilla's addon.mozilla.org portal already provides comprehensive tracking and usage statistics for addons.
To check if Mozilla provides what you need go to the Statistics Dashboard and choose the statistics for one of the publicly available addons.

A: It sounds like the cookies required to track a user aren't being registered properly and used by the ga.js script. Without a way to identify a visitor GA will think that every time you call the tracking code it comes from a new visitor.
You could try constructing the tracking pixel yourself and sending it to GA whenever you want to register a pageview. You would need to simulate the __utm.gif request and place your own values into the URL parameters.


text:
Q: Python range with tuple,list as imput is there a way to hack range function to accept tuples?
like this :
range( (0,0,0), (10,1,5) , (1,1,1) )
i want to use range on custom point class , it can return list,tuple or class object. I tired the for loops, while loops, generators, list comprehensions, maps and filtering. They are very good on smaller numbers <10 but on larger numbers they take too long. Is there a way this can be done?
And i plan to use this function to describe space, for example you have available points of some 3d box, you need to check some other 3d box if it can be located in some point withing the bigger 3d box, so i would need to call this range 2 times in this example. One : for the available points in bigger 3d box, and second to check every point in  smaller 3d box if it is empty in bigger box. So if i have range functions that take 2 minutes this one will need 4 minutes + exec time for any function to be done. Now this project must be on greater scale, not only 1 small box but several.

A: Here is a little custom range function, that is based on zipping, unpacking and itertools.product:
>>> from itertools import product
>>> from pprint import pprint

>>> def my_range(start, stop, step):
...     return product(*(xrange(*x) for x in zip(start, stop, step)))

>>> r = ((0, 0, 0), (5, 2, 4), (1, 1, 1))

>>> pprint(list(my_range(*r)))
[(0, 0, 0),
(0, 0, 1),
(0, 0, 2),
(0, 0, 3),
(0, 1, 0),
(0, 1, 1),
# ...
(4, 1, 1),
(4, 1, 2),
(4, 1, 3)]

However, when performance becomes important, you should look at implementing your own range class along the lines of the Python3 range object, as these points become numerous quite fast and there much cleverer ways to check whether one box is contained in another one then iterating over all points.


text:
Q: trivial motion identity I am a bit confused about this trivial identity. We have rotation by $\theta$ and translation with a vector $a$. Can someone provide intuition why this is true?

A: Rotation of a vector in 2D by an angle $\theta$ can be thought of as multiplication by $e^{i\theta}$, i.e.
\begin{align*}
\rho_{\theta}(z)&=ze^{i\theta} && \text{(rotation)}\\
\tau_{a}(z)&=z+a && \text{(translation)}
\end{align*}
Thus
$$\rho_{\theta}\left(\tau_{a}(z)\right)=\rho_{\theta}(z+a)=e^{i\theta}(z+a).$$
And,
$$\tau_{a'}\left(\rho_{\theta}(z)\right)=\tau_{a'}(ze^{i\theta})=ze^{i\theta}+a'.$$
But we are given that $a'=ae^{i\theta}$. Thus the two expressions are equal.


text:
Q: SQL server, pyodbc and deadlock errors I have some code that writes Scrapy scraped data to a SQL server db. The data items consist of some basic hotel data (name, address, rating..) and some list of rooms with associated data(price, occupancy etc). There can be multiple celery threads and multiple servers running this code and simultaneously writing to the db different items. I am encountering deadlock errors like:
[Failure instance: Traceback: <class 'pyodbc.ProgrammingError'>:
('42000', '[42000] [FreeTDS][SQL Server]Transaction (Process ID 62)
 was deadlocked on lock resources with another process and has been
chosen as the deadlock victim. Rerun the transaction. (1205) (SQLParamData)')

The code that actually does the insert/update schematically looks like this:
1) Check if hotel exists in hotels table, if it does update it, else insert it new.
   Get the hotel id either way. This is done by `curs.execute(...)`

2) Python loop over the hotel rooms scraped. For each room check if room exists
   in the rooms table (which is foreign keyed to the hotels table).
   If not, then insert it using the hotel id to reference the hotels table row.
   Else update it.  These upserts are done using `curs.execute(...)`.

It is a bit more complicated than this in practice, but this illustrates that the Python code is using multiple curs.executes before and during the loop.
If instead of upserting the data in the above manner, I generate one big SQL command, which does the same thing (checks for hotel, upserts it, records the id to a temporary variable, for each room checks if exists and upserts against the hotel id var etc), then do only a single curs.execute(...)  in the python code, then I no longer see deadlock errors.
However, I don't really understand why this makes a difference, and also I'm not entirely sure it is safe to run big SQL blocks with multiple SELECTS, INSERTS, UPDATES in a single pyodbc curs.execute. As I understand pyodbc is suppose to only handle single statements, however it does seem to work, and I see my tables populates with no deadlock errors.
Nevertheless, it seems impossible to get any output if I do a big command like this. I tried declaring a variable @output_string and recording various things to it (did we have to insert or update the hotel for example) before finally SELECT @output_string as outputstring, but doing a fetch after the execute in pyodbc always fails with
<class 'pyodbc.ProgrammingError'>: No results.  Previous SQL was not a query.

Experiments within the shell suggest pyodbc ignores everything after the first statement:
In [11]: curs.execute("SELECT 'HELLO'; SELECT 'BYE';")
Out[11]: <pyodbc.Cursor at 0x7fc52c044a50>

In [12]: curs.fetchall()
Out[12]: [('HELLO', )]

So if the first statement is not a query you get that error:
In [13]: curs.execute("PRINT 'HELLO'; SELECT 'BYE';")
Out[13]: <pyodbc.Cursor at 0x7fc52c044a50>

In [14]: curs.fetchall()
---------------------------------------------------------------------------
ProgrammingError                          Traceback (most recent call last)
<ipython-input-14-ad813e4432e9> in <module>()
----> 1 curs.fetchall()

ProgrammingError: No results.  Previous SQL was not a query.

Nevertheless, except for the inability to fetch my @output_string, my real "big query", consisting of multiple selects, updates, inserts actually works and populates multiple tables in the db.
Nevertheless, if I try something like
curs.execute('INSERT INTO testX (entid, thecol) VALUES (4, 5); INSERT INTO testX (entid, thecol) VALUES (5, 6); SELECT * FROM testX; '
...: )

I see that both rows were inserted into the table tableX, even a subsequent curs.fetchall() fails with the "Previous SQL was not a query." error, so it seems that pyodbc execute does execute everything...not just the first statement.
If I can trust this, then my main problem is how to get some output for logging.
EDIT Setting autocommit=True in the dbargs seems to prevent the deadlock errors, even with the multiple curs.executes. But why does this fix it?

A:
Setting autocommit=True in the dbargs seems to prevent the deadlock errors, even with the multiple curs.executes. But why does this fix it?

When establishing a connection, pyodbc defaults to autocommit=False in accordance with the Python DB-API spec. Therefore when the first SQL statement is executed, ODBC begins a database transaction that remains in effect until the Python code does a .commit() or a .rollback() on the connection.
The default transaction isolation level in SQL Server is "Read Committed". Unless the database is configured to support SNAPSHOT isolation by default, a write operation within a transaction under Read Committed isolation will place transaction-scoped locks on the rows that were updated. Under conditions of high concurrency, deadlocks can occur if multiple processes generate conflicting locks. If those processes use long-lived transactions that generate a large number of such locks then the chances of a deadlock are greater.
Setting autocommit=True will avoid the deadlocks because each individual SQL statement will be automatically committed, thus ending the transaction (which was automatically started when that statement began executing) and releasing any locks on the updated rows.
So, to help avoid deadlocks you can consider a couple of different strategies:

*

*continue to use autocommit=True, or

*have your Python code explicitly .commit() more often, or

*use SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED to "loosen up" the transaction isolation level and avoid the persistent locks created by write operations, or

*configure the database to use SNAPSHOT isolation which will avoid lock contention but will make SQL Server work harder.

You will need to do some homework to determine the best strategy for your particular usage case.


text:
Q: What's the best way to reference a .DLL - as a normal reference or as a web service? What is the best way to reference an existing .NET dll (Class library)? Is there any benefit to expose web services from the class library and reference these as opposed to referencing the actual .dll (Although one benefit of the web service approach is the granularity and thus surface area exposed is up to you at coding time)?
I am thinking with loose coupling in mind, as a criteria.
Thanks

A: I would have thought that referencing "normally" was generally your best bet. I'd only reference a Web Service if that was the only option.
If loose-coupling is a key driver then you're better off using Dependency Injection / IoC.

A: I don't believe web services are what you are looking for. Web services are not a blanket decoupling tool, and should not be used as one.
First and foremost, I would say the first thing to do before referencing an existing .NET class library is ask yourself, how much risk are you taking if you access this directly? Or, what am I going to have to do if the API/functionality of this library changes?
If you are referencing System.dll, then you know it's not going to change (.NET Framework upgrades aside) and I would recommended referencing it directly. There's no real risk here. If the referenced library is highly suspect or changes often, then you want to protect your consuming library from being dependent on it.
There are many different ways to decouple your library from the library you are consuming. As Adrian K mentions, Dependency Injection and Inversion of Control are a good place to start. They might also be overkill and a simple application of the Adapter pattern may suffice. It really depends on the situation.


text:
Q: Why is my multiprocessing code leaking? I have created a flow of execution which spawns several Processes and then on those spawns several Threads.
I thought some issues could be:

*

*I am not joining the queue correctly. I join once in the process to get the results from the thread and then once outside to get the processes. However I don't join the sub-process.

*I am not using process.daemon = True

*I am missing a break somewhere, etc.
However, I notice that as I go through the loop some processes remain and do not close and can't seem to figure out why.
First I create two queues to hold my request-urls and then the response from them. Then, I start my processes, which in turn establish a urllib3.HTTPConnectionPool and then create threads (using that thread-safe connection pool).
The issue is that some of the processes don't fully close and I can't figure out why.
from threading import Thread
from urllib3 import HTTPConnectionPool
from multiprocessing import Process, cpu_count, Queue, JoinableQueue, Event

class Consumer(Thread):
    def __init__(self, qin, qout, conn_pool):
        Thread.__init__(self)
        self.__qin = qin
        self.__qout = qout
        self.__connpool = conn_pool

    def run(self):
        # Close once queue empty (otherwise process will linger)
        while not self.__qin.empty():
            msg = self.__qin.get()
            ul, qid = msg
            try:
                response = self.__connpool.request('GET', ul)
                s = float(response.status)
                if s == 200:
                    json_geocode = json.loads(response.data.decode('utf-8'))
                    tot_time_s = json_geocode['paths'][0]['time']
                    tot_dist_m = json_geocode['paths'][0]['distance']
                    out = [qid, s, tot_time_s, tot_dist_m]
                elif s == 400:
                    #print("Done but no route for row: ", qid)
                    out = [qid, 999, 0, 0]
                else:
                    print("Done but unknown error for: ", s)
                    out = [qid, 999, 0, 0]
            except Exception as err:
                print(err)
                out = [qid, 999, 0, 0]
            #print(out)
            self.__qout.put(out)
            self.__qin.task_done()
            return

class Worker(Process):
    def __init__(self, qin, qout, *args, **kwargs):
        super(Worker, self).__init__(*args, **kwargs)
        self._qin = qin
        self._qout = qout
        self.exit = Event()

    def run(self):
        # Create thread-safe connection pool
        concurrent = 10
        with HTTPConnectionPool(host=ghost, port=gport, maxsize=concurrent) as conn_pool:
            num_threads = concurrent
            # Start threads (concurrent) per process
            for _ in range(num_threads):
                Consumer(self._qin, self._qout, conn_pool).start()
            # Block until all urls in self._qin are processed
            self._qin.join()
        return

if __name__ == '__main__':
    for _ in range(100):
        # Fill queue input
        qin = JoinableQueue()
        for url_q in url_routes:
            qin.put(url_q)
        # Queue to collect output
        qout = Queue()
        # Start cpu_count number of processes (which will launch threads and sessions)
        for __ in range(cpu_count())
            Worker(qin, qout).start()
        # Block until all urls in qin are processed
        qin.join()
        # Fill routes
        calc_routes = []
        while not qout.empty():
            calc_routes.append(qout.get())


text:
Q: Sort Multiple columns Alphabetically in SQL There is a table named books which has two columns,

*

*text column title

*text column author
How to get both columns sorted alphabetically.
Input:
CREATE TABLE books (
  id Int,
  title Varchar,
  author Varchar
);

INSERT INTO books (title, author) VALUES ("Alice in Wonderland", "Lewis Carroll");
INSERT INTO books (title, author) VALUES ("Elements", "Euclid");
INSERT INTO books (title, author) VALUES ("The Extended Phenotype", "Richard Dawkins");
INSERT INTO books (title, author) VALUES ("Philosophiæ Naturalis Principia Mathematica", "Isaac Newton");
INSERT INTO books (title, author) VALUES ("Flatland: A Romance of Many Dimensions", "Edwin Abbott Abbott");
INSERT INTO books (title, author) VALUES ("The Emperor's New Mind", "Roger Penrose");
INSERT INTO books (title, author) VALUES ("Romeo and Juliet", "William Shakespeare");

Expected Output:
Alice in Wonderland
Elements
Flatland: A Romance of Many Dimensions
Philosophiæ Naturalis Principia Mathematica
Romeo and Juliet
The Emperor's New Mind
The Extended Phenotype
Edwin Abbott Abbott
Euclid
Isaac Newton
Lewis Carroll
Richard Dawkins
Roger Penrose
William Shakespeare

A: you could use the with clause then union your two inline views.
with t1 as (select title as colA from books order by title),
t2 as (select author as colA from books order by author)
select * from t1 union all select * from t2

https://www.db-fiddle.com/f/6CUeX8fnp2cHgi7iRzyL73/0


text:
Q: Matrix with complex exponential elements in Python I have been trying to create this Hamiltonian matrix, and I believe the complex exponential elements are giving me trouble. However, I don't know how to fix it.
This is what I have written so far:
t = 2.7
a = 1

z = -t * np.exp(-j*k*a)

y = -t * np.exp(j*k*a)

H = np.matrix(([0, -t,0,-t,0,0,0,0,0,0,0,0,0,0],
    [- t, 0,- t ,0,0,0,0,0,0,0,0,0,0,0]
    [0, - t ,0,y,0,-t,0,0,0,0,0,0,0,0]
    [-t, 0,z,0,-t,0,0,0,0,0,0,0,0,0]
    [0, 0,0,- t ,0,- t ,0,-t,0,0,0,0,0,0]
    [0, 0,-t,0,0,-t,0,-t,0,0,0,0,0,0]
    [0, 0,0,0,0,- t ,0,y,0,-t,0,0,0,0]
    [0, 0,0,0,-t,0,z,0,- t,0,0,0,0,0]
    [0, 0,0,0,0,0,0,- t,0,- t,0,-t,0,0]
    [0, 0,0,0,0,0,-t,0,- t,0,- t,0,0,0]
    [0, 0,0,0,0,0,0,0,0,- t,0,y,0,-t]
    [0, 0,0,0,0,0,0,0,-t,0,z,0,- t,0]
    [0, 0,0,0,0,0,0,0,0,0,0,- t ,0,- t]
    [0, 0,0,0,0,0,0,0,0,0,-t,0,- t ,0]),dtype = np.complex)`

When I try to run the cell, this error message appears
TypeError: list indices must be integers or slices, not tuple
The matrix needs to be a 14x14 one so that I can code and obtain the eigenvalues and eigenvectors.
In the past I have used np.array to build matrices, and it has worked fine. However, for this one it didn't. As can be seen, I have also tried using np.matrix.

A: Try using
np.array([[val1, val2], [val3, val4]])

instead of
np.array(([val1, val2] [val3, val4])) ...

You got the error because of the commas in between the rows. Don't forget them otherwise Python thinks you are trying to do list indexing:
I.e.
[1,2,3][0]
Output: 1

Whereas
[1,2,3], [0]

Output:
([1,2,3], [0])


text:
Q: How to support and paint multiple algorithms I have been working on a maze generator/solver program. It works nicely, but I came across a problem while refactoring my code.
Basically, I used to call methods that draw the process of solving a maze directly from another class, as opposed to calling the paintComponent method (or rather the repaint method). As obviously that is not a good practice, nor is it satisfactory performance-wise I am trying to get around that.
The problem is, to draw the sub-steps of a solution, different solver algorithms need different types and numbers of arguments.
I could store these in a class, then call the paintComponent method, in which I invoke the method that paints the sub-steps using the aforementioned arguments.
Unfortunately, that would mean that I have to create a bunch of other classes that extend JPanel, just so I can store the necessary collections and variables, just so I can draw that one specific solution.
Is there a nicer way to get around this, or should I just give up and do it the way I mentioned?
So what I am trying to do:
@Override
public void paintComponent(Graphics g){
    super(g);
    drawMaze(g);
    switch(solverType) //Based on what solver is assigned to the maze it calls the proper method
    {
       case solver1:
          solver1Drawer(g, additional arguments);
       break;
       case solver2:
          solver2Drawer(g, different kind, and number of arguments);
       break;
       //Other cases, with other method calls
    }
}

A: There are many ways to build such applications that can accept different solvers and views. I'll try to demonstrate a very basic, stripped-down one in an effort to make it as simple as possible.
For this purpose, we'll use a solver that calculates the perimeter of a certain shape and draw the solution.
For a start, we'll define some interfaces, the use of which should become clearer later:
interface Model{
    boolean solve();
    int solution();
    boolean isSolved();
}

interface View{
    void draw(Graphics g);
}

interface Solver {
    Model getModel();
    View getView();
}

Using these interfaces we'll define the Model, the View and the Controller to support the calculation of a perimeter of a square.
The model encapsulates the information (attributes and states) and logic :
class SquarePrimeterModel implements Model{

    private final int edgeLength;
    private int perimeter;
    private boolean isSolved = false;

    public SquarePrimeterModel(int edgeLength) {
        this.edgeLength = edgeLength;
    }

    @Override
    public boolean solve() {
        perimeter = 4 * edgeLength;
        isSolved = true;
        return true;
    }

    @Override
    public int solution() {
        return perimeter;
    }

    @Override
    public boolean isSolved() {
        return isSolved;
    }

    //edgeLength is a unique property for this model
    public int getEdgeLength() {
        return edgeLength;
    }
}

The responsibility of the view, as its name suggests to generate the view:
class SquarePrimeterView implements View{

    private final static int xOffset = 50, yOffset = 50, GAP = 20;
    private final SquarePrimeterModel model;

    public SquarePrimeterView(SquarePrimeterModel model) {
        this.model = model;
    }

    @Override
    public void draw(Graphics g) {
        if(model.isSolved()){
            g.drawRect(xOffset, yOffset, model.getEdgeLength(), model.getEdgeLength());
            String text = "Edge =" + model.getEdgeLength() + " Perimiter ="+ model.solution();
            int yPosition = yOffset + model.getEdgeLength()+ GAP;
            g.drawString(text, xOffset, yPosition);
        }
    }
}

The controller constructs, configures and manages the model and the view:
class SquarePrimeterController implements Solver{

    private final SquarePrimeterModel model;
    private final View view;

    public SquarePrimeterController(int edgeLength) {
        model = new SquarePrimeterModel(edgeLength);
        view = new SquarePrimeterView(model);
    }

    @Override
    public Model getModel() {
        return model;
    }

    @Override
    public View getView() {
        return view;
    }
}

If we need another solver, for example, a solver to calculate the perimeter of a triangle, we simply have to write TriangelPrimeterController, TriangelPrimeterModel and TriangelPrimeterView, very similar to the SquarePrimeter classes.
The last pice of code that we need is the application that uses SquarePrimeterController:
public class SwingMVCSolveController {

    public SwingMVCSolveController() {
        Solver solver = new SquarePrimeterController(150);//todo: select solver by gui
        solver.getModel().solve(); //todo start solve by gui
        new MainView(solver.getView());
    }

    public static void main(String[] args) {
        new SwingMVCSolveController();
    }
}

class MainView extends JPanel {

    private static final Dimension size = new Dimension(400, 400);
    private final View solverView;
    public MainView(View view) {
        solverView = view;
        createAndShowGui();
    }

    private void createAndShowGui() {
        JFrame frame = new JFrame ();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.add (this);
        frame.pack();
        frame.setVisible (true);
    }

    @Override
    public Dimension getPreferredSize() {
        return size;
    }

    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        solverView.draw(g);
    }
}

Clearly Solver solver = new SquarePrimeterController(150); can be changed to Solver solver = new TrianglePrimeterController(150); or any other implementation of Solver.
A full runnable code is available here


text:
Q: Case class copy does not maintain state of an inherited trait Say I define a trait and case class that extends it:
    trait A {
        var list: List[Int] = List()
        def add(i: Int) = list = i :: list
    }

    case class B(str: String) extends A

If I then create an instance of B, modify the list and make a copy of it, the copy takes the values of the list as defined in trait A:
    val b = B("foo")
    b.add(3)
    println("B: " + b.list)
    println("Copied: " + b.copy(str = "bar").list)

Output:

B: List(3)
Copied: List()

I know this is probably not good functional programming practice anyway, but is there a way I can force the copy of B to take the altered version of the list for instance b?

A: You can accomplish this by declaring the list in the case class, and satisfy your trait's type by declaring a method. So:
trait A {
    def list: List[Int]
}

case class B(i: Int, var list: List[Int]) extends A

And then your example:
scala> val b = B(2, List(1))
b: B = B(2,List(1))

scala>  b.list = List(3)
b.list: List[Int] = List(3)

scala>  println("B: " + b.list)
B: List(3)

scala> println("Copied: " + b.copy(i = 4).list)
Copied: List(3)

I don't know what you're doing that requires a mutable list in your class, but I imagine that even though this satisfies your example it might not satisfy whatever problem you're working on since:
scala> val a: A = b
a: A = B(2,List(3))

scala> a.list
res2: List[Int] = List(3)

scala> a.list = List(4)
<console>:15: error: value list_= is not a member of A
       a.list = List(4)

When trying to view an instance of B as an A you won't be able to assign the list type. If you were dealing with an instance of A you'd have to do something like
scala> a match {
     | case itsAB: B => itsAB.list = List(4); itsAB
     | case other => other
     | }
res3: A = B(2,List(4))

But either way, this is how you'd do it. Either that or you can follow phongnt's advice to create a non-case class and define a copy method yourself.
In a comment you said:

I failed to mention that the trait attribute needs to be modifiable with a reference to the trait itself

But this sounds like global mutable state to me. If you really need that, and I encourage you to not to then you can use an object:
object A {
   @volatile
   var list = List.empty[Int]
}

But I doubt this gets at what you're expressing in your question either since there is not an individual list still per instance here. So... looking at your updated question, I can only guess that something like this is what you're trying to accomplish:
object A {
   @volatile
   var list = List.empty[Int]
}

trait A {
   def list = A.list
   def add(i: Int) = A.list = i :: A.list
}

case class B(str: String) extends A

Which lets you:
scala> val b = B("hi")
b: B = B(hi)

scala> b.add(0)

scala> b.add(1)

scala> A.list
res4: List[Int] = List(1, 0)

But again, this is global mutable state, it's not a good thing. It's not threadsafe. So if there's a way for you to figure out your problem without doing this... I'd encourage you to do so.

A: The copy method is generated for you by the compiler when you declare a case class and it is only parameterised with the variables you define in the case class
Hence, you can definitely have copy method do that for you by declaring the variable list in the case class e.g. case class B(i: Int, list: List[Int]). You will also need override val modifier to satisfy scalac. However, scalac doesn't allow you to override a mutable variable, so you need to change the trait too, for example
trait A {
  val list: List[Int] = List(1)
}

case class B(i: Int, override val list: List[Int]) extends A


text:
Q: How to skip intro videos in MGS5:Ground Zeroes for PC? Is there a command line argument or something for Metal Gear Solid V: Ground Zeroes on PC (Steam) to skip the intro videos, like there are in other games?
(I'm not talking about the mission intro cutscene - I'm talking about the Konami/NVidia/etc splashes when you first load the game)
Thanks.


text:
Q: Python in the enterprise: Pros and cons I have been exploring and developing an application in Python for mission critical work in the commercial banking arena.
Banks are way conservative in selecting new applications.
I need real proof of stability and others using.
Have looked at the Python site but now I'm hoping this crowd can tell me more.
So far I don't have a development bank partner which I will need next stage, so I'm gathering proof and pitch info. All help and comments appreciated.

A: Of course you can implement mission-critical software (whatever that is in your case) using Python. At the end of the day the success of your application is going to weigh more on its capabilities than whether it is written in Python. Some all .NET companies will even bring in Python applications provided that there is a way to talk to the system from .NET.
I would not market your application as being a Python application. This is going to cause you trouble down the road because you will run into roadblocks. This often happens when you satisfy a business customer and he speaks to their IT guy who says "whoa we can't support that" without a full analysis of the cost/benefit to the business. This is the place that references to use of Python in mission-critical systems will arise. Try to avoid this area.
With Python you can always target the popular platforms if you build your application under certain constraints. IronPython runs on .NET and Jython runs on Java. Being able to fire back with info on how to run your application on these platforms might be helpful.

A: There is a rather famous application heavily used in both banks and hedge funds called FrontArena. I believe that this is written in Python.
Additionally the numpy numeric processing libraries and concise, clear syntax means that Python is very popular with Quantitative Analysts (or quants) within the financial sector.

A: Banca d'Italia (roughly the Italian equivalent of the Fed, except that, since the introduction of the Euro, all countries using euros as their currency, including of course Italy, have "outsourced" monetary policy to the European Central Bank) uses Python, is very happy with it, and plans to extend its use. The talk I'm pointing to is in Italian, but if you search around for the authors I think you can find similar papers of theirs in English.
Sungard's FrontArena, a widespread "next generation cross-asset trading" system, uses Python (e.g., see here).
This post gives a good summary of Python use in banking (as of a couple years ago) with focus on the City of London.
Considering how banks like to "play them close to their vest" I think it's amazing that there's as much information as this about the use of Python in banking -- if these few cases "leak", just imagine how many must be staying under wraps!-)

A: CCP Games uses a version called Stackless Python in their MMO, for both the client and server.  A large part of the game is based on a market/trade simulation, and accurately tracks and reports millions of market transactions on thousands of items daily.  It may sound odd, but considering how fickle and downright whiny my fellow gamers can be, the decision to use Python in that type of high availability environment should count for something.

A: There's always ResolverOne.

A: Sungard Front Arena makes extensive use of Python in its system architecture.  This is a trading floor system with quite a substantial market share in its space.  And, yes, it is used extensively by investment banks.

A: It's not exactly extensive proof, but this blog describes a bit of an overview of how Google is using Python.
I might argue that Google is more "mission-critical" than (almost?) any bank out there.
There's obviously plenty more resources besides that link on how Google is using Python, but if Google, the company indexing virtually the entire internet, can use Python as a core language, surely Python would meet a bank's criteria.

A: i know topic is rather old, but anyway.
if we talk about mission critical.
Python is widly used in Thales software provided with is hardware encryption solutions.
and in PayShield application for example, which i believe really mission critical.
Although Java is being used there more than Python.

A: Python doesn't have anywhere close to as much money backing it as MSFT or Redhat etc.  If Guido gets hit by a bus, Python is in trouble.
I <3 python for a lot of things, but a financial transaction system probably wants a real, trusted, stable company backing it.
Edit: this isn't flame bait; this is a major lesson learned from watching a colleague push a platform backed by a small company, and the resulting 'business-strategic' nightmare that ended with his project getting dropped in favor of someone using a far crappier project with lots of money.  There's more to project success than the technical bit.

A: I'll try again.
My employer (we're huge) did a study to resolve an internal conflict over what 'platform' to standardize to.  Platforms were judged on technical depth, business alignment, and company viability.  The one that won was middle of the road technically and had superior business alignment and company viability.  The customers don't care about the technical bits; the customer wants to make sure there will be no major strategic roadblocks in 4 years like if the supporting company folded.
All of the links I've clicked on in this thread are not enterprise systems, they're applications.  As far as I have seen, no company has the balls to write a mission critical enterprise system in python, except for Eve Online, which is a game--downtime isn't going to get anyone killed or sued.


text:
Q: Using Selenium in PowerShell, cannot capture dropdown I have been attempting to automate a web page (help desk form) in PowerShell with the Selenium module. I can get all different types of elements except dropdowns. I have inconsistently been able to get some of them by doing a Find-SEElement and using the -xPath, performing a click() and then doing a Find-SEElement again on the resultant drop down list, but this does not always work. The one I am working on at the moment looks like this:
$User = Find-SeElement -Driver $chrome -Timeout 30 -XPath "//span[@id='control-wrapper-mainForm-GroupBoxDesignerControl4']//tr[1]//td[2]"

I can confirm that I do find the element, but if I try to do anything except click on it I get the "element is not interactable" error. I was reading through some other forums, and someone suggested doing something like this:
$User = Find-SeElement -Driver $chrome -Timeout 30 -XPath "//span[@id='control-wrapper-mainForm-GroupBoxDesignerControl4']//tr[1]//td[2]"
$Value = 'Joe Smith'
$SelectElement = [OpenQA.Selenium.Support.UI.SelectElement]::new($User)
$SelectElement.SelectByValue($Value)

When I run this, however, I get the error "Element should have been select but was td". Googling this I have seen a number of threads and solutions for other languages such as Python and C#, but nothing specific to PowerShell. I am just looking for a consistent syntax to be able to grab a dropdown menu and select an item from the resultant list.


text:
Q: jQuery Isotope center expanded element I am using Isotope to layout a grid of blocks using the 'masonryHorizontal' layout mode. On click the selected box expands and re-adjusts the layout. What I want is to scroll the window so the expanded box is centered in the window horizontally. I have this working so that it scrolls to the expanded box, but it's not centered horizontally.
In my click function, I have the following:
setTimeout(function() {
var itemPosition = $this.parent().data('isotope-item-position');
    $('#page').scrollTo({ top:itemPosition.y, left:itemPosition.x}, 500);
}, 800);

I know I have to adjust the itemPosition.x, but can't seem to calculate the correct center. Any help is appreciated.
Edit: Here is a screenshot to reference

Need to center the expanded block


text:
Q: How to configure logstash to transfer data from MS-SQL server to elasticsearch I am trying to copy my table data from MSSQL server to elasticsearch, after going through some documents i wrote my config file for logstash, when i run the file from command prompt , i get this message :

"J_3a_.ELK.logstash_minus_6_dot_6_dot_2.logstash_minus_core.lib.logstash.pipeline.block
  in start_input"

  I have the MSSQL database in aws-RDS.

This is my conf file
input {
    jdbc {
        jdbc_driver_class => "com.microsoft.sqlserver.jdbc.SQLServerDriver"
        jdbc_driver_library => "J:\Java\sqljdbc_4.2\enu\jre8\sqljdbc42.jar"
        jdbc_connection_string =>
       "jdbc:sqlserver://skunestdevdb.czdnys4mper2.ap-southeast-
         2.rds.amazonaws.com;database=skudevusr;user=
       <my_username>;password=<my_password>"
        jdbc_user => "<my_username>"
        jdbc_password => "<myPassword>#"
        statement => "select * from product"
    }
}
output{
    elasticsearch{
      hosts => ["localhost:9200"]
      index => ["skunest_qa"]
    }
}

I cant seem to get what is wrong here, i have provided necessary details in the conf file, the command line stucks showing above message. I have tried removing the username and password from the connection string.
Help!!

A: Try this:
input {
jdbc {
    # SqlServer jdbc connection string to your database, productdb
    #  "jdbc:sqlserver://HostName\instanceName;database=DBName;user=UserName;password=Password"
    jdbc_connection_string => "jdbc:sqlserver://localhost\SQLExpress;database=productdb;user=sa;password=test@123"
    # The user you want to execute your statement as
    jdbc_user => nil
    # The path to your downloaded jdbc driver
    jdbc_driver_library => "C:/Program Files/sqljdbc_6.0/enu/jre8/sqljdbc42.jar"
    # The name of the driver class for SqlServer
    jdbc_driver_class => "com.microsoft.sqlserver.jdbc.SQLServerDriver"
    # Query for testing purpose
    statement => "SELECT * from product"
}
}
output {
    elasticsearch {
     hosts => ["localhost:9200"]
     index => "logstash-%{+YYYY.MM.dd}"
 }

   }


text:
Q: How do I identify CUTOFF frequency from my audio signal? I was able to recorded an audio signal through the MIC and i applied FFT and Hanning window function to it. Now I want to know how do I identify CUTOFF frequency from it to apply the High Pass Filter.
my sample rate = 8000 Hz, FFT block size = 256
Can anyone help me to identify this ? I would really appreciate it ! :)
Thanks!


text:
Q: SharePoint ReplaceContent="TRUE" I am trying to deploy pages to a pages library for the second time by activating a feature. The module has the attribute: ReplaceContent="TRUE".
When I deactivate the feature, everything goes fine. When I activate the feature, I receive an error that the pages are checked out to another user (which is my account, the same account am doing the activate process with), and I can't deploy the pages.
Do I need to have the pages checked in? even if am the same user who has them checked out?
Do I need to delete the page before activating the feature to deploy the new page?
Also if someone can tell me the difference between IgnoreIfAlreadyExists and ReplaceContent .
Thanks.

A: You don't need to delete the page.You just need to check in the page even if it is same account.
ReplaceContent allows you to overwrite the ghostable file.This is nw
IgnoreIfAlreadyExists=true
SharePoint doesn't freak out if the file already existed in the library but it never allowed us to replace the file.
Please find link below.
https://blogs.msdn.microsoft.com/how24/2013/06/14/overwriting-ghostable-files-in-sharepoint-2013-libraries-using-feature-elements-no-code/


text:
Q: Getting a prediction from an ONNX model in python I can't find anyone who explains to a layman how to load an onnx model into a python script, then use that model to make a prediction when fed an image. All I could find were these lines of code:
sess = rt.InferenceSession("onnx_model.onnx")
input_name = sess.get_inputs()[0].name
label_name = sess.get_outputs()[0].name
pred = sess.run([label_name], {input_name: X.astype(np.float32)})[0]

But I don't know what any of that means. And everywhere I look, everybody already seems to know what they mean, so nobody's explaining it. That would be one thing if I could just run this code, but I can't. It gives me this error:
onnxruntime.capi.onnxruntime_pybind11_state.InvalidArgument: [ONNXRuntimeError] : 2 : INVALID_ARGUMENT : Invalid rank for input: Input3 Got: 2 Expected: 4 Please fix either the inputs or the model.

So I need to actually know what those things mean so I can figure out how to fix the error. Will someone knowledgeable please explain?

A: Let's first start by going over the code you provided, to make everything clear.
sess = ort.InferenceSession("onnx_model.onnx")

This line loads the model into a session object. This means that the layers, functions and weights used in the model are made ready to perform inferences.
input_name = sess.get_inputs()[0].name
label_name = sess.get_outputs()[0].name

The two methods get_inputs and get_outputs each retrieve some meta information about the model, that being what inputs the model expects, and what outputs it can provide. Off of this meta information in these lines, only the first input & output is actually used, and off of these, only the name is being gotten, and saved into  variables.
For the last line, let's tackle that part by part.
pred = sess.run(...)[0]

This performs a inference on the model, we'll go over the inputs to this method after this, but for now, the output is a list of different outputs. These outputs are each numpy arrays. In this case only the first output in this list is being used, and saved to the pred variable
([label_name], {input_name: X.astype(np.float32)})

These are the inputs to sess.run. The fist is a list of names of outputs that you want to be computed by the session. The second argument is a dict, where each input's name maps to numpy arrays. These arrays are are expected to be of the same dimension as the ones supplied during creation of the model. Similarly the types of these arrays should also match the types used during creation of the model.
The error you encountered seems to indicate that the supplied array doesn't have the expected dimensions. These intended amount of dimensions seems to be 4.
To gain clarity about what the exact shape and data type of the input array should be, there are visualization tools, like Netron


text:
Q: How do I ensure the entire parent control is visible when a compound XAML control is Tab Selected? I have a compound XAML control. It looks like this:
<UI:CompoundControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Dynamics="clr-namespace:MyNamespace.UI" Height="Auto" >
    <Stackpanel Orietnation="Vertical">
        <TextArea x:Name="lblTop" DockPanel.Dock="Left">Label</TextArea >
        <TextArea x:Name="lblBottom" DockPanel.Dock="Left">Label</TextArea >
    </Stackpanel >
</UI:CompoundControl>

When the application runs, there is a UIElementCollection of these CompoundControls, which displays them in a scrollable list.
When I press the Tab key, the application moves focus to the next TextArea in sequence, scrolling the view to do so. However, it only scrolls to show the focused control, so I'm running into an issue where pressing Tab doesn't show the entirety of the CompoundControl, only the upper half.
Is there some attribute I can set so that the automatic scrolling shows the entire control, instead of simply the upper half?

A: Figured out a way to make it work by responding to the top control's "GotFocus" event. scrollViewer in this case is the parent ScrollViewer that the compound control gets added to.
private const int SCROLL_PADDING = 10;
private void lblTop_GotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
        {
            if (scrollViewer == null) return;
            FrameworkElement element = e.OriginalSource as FrameworkElement;
            var transform = element.TransformToVisual(scrollViewer);
            var positionInScrollViewer = transform.Transform(new Point(0, 0));

            //Scrolls the viewer down far enough to see this control + the control directly below it.
            if (positionInScrollViewer.Y < 0 ||
                positionInScrollViewer.Y + SCROLL_PADDING > scrollViewer.ViewportHeight)
            {
               scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset +
                    positionInScrollViewer.Y - SCROLL_PADDING);
            }

        }

This will scroll the ScrollViewer past the entirety of the compound control, but only if the top part of the compound control is off, or nearly-off, the screen.


text:
Q: Workaround for using alias in where clause:oracle10g I have a query like this:
select data.* from ((select table1.col1 as "a") union (select table2.col2 as "b")) data where 1 = 1
How can I add a where caluse to this if I wish to filter on column "a"? I understand that I cannot use the alias names, but how do I go about writing the where clause?
I tried:
select data.*
from (
   select table1.col1 as "a"
   union
   select table2.col2 as "b"
)
data where 1 = 1
 and data.a = 'someValue'

Also:

select data.*
from (
   select table1.col1 as "a"
   union
   select table2.col2 as "b"
) data
where 1 = 1
  and data.table1.col1 = 'someValue'

Both gave errors

A: In addition to what DBCookie as correctly said (I assume the missing from in the inner queries is just a copy & paste error):
The derived table with the alias data only has a single column which is determined by the column name of the first SELECT in the union. This column is called "a" (not a) and because of the quotes is now case sensitive.
If you don't insist on having a lower case column name, then simply leave out the quotes from the inner queries.

select data.*
from (
   select col1 as a
   from table1
   union
   select col2   --- you can leave out the alias here it's useless.
   from table2
)
WHERE data.a = 'someValue' -- I remove the 1=1 as it doesn't serve any purpose

If you insist on having the alias in quotes, you must use them in the WHERE clause as well:

WHERE data."a" = 'someValue'

But this will also filter out values that come from table2 and have 'someValue' in their col2. I'm not sure if this is what you intended. If you only want to filter out rows that come from table1 and have 'someValue' in col1, then you need to put that condition inside the union:

select data.*
from (
   select col1 as a
   from table1
   where col1 = 'someValue'
   union
   select col2
   from table2
) data

If you are sure there are no duplicates between table1 and table2 I recommend UNION ALL over UNION as it is faster then.

A: All selects in Oracle require a FROM clause:
select data.*
  from ((select 1 as a FROM dual) union
        (select 2 as b FROM dual)) DATA
 where 1 = 1
   and data.a = '1'

Substitute your table names for dual in my example (just used it for basic syntax and sanity checking).
Also, unless you need the alias to be lower case, it's easier to omit the double quotes from your aliases to avoid using double quotes everywhere you reference the alias.


text:
Q: Xamarin.iOS: How to add query parameters to HTML file with NSUrl? I have built a Xamarin.Forms app with a Hybrid Web View using this tutorial. My Hybrid Web View uses a local HTML file which contains JavaScript which renders the page.
Now my local HTML file takes in query parameters through JavaScript and I have successfully implemented this in my Xamarin.Android project using this snippet located in the Hybrid View Renderer:
if (e.NewElement != null)
{
    Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
    Control.LoadUrl($"file:///android_asset/Content/{Element.Uri}");
}

Where Element.Uri contains MyFile.Html?x=1&y=2&z=3 as a string. This loads my local HTML page perfectly.
I can't get the same success in my Xamarin.iOS project. For my Xamarin.iOS project, I am using this snippet, located in the iOS Hybrid View Renderer, to try and load my local HTML file:
if (e.NewElement != null)
{
    string fileName = Path.Combine(NSBundle.MainBundle.BundlePath, string.Format("Content/{0}", Element.Uri));
    NSUrl nsUrl = new NSUrl(filename, false);
    Control.LoadRequest(new NSUrlRequest (nsUrl));
}

When I run my app, the page renders nothing and no exceptions are thrown. I have debugged my code and noticed that nsUrl.AbsoluteString contains file:///path/to/MyFile.html%3Fx=1&y=2&z=3where the ? at the start of the query parameters have been encoded to %3F. I suspect this is the problem.
Is there a way to pass query parameters to a local HTML file in Xamarin.iOS? Or am I taking this approach the wrong way?
Thanks.

A: You can use NSUrlComponents with an array of NSUrlQueryItem elements to construct your NSUrl:
Example:
using (var contentBase = NSUrl.FromFilename(Path.Combine(NSBundle.MainBundle.BundlePath, "WebSite")))
using (var url = new NSUrlComponents
{
    Scheme = "file",
    Host = "localhost",
    Path = Path.Combine(NSBundle.MainBundle.BundlePath, "WebSite", "index.html"),
    QueryItems = new[] { new NSUrlQueryItem("x", "1"), new NSUrlQueryItem("y", "2"), new NSUrlQueryItem("z", "3") }
}.Url)
{
    webView.LoadFileUrl(url, contentBase);
}

Resulting NSUrl AbsoluteString output:
file://localhost/.../some.ios.app/WebSite/index.html?x=1&y=2&z=3


text:
Q: how to compile Rmarkdown file only until the error This is about rendering a Rmarkdown file containing errors.
I am aware that you can configure a Rmarkdown document with error=TRUE to keep compiling although an error is present, and it generates your html or pdf file.
However, I would like to find a way in which the compiling process stops in the error, and the posterior chunks are not run, but it still generates the html or pdf file from the output of the previous chunks.
Does someone know how to do it?
Thank you in advance!


text:
Q: Unable to run PHPUnit outside of tests folder So I have a CodeIgniter project and I'm trying to use PHPUnit with it. My directory looks something like
application
node_modules
Gruntfile.js
scripts
vendor
tests
    PostTest.php
    phpunit.phar
    bootstrap.php
    phpunit.xml
composer.json
package.json

When I'm inside of the tests folder, I can do "phpunit ." or "php phpunit.phar ." to run the tests inside of PostTest.php and that works fine, but when I'm in the root folder, and try doing "phpunit tests", I get the error:
ERROR: Not Found

    The controller/method pair you requested was not found.

PostTest.php
<?php
class PostTest extends PHPUnit_Framework_TestCase {
      private $CI;

      public function setUp() {
          $this->CI = &get_instance();
      }

      public function testNotes() {
        $this->CI->load->model('class');
        $students = $this->CI->class->getStudents('11');
        $this->assertEquals(3, count($students->result_array()));
      }
}

phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
    <phpunit bootstrap="bootstrap.php"
             colors="true"
             convertErrorsToExceptions="true"
             convertNoticesToExceptions="true"
             convertWarningsToExceptions="true"
             processIsolation="false"
             stopOnFailure="false"
             syntaxCheck="false"
             verbose="true">
    </phpunit>

Does anyone have any ideas why I'm getting that error?

A: Phpunit looks in the current directory for phpunit.xml, and descends into directories to find test files. So move this file to webroot and you should be sorted. Alternatively, you could specify the directory for tests to run in in the phpunit.xml and leave it where it is and add something like this (untested) to get it to include tests in webroot:
<testsuites>
    <testsuite name="My Test Suite">
        <directory suffix="Test.php">../</directory>
    </testsuite>
</testsuites>

https://phpunit.de/manual/current/en/appendixes.configuration.html


text:
Q: Insertion iterative approach to BST (C) I have the recursive approach figured out, but I can't seem to figure out how to iteratively insert an element in a BST. I don't need the answer just a little direction on how to go about solving the iterative approach. Thank you!
static NODE * insert(NODE *r, int x)  //recursive approach
{
    NODE *leaf;
    if(r == NULL)
    {
      leaf = malloc(sizeof(NODE));
      leaf->left = NULL;
      leaf->right = NULL;
      leaf->val = x;
      return leaf;
    }

    if(r->val == x)
        return r;

    if(x < r->val)
    {
        r->left = insert(r->left, x);
        return r;
    }
    else
    {
        r->right = insert(r->right, x);
        return r;
    }
}

static NODE *insert_i(NODE *r, int x) //iterative approach
{
    NODE *leaf;

    if(r == NULL)
    {
      leaf = malloc(sizeof(NODE));
      leaf->left = NULL;
      leaf->right = NULL;
      leaf->val = x;
      return leaf;
    }

}

A: static NODE * insert_i(NODE **rr, int x)
{
  while (*rr) {
    if((*rr)->val == x) break;
    rr = (x < (*rr)->val) ? &(*rr)->left : &(*rr)->right;
    }

  if(*r) return *r; /* duplicate */

  (*rr) = malloc(sizeof **r);
  (*rr)->left = NULL;
  (*rr)->right = NULL;
  (*rr)->val = x;
  return *rr
}

To be called like:
NODE *root=NULL, pp;
pp = insert_i( &root, 1234);


text:
Q: use isolate storage to save items in observablecollection I've created an app, everything done except save data when close app. In this app I use 2 ObservableCollections which is something like
public ObservableCollection<item1> list1 { get; private set; }
public ObservableCollection<item2> list2 { get; private set; }

Each item1 and item2 contains some element (string, int, colors ...)
Can I use a simple solution to use isolated setting to save 2 collections and read them when the app starts? I've searched Google but can't find an exact solution.


text:
Q: Xcode 7.0 update issue with Swift 2 I just faced an issue with my project written in Swift, when I updated my Xcode to the latest version; Xcode 7.0.
Xcode told me that I should convert my code to work with Swift's new syntax (Swift 2).
The problem is I could not understand how to solve some line of codes.
As an example: I'm using SwiftyJSON in my application and Xcode gives me this error you see below:
public struct JSON {

    public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
        if let object: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: opt, error: error) {
            self.init(object)
        } else {
            self.init(NSNull())
        }
    }

A: Some functions dropped some arguments and in this case the error pointer. instead it throws (which means you can call it only with try catch handling). here is swift 2.0 version of your code
public struct JSON
{

    public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil)
    {
        do {
            let object:AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt)
            self.init(data: object as! NSData)
        } catch {
            //error handling code
        }
    }
}


text:
Q: qt "resource" string I am wanting to have a place where i can store all the strings used in my applicaton, so i can modify them in one place and not all the places. Something like a resource file, where i can put a label on the strings and just call the label.
I am not aware of anything offered by QT for this, so would I just need to create a header file with all those strings and include it everywhere I need it? What is the appropriate way to do this and could you offer a small example?
Thanks!!

A: I haven't used it yet, but I think, that the Qt Internationalization would allow you to do something like this, since one of it's options is to take all strings out of the application code so they can be replaced by translations. Even if you don't want to use any other features of this module, it would allow you to solve your problem. Replacing a string for a label would look like this:
QLabel *label = new QLabel(tr("Password:"));

The tr() function is already part of the Qt classes and you get a few more functions and macros for free that help to search and replace strings.
The strings to be replaced can then be managed with QtLinguist.
You can find a more detailed explanation here: Internationalization with Qt

A: In the old days[1], when using Windows resources, people have been using:
// in your project_strings.h file
#define STRING_PASSWORD 1
...

// resources project.rc
#include "project_strings.h"
STRINGTABLE
BEGIN
STRING_PASSWORD "Password:"
...
END

// in some other file
#include "project_strings.h"
CString str(STRING_PASSWORD);

The CString knew about windows resources (ugly dependency) and could go and read the string password. The #define is definitively very ugly in modern C++, but resources would not understand a static const variable or an inline function.
The easiest way to replicate this in a somewhat similar way is to use a header file with string declarations and then reference those strings anywhere you need them.
// in your project_strings.h
namespace MyProjectStrings {
const char *password;
...
}

// the project_strings.cpp for the strings
#include "project_strings.h"
namespace MyProjectStrings {
const char *password = "Password:";
...
}

// some random user who needs that string
#include "project_strings.h"
std::string password(MyProjectStrings::password);

Now all your strings are in project_strings.cpp and you cannot as easily translate them with tr()... but you could transform all those strings declarations with functions:
// in your project_strings.h
namespace MyProjectStrings {
const char *password(); //[2]
...
}

// the project_strings.cpp for the strings
#include "project_strings.h"
namespace MyProjectStrings {
const char *password() { return QObject::tr("Password:"); }
...
}

// some random user who needs that string
#include "project_strings.h"
std::string password(MyProjectStrings::password()); //[3]

And Voilà! You have a single long table of all your strings in one place and translatable.
[1] Many people still use that scheme!
[2] The function could return std::string to 100% prevent modifying the original.
[3] In this last example the string reference uses () since it's a function call.


text:
Q: How do I add my own header in Keil? I have main.c and I want to include my header. I made header led.h (right click on user -> Add new item to Group User). But like on picture, it didnt appear. I only got new window where I can write my code for header, but I still cant include it in main (getting error led.h file not found). What I need to do, to get my header be visible in main.c?

A: By default, Keil does not show the header files in the project tree. You can show them by right clicking on the group and Add existing files to Group. This is only to display nicely your files, but this will not help you when you want to include the header in your c file.
To include led.h in your main.c file, you can try the following options:

*

*add the full path in your include for example #include "..\led.h"

*copy the led.h file in the same folder as the main.c file and include it #include "led.h"

*update your projects settings (Options for target -> C/C++ -> Include path) to add all your paths and include led.h #include "led.h"


text:
Q: Can we prove that if $\lim_{n \to \infty} a_n = c$, and $f$ is continuous, then $\lim_{n \to \infty} f(a_n) = f(c) $? Good day everyone,
I was wondering how we could say that if $\lim_{n \to \infty} a_n = c$, and f is continuous, then $\lim_{n \to \infty} f(a_n) = f(c) $
I found this in the bisection method used to prove Bolzano's theorem. Do you know if there is a theorem (and which) or a corollary that explains the above statement? Maybe the reason is obvious but I still do not get it; if anyone could help me I would be so grateful.
Thanks in advance!

A: Absolutely! There exists $\delta>0$ such that whenever $|x-c|<\delta$, we have $|f(x)-f(c)|<\epsilon$. Since $x_n\to c$, there exists $N\in\mathbb{N}$ such that whenever $n\geq N$, $|x_n-c|<\delta$. Therefore, for all $n\geq N$, $|f(x_n)-f(c)|<\epsilon$. This is what it means to say that $f(x_n)\to f(c)$.

A: you can show a if and only if, that is;
A function $f:A\subset \mathbb{R} \rightarrow \mathbb{R}$ is continuos at the $c \in A$ if and only if for every sequence $\left\{x_{n}\right\}$ in $A$ such that $\left\{x_{n}\right\} \rightarrow c$, the sequence $\left\{f(x_{n}\right\} \rightarrow f(c)$
proof.$\Leftarrow )$ Suppose that $lim_{x \to c}f(x)=f(c)$ it is false, that is:
$(\exists \epsilon >0)(\forall \delta>0)(|x-c|<\delta  \wedge \ |f(x)-f(c)| \geq \epsilon)$, hence some $n \in \mathbb{N}$ there is $x_{n}$ such that $|x_{n}-c|< \frac{1}{n}$ but $|f(x_{n}-f(c)|\geq\epsilon$, which implies that $\left\{f(x_{n}\right\} \nrightarrow f(c)$, the which is a contradiction.
Hence $f$ is continuos.


text:
Q: Does the 'private' access modifier give the compiler more room for optimization? Does it allow the compiler to inline it, knowing that only functions in the same class can access it? Or is it only for the programmer's convenience?

A: The compiler can (but is not required to) optimize as you suggest, but that's not the point.  The point of access modifiers is to catch certain classes (no pun intended) of programming errors at compile time.  Private functions are functions that, if someone called them from outside the class, that would be a bug, and you want to know about it as early as possible.
(Any time you ask the question "could the compiler make optimizations based on this information available to it", the answer is "yes, unless there's a specific rule in the standard that says it's not allowed to" (such as the rules for volatile, whose entire purpose is to inhibit optimizations).  However, compilers do not necessarily bother optimizing based on any given piece of information.  There is, after all, no requirement for compilers to do any optimization in the first place!  How clever your compiler is, nowadays, largely depends on how long you are willing to let it run; MSVC's whole-program PGO mode is capable of inlining through virtual method dispatch -- it guesses the most likely target, and falls back to a regular virtual call at runtime if the guess was wrong -- but slows down compiles by at least a factor of two.)

A: The access specifiers are a part of C++ mechanism to implement OOP principles of Encapsulation and Abstraction and not optimization for compilers.
Some intelligent compiler can possibly implement some optimization through it but it not enforced to do so by the C++ Standard. The purpose of access specifiers is not Optimization but to facilitate language constructs for principles supported by the C++ language.


text:
Q: Prove that $\limsup s_n \le\limsup t_n$ The question is:
Let $s_n$ and $t_n$ with $ n \ge 1 $ be two bounded sequences.
Assume that there exists a natural number $N$ such that for every $ n \ge N $, we have $ s_n \le t_n $.
Prove that $$ \lim_{n\to\infty} \sup s_n \le \lim_{n\to\infty} \sup t_n. $$
I think its obvious, but the part of proving it is kinda tricky.
Can someone please help?

A: One definition of $\limsup$ of a sequence $\{ r_{k} \}$ is as follows. Define
$$
              R_{n} = \sup \{ r_{n}, r_{n+1}, r_{n+2},\ldots \}.
$$
Whether finite or infinite,
$$
             R_{1} \ge R_{2} \ge R_{3} \ge ....
$$
converges downward to some finite or infinite limit defined as $\limsup_{n}r_{n}$. For and $n \ge N$, the least upper bound $T_{n}$ of $\{ t_{n},t_{n+1},t_{n+2},\ldots\}$ is an upper bound for $\{ s_{n},s_{n+1},s_{n+2}\}$ because $s_{k} \le t_{k}$ for $k \ge n \ge N$. Therefore the least upper bound $S_{n}$ of $\{ s_{n},s_{n+1},s_{n+2},\ldots\}$ must satisfy $S_{n} \le T_{n}$. So the argument is now reduced to the case of monotone sequences:
$$
   \limsup_{n} s_{n}  = \lim_{n} S_{n} \le \lim_{n} T_{n} = \limsup_{n} t_{n}.
$$
The infinite cases can be dealt with directly. If $\limsup_{n} t_{n}=\infty$, there is nothing to show. If $\limsup_{n} s_{n}=-\infty$, there is nothing to prove. In all other cases, both $\limsup$ terms are finite, and $\{ S_{n} \}$, $\{ T_{n} \}$ are non-decreasing, convergent sequences with $S_{n} \le T_{n}$ for $n \ge N$, a case which is assumed to be known.

A: I'll use the following property:

For a sequence $(a_n)_{n\in\mathbb N}$ the $\limsup a_n$ is  the largest limit point of $(a_n)_{n\in\mathbb N}$, where $a$ is a limit point if there is a subsequence $(a_{k_n})_{n\in\mathbb N}$ such that $\lim_{n\to\infty} a_{k_n}=a$.
Assume that $\limsup s_n>\limsup t_n$.
Then there is a subsequence $(s_{k_n})_{n\in\mathbb N}$ of $(s_{n})_{n\in\mathbb N}$ such that $\lim_{n\to \infty} s_{k_n}=\limsup s_n>\limsup t_n$.
Therefore $s_{k_n}>\limsup t_n$ for all large $n$ so $t_{k_n}>\limsup t_n$ for all large $n$.
Now find a subsequence of $t_{k_n}$ that converges ($t_{k_n}$ is bounded) to derive a condradiction.

A: On the contrary let $S = \limsup s_{n} > \limsup t_{n} = T$. Then by definition of $\limsup$ we have the following:
1a) For any $\epsilon > 0$ there are infinitely many values of $n$ for which $s_{n} > S - \epsilon$.
1b) For any $\epsilon > 0$ we have $s_{n} < S + \epsilon$ for all sufficiently large values of $n$.
2a) For any $\epsilon > 0$ there are infinitely many values of $n$ for which $t_{n} > T - \epsilon$.
2b) For any $\epsilon > 0$ we have $t_{n} < T + \epsilon$ for all sufficiently large values of $n$.
Put $2\epsilon = S - T > 0$ so that $T + \epsilon = S - \epsilon$. Now for all sufficiently large values of $n$ we have $t_{n} < T + \epsilon = S - \epsilon$ and hence $s_{n} \leq t_{n} < S - \epsilon$. This contradicts the fact that $s_{n} > S - \epsilon$ for infinitely many values of $n$. Hence we must have $S \leq T$.


text:
Q: SQL Report Builder 3.0 trying to check for nulls OR a date in a date range and received filter errors I am new to report builder and I am using it with SharePoint 2010 to create a report combining several lists. I have a dataset that has a datetime field column that I need to interrogate to limit the rows pulled back to the report. I thought a filter would do the trick... however I cannot seem to figure out the proper way to pull only what I need.
I need all rows where orderstatus is completed and date1 is empty or has been pushed out to 2015.
Example data:
ID  DATE1           OrderStatus
1   Empty           Completed
2   Empty           Not Started
3   12/01/2012      Completed
4   03/05/2013      Completed
5   08/21/2014      Completed
6   12/31/2014      Completed
7   01/07/2015      Completed
8   01/08/2015      Not Started
9   01/31/2015      Completed

In Group Properties I added the filter where OrderStatus (Text) = Completed and this works but I also need all rows with an empty date (or anything before 1960) or a date where the year is 2015 with orderstatus completed.
From the data above I expect to see in my report the following rows:
1, 7, and 9
Is there a better way to add the OR option and when I use the fx for the expression or the value I get rsfilter errors.
Here is the first filter:
 Expression    OrderStatus (Text)
 Operator       =
 Value             Completed

Here is the second filter I added: (this filter receives errors and will not process)
 Expression    Date1   (Date/Time)
 Operator       =
 Value [Expr]   =(Fields!Date1.Value) < 12/01/1960 Or (Fields!Date1.Value) > 12/31/2014

I have tried different methods with OrElse, Xor, IsNothing, multiple Ands' etc... at the query level the row and report level filtering but still get a similar result.
Can someone point me in the right direction to achieve my end goal? I have looked in Microsoft and their examples do not have a scenario of 1 column needing the empty and a date range included in the result set.
I have corrected the syntax errors above as directed but still have a RSFilterProcessError. I will look at other examples. the tool does not lend me to easily copy the filter code to paste here. All suggestions welcome.

A: I can see a syntax problem in these expressions:
Year(Fields!Date1.Value < 1960)
Year(Fields!Date1.Value = 2015)

You have the brackets in the wrong place. Year() is a function that accepts a date parameter and returns a year, which you then compare with a value.
Change them to:
Year(Fields!Date1.Value) < 1960
Year(Fields!Date1.Value) = 2015

A: I have had some difficulty trying to fit complex statements into Report Builder's filters. What has worked for me is to set the filter as Boolean and do the expression as an iif.
Expression:
=IIF(Year(Fields!Date1.Value) < 1960 OR Year(Fields!Date1.Value) = 2015, true, false)
Type:
Boolean
Operator:
 =
Value:
True


text:
Q: How to prevent a partition from being mounted [by dolphin]? I have a partition taking a whole separate drive that I use for backups. I don't want it to be automounted at startup or mounted by anything I'm not aware of because else it would kill the purpose of being protected against (amongst other things) rm -rf /. Here's a piece of my fstab:
#Backups
UUID=... /mnt/backups  ext4 nouser,noauto,ro,suid,dev,exec,async 0 2

This works with command line mount actions but as a normal user if I click on the drive in Dolphin it still gets mounted although while respecting read only mode, which makes it less harmful.
How can I totally prevent dolphin from doing its thing on its own with my partitions? I'm on a really fresh Kubuntu 14.04.
Note: I read this, but the asker said in a comment that he ran into the same issue.

A: Create a udev rules to ignore that hard drive.

*

*Check drive serial number, using Disks utility (GUI)

or using CLI:
udevadm info --attribute-walk --name=/dev/sdb

*Write a rule files
sudo nano /etc/udev/rules.d/90-hide-disks.rules
ATTRS{serial}=="0000000000", ENV{UDISKS_IGNORE}="1"

Replace 0000000000 with real drive serial number

*Reload/Trigger the new rules
sudo udevadm control --reload-rules
sudo udevadm trigger

References:

*

*Hide Your Disks Or Partitions From Nautilus (Quiet old)

*How to reload udev rules without reboot?

*How to Write udev Rules for USB Devices

*man udevadm & udevadm -h


text:
Q: How do I get all the distinct field values that satisfy a particular query in Elasticsearch? My sample document looks like this.
{
    "user": "dslfjd",
    "productLength": 68,
    "productPrice": 4500,
    "action": "Made Purchse"
}

I want to get all the users that brought products whose price is between 4000 and 10000 and whose length is between 50 and 100. The following query returns all the documents that satisfy the above conditions.
{
   "query": {
       "bool": {
           "must": [
               {
                   "term": {
                       "act": "Made Purchase"
                   }
               },
               {
                   "range": {
                       "productPrice": {
                           "gte": 4000,
                           "lte": 10000
                       }
                   }
               },
               {
                   "range": {
                       "length": {
                           "gte": 50,
                           "lte": 100
                       }
                   }
               }
           ]
       }
   }
}

Here I will get all the documents that satisfy the above query clauses, I can even project my response by just specifying "_source" = ["user"] so that I don't get the entire document but just the user
Instead what I want is a list of all the unique distinct users. Instead of all the documents that may have user field repeated.
An aggregation like below
{
    "aggs": {
        "unique_users": {
            "terms": {
                "field": "user"
            }
        }
    }
}

aggregates all the documents, instead I want aggregation on documents that satisfy any query. I feel like I'm missing a simple thing like defining my query inside my aggregation. But I don't know what it is.

A: It's too simple, or you need something else from what you described:
GET /some_index/some_type/_search?search_type=count
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "action": "Made Purchase"
          }
        },
        {
          "range": {
            "productPrice": {
              "gte": 4000,
              "lte": 10000
            }
          }
        },
        {
          "range": {
            "productLength": {
              "gte": 50,
              "lte": 100
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "unique_users": {
      "terms": {
        "field": "user"
      }
    }
  }
}


text:
Q: Sum Of Total Time Taken Of Timer I am making a game.
Lets say that it has 2 levels.
I have a TIMER in both which works properly. The code for timer:
public Timer t;
public int TimeCounter = 0;
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        runOnUiThread(new Runnable() {
            public void run() {
                TextView t = (TextView)findViewById(R.id.txtcount);
                t.setText(String.valueOf(TimeCounter));
                TimeCounter++;
            }
        });
    }
}, 1000, 1000);

Now in my 3rd activity i want the total time (Adding the first activity's and second activity's time taken) to be shown.
Also, I want to save the time the user took as the high score.  And then when the user takes less time than the highest score,  the previous will get deleted and the new will be saved
I would appreciate your help.Thanks

A: Make TimeCounter static
public static int TimeCounter = 0;

Now you can increment it in both of your activities like (in second activity it will retain values from first activity)
ActivityOne.TimeCounter++;

Wherever you want to get its value you can get it easily.


text:
Q: How to target dialog buttons/Add ids I have a modal dialog. I want one button to be disabled and then later enabled. I plan to do this by adding an id to the button and then using that id to use the add/remove attribute disabled. If there is another way I am open to suggestions. Here is some sample code:
$('#navDialog').dialog({
        modal:true,
        autoOpen:false,
        height: 'auto',
        width: 'auto',
        title: "Category Editor",
        buttons: {
            "Delete": function(){somethingMore();},
            "Edit": function(){something();},
            "Confirm":function(){importantSomething();}
        },
        draggable: true,
        resizable: false
    });

I want to be able to control the Confirm button.

A: $('#navDialog').dialog({
    modal:true,
    autoOpen:false,
    height: 'auto',
    width: 'auto',
    title: "Category Editor",
    buttons: [{
        id:"btn-delete",
        text:"Delete",
        click:function(){somethingMore();}
    },{
        id: "btn-edit",
        text:"Edit",
        click: function(){something();}
   },{
        id:"btn-confirm"
        text:"Confirm",
        click:function(){importantSomething();}
    }],
    draggable: true,
    resizable: false
});

A: You can try this:
$('.ui-dialog-buttonpane button:contains(Ok)').hide();

A: There currently isn't any proper way of doing this. It's on the roadmap for inclusion but I don't exactly know when. I'll report back when I've found the forum post detailing this issue.


text:
Q: Why external function can't navigate other javascript file in React? I'm making simple app which contains Todo App.
However, the function which locate in outside of main function(Is this expression right?) in same Javascript file can't navigate to other screen.
Below is my Screen structure(simplified)
<Stack.Screen name="Myqtwrite" component={MyqtwriteScreen} options={{headerShown: false}} />
<Stack.Screen name="Myqtupdate" component={MyqtupdateScreen} options={{headerShown: false}} />

And the problem is below.
I expressed the location of problem.
MyqtwriteScreen.js
export function Note(props, {navigation, route}) {
return (
    <View style={[styles.myblock, {backgroundColor:props.val.color}]}>
        <View style={{alignItems:'flex-start'}}>
            <View style={{borderBottomWidth:2,borderColor:'white',marginBottom:5}}>
                <Text style={[styles.myblocktitle]}>{props.val.date}</Text>
            </View>
            <Text style={styles.myblocktext}>{props.val.note}</Text>
        </View>
        <View style={{width: '100%' ,flexDirection:'row',justifyContent:'flex-end'}}>
/* problem is here-->  */   <TouchableOpacity onPress={() => {navigation.navigate('Myqtupdate') }} style={{marginTop:5,marginLeft:10}} >
                <Text style={styles.myblockbuttontext}>UPDATE</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={props.deleteMethod} style={{marginTop:5,marginLeft:10}} >
                <Text style={styles.myblockbuttontext}>DELETE</Text>
            </TouchableOpacity>
        </View>
    </View>
);

}

export function MyqtwriteScreen({ navigation, route }) {

const [noteArray, setNoteArray] = useState([]);
const [noteText, setNoteText] = useState('');

let rdcolor = 'hsl('+Math.random()*255+','+ Math.random()*(60)+10+'%, 82%)';

let notes = noteArray.map((val, key) => {
    console.log('start');
    return <Note key={key} keyval={key} val={val}
        deleteMethod={() => deleteNote(key)} />
});
const addNote = () => {
    if (noteText) {
        var d = new Date();
        noteArray.unshift({
            'date': d.getFullYear() +
                "Y " + (d.getMonth() + 1) +
                "월 " + d.getDate() + "일 " + d.getHours() + "시 " + d.getMinutes()+"분",
            'note': noteText,
            'color': rdcolor,
        });
        setNoteArray(noteArray);
        setNoteText('');
        // alert('큐티 입력을 완료했습니다.');
    }
    else {
        alert('큐티를 입력하세요');
    }
};
const deleteNote = (key) => {
    const newArray = [...noteArray];
    newArray.splice(key, 1);
    setNoteArray(newArray);
};

return (
    <View style={styles.container}>
        <View style={styles.topbar}>
            <Text style={styles.topbartext}>오늘의 큐티</Text>
            <Icon style={styles.topbarmenu} name="close" onPress={() => { navigation.navigate('My') }} />
        </View>
        <View style={styles.qtinputblock}>
            <TextInput
                onChangeText={(noteText) => setNoteText(noteText)}
                value={noteText}
                placeholder='큐티를 입력하세요'
                placeholderTextColor='gray'
                multiline={true}
                style={styles.qtinputtext}
            />
            <TouchableOpacity onPress={addNote} style={styles.myblockbutton}>
                <Text style={styles.myblockbuttontext}>추가</Text>
            </TouchableOpacity>
        </View>

        <ScrollView style={styles.scroll}>
            <View style={{alignItems:'flex-start'}}>
                {notes}
            </View>
        </ScrollView>

    </View>
);

}

I made 'MyqtupdateScreen.js' file of course.
The most interesting thing is that when I wrote same onPress={() => {navigation.navigate('Myqtupdate') }} in some TouchableOpacity in the 'function MyqtwriteScreen({navigation, route'})' , it works!!
I don't understand why navigation.navigate('Myqtupdate') doesn't work in export function Note, but works in export function MyqtwriteScreen.
Any words would be help!

A: Note doesnt get a navigation prop you will have to pass it like below
 return <Note key={key} keyval={key} val={val} navigation={navigation} deleteMethod={() => deleteNote(key)} />

It works on the other screen as its part of the stack.
You can also use the useNavigation hook to get access to navigation.


text:
Q: Can a dynamic table be returned by a function or stored procedure in SQL Server? I would like to call a stored procedure or user-defined function that returns a dynamic table that is created via a pivot expression. I don't know the number of columns up front.
Is this possible? (I am not interested in temporary tables)

A: You can do that via stored procedure as it can return any kind of table, question is what are you trying to achieve and what will you do with data that you have no idea about?

A: This cannot be done with functions (as the returned table structure must be pre-defined), but it can be done with a stored proceed. Some psuedo-code:
CREATE PROCEDURE Foo

As

DECLARE @Command

SET @Command = 'SELECT * from MyTable'

-- For debugging, work in an optional PRINT @Command statement
EXECUTE (@Command)

RETURN 0

When you run stored procedure Foo, it builds your query as a string in @Command, and then dynamically executes it without knowing anything about what is being queried or returned, and the data set returned by that EXECUTE statement is "passed back" to the process that called the procedures.
Build your query with care, this stuff can be really hard to debug. Depending on your implementation, it might be a source of SQL injection attacks (remember, the stored procedure really doesn't know what that dynamic query is going to do). For quick stuff, EXECUTE() works fine, but for safer and more useful (if elaborate) solutions, look into sp_ExecuteSQL.

A: Yes, you can do this from a Stored Procedure, but not from a user-defined Function. It is worth looking into the Table Value Function, I believe you can also return a dynamic table from there, but I have not used that myself.


text:
Q: Hide a button if non of Checkbox is checked on a table I have a table with checkbox at the beginning of a row. I have a button that is hidden. If I check one checkbox the button shows. If I uncheck it, the button hides. It works fine. My problem is, if I have all checkboxes "checked" and uncheck one checkbox from those checked ones, the button hides. It should not hide because there are still checkboxes checked. How am I going to fix this?
Here is my code
Script:
$('table').on('change', ':checkbox', function(){
    if (!this.checked)
    {
        $('#delete').hide();
    }

    else
    {
        $('#delete').show();
    }

});

Html:

                    <input type ="checkbox" id = "chkall">
                    Type
                    Brand
                    Description
                    Serial No
                    Asset No
                    Date of Purchased
                    Warranty Expiration
                    Status

                    <input type ="checkbox">
                    Keyboard
                    HP
                    One time use keyboard
                    123456
                    789456
                    July 5, 2019
                    August 6, 2015
                    Available

                    <input type ="checkbox">
                    Keyboard
                    HP
                    One time use keyboard
                    123456
                    789456
                    July 5, 2019
                    August 6, 2015
                    Available

                    <input type ="checkbox">
                    Keyboard
                    HP
                    One time use keyboard
                    123456
                    789456
                    July 5, 2019
                    August 6, 2015
                    Available

                    <input type ="checkbox">
                    Keyboard
                    HP
                    One time use keyboard
                    123456
                    789456
                    July 5, 2019
                    August 6, 2015
                    Available

                    <input type ="checkbox">
                    Keyboard
                    HP
                    One time use keyboard
                    123456
                    789456
                    July 5, 2019
                    August 6, 2015
                    Available

A: You can check whether at least one checkbox is checked like

$('table').on('change', ':checkbox', function() {
  $('#delete').toggle(!!$('input:checkbox:checked').length);
});

delete

      <input type="checkbox" id="chkall">

    Type
    Brand
    Description
    Serial No
    Asset No
    Date of Purchased
    Warranty Expiration
    Status

      <input type="checkbox">

    Keyboard
    HP
    One time use keyboard
    123456
    789456
    July 5, 2019
    August 6, 2015
    Available

      <input type="checkbox">

    Keyboard
    HP
    One time use keyboard
    123456
    789456
    July 5, 2019
    August 6, 2015
    Available

      <input type="checkbox">

    Keyboard
    HP
    One time use keyboard
    123456
    789456
    July 5, 2019
    August 6, 2015
    Available

      <input type="checkbox">

    Keyboard
    HP
    One time use keyboard
    123456
    789456
    July 5, 2019
    August 6, 2015
    Available

      <input type="checkbox">

    Keyboard
    HP
    One time use keyboard
    123456
    789456
    July 5, 2019
    August 6, 2015
    Available


text:
Q: How can I get the last descendant element using jQuery? OK, this should be super low hanging fruit.
I'm aware of .last() and yet for some reason my copy of jquery-min (version 1.4.2) is returning a .last is not a function() error when I call $('form#demo td').last() on the following markup:
<form id="demo">

    1
    2
    3

</form>

even though a call to $('form#demo td') returns
[td, td, td.action]

at the firebug console in Firefox 3.5.5.
What am I missing?

A: use $('form#demo td:last') instead.
the way you were doing it just returns an array, and jquery doesn't seem to define last() for arrays. You're right that it's in the jQuery api docs, but I've personally never gotten it to work that way.

A: try
$('form#demo td:last')

edit:
I think your problem is you got a broken html structure there...
I tested your code and got the error... but got it fixed by getting the correct structure..
here is a demo


text:
Q: Text Field Troubleshooting in Swift As practice, I am trying to create a simple math app in which one can input two values as the bases of a right triangle and when they press a button the 3rd leg is calculated. This is the code I am using:
class pythagoreanTheoremViewController: UIViewController {
    @IBOutlet weak var baseOneTextField: UITextField!
    @IBOutlet weak var baseTwoTextField: UITextField!
    @IBOutlet weak var answerLabel: UILabel!

    var a = baseOneTextField.text.toInt()
}

However, this returns the error that pythagoreanTheoremViewController.Type does not have a member named 'baseOneTextField'. I deleted and then reconnected my outlets and I still have the same problem.
What am I doing wrong and how do I fix it?
Thanks

A: The problem is that your var a declaration is positioned at the top level of your class, so it is an instance variable. But an instance variable's initialization cannot refer to another instance variable (baseOneTextField), because the object is not yet formed at initialization time - forming the object is exactly what we are in the middle of doing.


text:
Q: Angularjs filter limit to include two params I want to use it just as limitTo(input,begin,end)?
How to set the begin index?

A: On Version 1.4
As highlighted by @doldt Angular 1.4 now added the feature to indicate the begin of and end of in the limit:
{{ limitTo_expression | limitTo : limit : begin}}

https://code.angularjs.org/1.4.0/docs/api/ng/filter/limitTo
Previous version 1.4
Angular limitTo does not support more than one argument:
{{ limitTo_expression | limitTo : limit}}

The filter limitTo creates a new array or string containing only the specified number of elements in the limit argument.
Therefore the recommended option is to create a custom filter.
For example here is an Online Demo and this is how you can do it:
Please note that the first argument of the filter is the "Data Source" ( the entire list). It is the purpose of the filter to filter the Data Source.
HTML Sample

{{row.name}}

Js App and filter creation
var myApp = angular.module('myApp',[]);

myApp.filter('myFilter', function() {
        return function(items, begin, end) {

            return items.slice( begin, end);
        }
    });

function myCtrl($scope)
{
    $scope.friends = [
      {name:'John', age:25, gender:'boy'},
      {name:'Jessie', age:30, gender:'girl'},
      {name:'Johanna', age:28, gender:'girl'},
      {name:'Joy', age:15, gender:'girl'},
      {name:'Mary', age:28, gender:'girl'},
      {name:'Peter', age:95, gender:'boy'},
      {name:'Sebastian', age:50, gender:'boy'},
      {name:'Erika', age:27, gender:'girl'},
      {name:'Patrick', age:40, gender:'boy'},
      {name:'Samantha', age:60, gender:'girl'}
    ];
}

myApp.controller('myCtrl',myCtrl);

A: Create your own filter to achieve this. Try below,
app.filter('limitFromTo', function(){
    return function(input, from, to){
        return (input != undefined)? input.slice(from, to) : '';
    }
});

Usage:
{{ limitTo_expression | limitFromTo : from : to}}

A: You may achive the disired result by sequential application of limitTo filter to the array.
Say you want to extract items from 4 to 9:
HTML:
{{ someArray | limitTo: to | limitTo: from}}

JS
var from = 4;
$scope.to = 9;
$scope.from = from - $scope.to; // This value must be a negative