Q:

How to execute Python program within @app.route without 405 error?

I am trying to execute this python back end program once I reach the handle data page. Why are the methods returning a 405 Method Not Allowed error?
In the past, I've tried changing the position of the python to outside of the @ decorator and the methods=["POST"] condition
Python
import random
import requests
import time
from datetime import date
import sys
import re
import json
from bs4 import BeautifulSoup
from flask import Flask, render_template, jsonify

app = Flask(__name__)

@app.route("/")
@app.route("/home")
def home():
    return render_template('home.html')

@app.route("/handle_data")
def handle_data():
        userName = requests.form['username']
        listName = requests.form['listname']

        full python code is here

        randomNumber = randint(0,len(nameList)-1)
        films = nameList[randomNumber]
        return render_template('home.html', films=films)
if __name__ == '__main__':
    app.run(debug=True)

...
HTML
<form action="{{ url_for('handle_data') }}" method="POST">
<form>

      <input type="text" size=15 name=username class="form-control" placeholder="Username">

      <input type="text" size=15 name=listname class="form-control" placeholder="List Name">

<input type = "submit" class="buttonclass" value = "Random!" />

</form>

I expect the program to run the requests from the form through the program and return the random list item in form of the variable "films" but I receive a 405 error.
If you need more info, please notify

A:

@app.route("/handle_data") registers the route only for GET requests.  If you want POST too, you need to ask for it explicitly:
@app.route("/handle_data", methods=['GET', 'POST'])
def handle_data():
    # your code here

or:
@app.route("/handle_data", methods=['GET'])
def handle_get_data():
    pass

@app.route("/handle_data", methods=['POST'])
def handle_post_data():
    pass

More here: http://flask.pocoo.org/docs/1.0/api/#url-route-registrations


Q:

Making bounties more useful

I don't find bounties to be very useful on this site. There tends to be two kinds of users, those with thousands of reputation points and those with a few hundred or less. We'll call them the 'haves' and the 'have-nots'. Bounties don't really entice the 'haves' because they don't need the rep. And, since most bounties are for a few hundred reputation points, they don't have much of an impact on the have-nots. Furthermore the have-nots are disinclined to offer bounties which would otherwise be a good tool for getting their question more attention.
A possible solution would be to offer some, possibly temporary, moderator capabilities instead of just rep points. But whatever the case, I believe that the bounty system does not work properly. Do others agree and if so what can/should be done about it?

A:

I would be more inclined to offer bounties if the rep didn't go down the drain when the question gets no takers.  That's what happened to me on the single bounty I offered (on what I thought was a reasonable question).


Q:

Exclude results from List Comprehensions in Elixir

I have a simple list comprehension:
for x <- [some_list] do
  case _compute(x) do
    nil -> nil # directly exclude this value from output
    val -> val # add this value to output as usual
  end
end

Short of running the whole comprehension, and then filtering out nil values, is there a better was to do this?

A:

Comprehensions support filters, generators, pattern matching and multiple clauses built-in.
Filter nil values:
for x <- list, !is_nil(x), do: x

Call a new function on each value (and automatically filter nil):
for x <- list, y = _compute(x), do: y

Example:
iex> list = [1, 2, 3, nil, 4, 5, 6, nil, 7, 8, nil, 9, nil, 0]
iex> for x <- list, !is_nil(x), do: x
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

iex> compute = fn x -> if x > 5, do: x end
iex> for x <- list, y = compute.(x), do: y
# => [6, 7, 8, 9]


Q:

Can not store the result of a get call using Fetch-node

I am using Fetch-node for a GET to a service.
 const response = await fetch("MY URL", {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      }).then(res => res.json()).then(json => console.log(json));
      console.log(response);

I log the result in the second console.log() then and everything is fine.
However, when it comes to the second console.log() the response is undefined.
What I need is whatever is logged in the second to be stored in the response.
Is there anything wrong with what I am doing?

A:

As mentioned, you're not returning a value for response, therefore it won't be equal to anything. You could return the JSON from your final then, or if you felt it was any cleaner, just await both instead of using .then at all.
const response = await fetch("MY URL", {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000
      });

const json = await response.json();

console.log(json);


Q:

Different owners of apps in /Applications depending on installation technique

I have noticed that pre-installed as well as apps installed from the App Store located in /Applications show permissions like this:
drwxr-xr-x+  3 root     wheel  102 Jan  1  2014 Mail.app
whereas apps installed by drag-and-drop into the same folder look like this:
drwxr-xr-x@  3 johndoe  admin  102 Jan  1 15:55 Steam.app
Why do these apps depending on the installation technique get assigned different owners and groups? I am using a standard user account for installation (johndoe) if that's important. Also, why would it be a bad idea to change the owner of every app to root as is mentioned for example in Homebrew's FAQs:

Did you chown root /Applications/TextMate.app? Probably not.

-- Homebrew FAQs

A:

If an app is digitally signed, then the owner will be assigned to the System. As this is a requirement for apps distributed through the Mac App Store, then the apps that you see from there will likely be owned by the system and not you.
With apps that you download directly from a vendor, then they may or may not digitally sign their apps, in which case upon installation, you may or may not be the owner. Digital signing provides different privileges to how the app can interact with parts of the OS, like getting beyond the firewall without an annoying popup to the user every time, so you may see even developer downloaded apps signed.
Be careful of taking ownerships of signed apps, as this can corrupt the digital signature and you may be force to reinstall the app.


Q:

Restar datos entre tablas si coincide X elemento

La explicacion es un poco larga pero quiero hacerme entender con el problema lo mas detallado posible.
Tengo 4 tablas, 2 indican la informacion de material usado y material devuelto (Transacciones y Devoluciones) y las otras 2 tablan detallan que material se uso o se devolvio (Trans_det1 y Devol_det1)
Cada material que se utiliza o no viene detallado por boletas, que estan vienen detallas por ordenes de trabajo, un ejemplo:
Tengo las siguientes sentencias:
--REGISTRO DE INGRESO
SELECT*FROM Transa WHERE orden='GORE-999888'

--REGISTRO DE DEVOLUCIONES
SELECT*FROM Devol WHERE orden='GORE-999888'

Me devuelve esto:

La tabla Transame devuelve todas las boletas que se usaron para esa orden y Devol tambien pero me muestra las boletas que se usaron para devolver material.
DETALLES DE MATERIALES
--LO QUE SE USO
SELECT Transa_det1.boleta, Transa_det1.rollo, Transa_det1.cantidad FROM Transa_det1,Transa
WHERE Transa.boleta=Transa_det1.boleta AND orden='GORE-999888'

--LO QUE SE DEVOLVIO
SELECT Devol_det1.boleta, Devol_det1.rollo, Devol_det1.cantidad FROM Devol_det1, Devol
WHERE Devol_det1.boleta=Devol.boleta AND orden='GORE-999888'

Me devuelve esto:

Aqui me devuelve los rollos que se usaron en las boletas de la orden XXXX y cuanto se uso, la segunda tabla me muestra la cantidad de rollos que se devolvio.
Viene mi pregunta, para el rollo RT0102estoy usando 100.5pero despues devolvi 100al final lo que realmente use fueron 0.5, igual para RT0103 use 250 pero despues devolvi 50, existe una forma de hacer la resta si rollos coinciden mientras sean de la misma orden todo en un solo query? osea que me devuelva de una vez:
RT0103 0.5
RT0102 200
FH0091 465.75 //ESTE QUEDA IGUAL PORQUE NO DEVOLVI MATERIAL DE ESTE

(Otra opcion que estoy pensando es recuperar cada tabla en un DataTable C# y despues realizar algun tipo de resta para colocar el resultado en una nueva Datatable)

A:

Al final me sirvio este codigo:
SELECT td.boleta,
       td.rollo,
       ( td.cantidad - Isnull(c.ret, 0) ) AS Total
FROM   transa_det1 td
       INNER JOIN transa ta
               ON ta.boleta = td.boleta
       OUTER apply (SELECT top 1 d1.cantidad AS Ret
                    FROM   devol_det1 d1
                           INNER JOIN devol d
                                   ON d1.boleta = d.boleta
                    WHERE  d1.rollo = td.rollo and d.orden=ta.orden)c
where ta.orden = 'GORE-999888' //el orden puede cambiar

Que me devuelve esto:


Q:

Using SELECT to assign interdependent variables in SQL Server

I have a rather long stored procedure which accepts input parameters, performs calculations and manipulations in accordance with a series of conditions, and then returns output parameters.
The problematic section is a SELECT statement which assigns values to multiple variables within the stored procedure, but these values are interdependent.
SELECT @varX = CASE WHEN @REC_CHANGE = 1 THEN VT.X ELSE @varX END
      ,@varY = CASE WHEN @REC_CHANGE = 1 THEN VT.Y ELSE @varY END
      ,@varZ = CASE WHEN @REC_CHANGE = 1 THEN VT.Y * VT.X ELSE @varX END
FROM VarTable VT
WHERE VT.ID = @myID
AND <....>

The @REC_CHANGE variable determines if the record to be examined is different than the user input values.  If so, then we want the query to assign the value from the table. If not, then we want to keep the user input value.
The problem I'm encountering is that the first variable, @varX, always takes the user input value rather than reassigning the value from the table, even if the other variables just after it do take the values from the table. For example, @varY does pull the new value from the table when @REC_CHANGE = 1, but @varX does not. These values both come from the same table, from the same row with the same ID that is indicated in the WHERE clause.
As you can see, the condition of @REC_CHANGE does not differ between the assignments, so I'm having trouble understanding why @varX would stay the same (the user input value), while @varY gets updated accordingly.  Moreover, because the later assignments are dependent upon @varX, they sometimes return false values.
I would appreciate any pointers you guys might provide.  Thanks a ton in advance!
EDIT: As a note, I've checked what happens if I separate the @varX assignment into its own SELECT or SET statement with the exact same conditions, and the value updates accordingly.  That is to say that the query looks like this:
SELECT @varX = CASE WHEN @REC_CHANGE = 1 THEN VT.X ELSE @varX END
FROM VarTable VT
WHERE VT.ID = @myID
AND <....>;

SELECT @varY = CASE WHEN @REC_CHANGE = 1 THEN VT.Y ELSE @varY END
      ,@varZ = CASE WHEN @REC_CHANGE = 1 THEN VT.Y * VT.X ELSE @varX END
FROM VarTable VT
WHERE VT.ID = @myID
AND <....>;

This returns the correct results, which leads me to wonder if SQL Server can't handle interdependent variables of this type?

A:

What you're trying should work. Here's a self-contained example that I've tested on SQL Server 2008 and it delivers the expected result. I would consider that it might be another element of your query that is causing the unexpected behaviour.
DECLARE @REC_CHANGE AS bit
DECLARE @myID AS int
DECLARE @varX AS int
DECLARE @varY AS int
DECLARE @varZ AS int

SET @REC_CHANGE = 1
SET @myID = 1
SET @varX = 2
SET @varY = 3

SELECT @varX = CASE WHEN @REC_CHANGE = 1 THEN VT.X ELSE @varX END
  , @varY = CASE WHEN @REC_CHANGE = 1 THEN VT.Y ELSE @varY END
  , @varZ = CASE WHEN @REC_CHANGE = 1 THEN VT.Y * VT.X ELSE @varX END
FROM
(SELECT 1 AS ID, 5 AS X, 6 AS Y)
AS VT
WHERE @myID = VT.ID

SELECT @varX, @varY, @varZ

I'd suggest testing testing the above code in your environment. If it works then it might be worth looking at the other elements of your query and tables.
One possible solution would be to assign the user input parameters to 'dummy' parameters at the start of the query. so like:
DECLARE @varXb AS int
SET @vaxXb = @varX


Q:

RecyclerView list ended listener

I have RecyclerView and I wish to download more data when my list ended.
In ListFragment I had this code:
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount;
    if (loadMore && !getLoaderManager().hasRunningLoaders()) {
        getLoaderManager().restartLoader(LOADER_ID);
    }
}

What should I use with RecyclerView to get the same result?

A:

In Adapter class I wrote this code
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
    Item item = mItems.get(position);
    viewHolder.Text.setText(item.getTitle());

    if (position == mItems.size() - 1) {
        mListener.onListEnded();
    }
}


Q:

How to debug ElasticBeanstalk error "X% of the requests are failing with HTTP 5xx"

My problem is similar to AWS: None of the Instances are sending data but has a slightly different error message.
I have a Rails application running on ElasticBeanstalk, and it appears to be running correctly. Periodically, Enhanced Health Monitoring sends me error messages such as:

Environment health has transitioned from Ok to Degraded. 20.0 % of the
  requests are failing with HTTP 5xx.

where the percentage varies up to 100%. Even though I've made no changes, a minute later I get a followup message telling me that everything is back to normal:

Environment health has transitioned from Degraded to Ok.

I've downloaded the full logs from ElasticBeanstalk but I don't know exactly where to look (there are around 20 different log files in various directories).
I'm currently using the free AWS tier with the smallest instances of database, server, etc. Could this be the cause? Which of the log files should I be looking in, and what should I be looking for?

A:

I run rails apps on Elastic Beanstalk and have found it helpful to think about Beanstalk as a computer (in this case an Amazon EC2 instance) running your rails app and a web server (either Passenger or Puma). When you get a 500 error, it could be because your rails app didn't properly deploy–in which case Passenger or Puma will return an error—or your app is deployed properly but encountered an error just like it might on your local machine.
In either case, to diagnose an error, download the full logs from your AWS console (open the correct app environment and then choose Logs > Request Logs > Full logs > Download). Deployment errors are harder to diagnose, but I recommend starting by looking in var-XX/logs/log/eb-activity.log. I suspect your error is coming from your rails app itself, in which case I recommend looking in var-XX/app/support/logs/passenger.log and production.log. To find a 500 error, search for "500 Internal" and then treat the error like you would any other rails error.

A:

You can go to the EC2 instance and run the application just like you would run on your local machine and see the logs.
You can ssh into your EC2 instance using the command eb ssh and go to /opt/python/ directory (It will be different for Ruby or other programming languages).
/opt/python/run is the directory where you will find the version of your application which is run from the EC2 instance. Look for the directory venv and app inside run directory.
Note: The above folder structure is for Python but a similar folder structure post deployment can be found for any other programming language. Just look for the standard directory structure for the deployment environment for your programming language.
For Python:
/opt/python: Root of where you application will end up.
/opt/python/current/app: The current application that is hosted in the environment.
/opt/python/on-deck/app: The app is initially put in on-deck and then, after all the deployment is complete, it will be moved to current. If you are getting failures in your container_commands, check out out the on-deck folder and not the current folder.
/opt/python/current/env: All the env variables that eb will set up for you. If you are trying to reproduce an error, you may first need to source /opt/python/current/env to get things set up as they would be when eb deploy is running.
/opt/python/run/venv: The virtual env used by your application; you will also need to run source /opt/python/run/venv/bin/activate if you are trying to reproduce an error.


Q:

Python heapq : How do I sort the heap using nth element of the list of lists?

So I have lists of lists getting added to the heap; eg:
 n = [[1, 5, 93],
     [2, 6, 44],
     [4, 7, 45],
     [6, 3, 12]]

 heapq.heapify(n)
 print(n)

This compares and sorts according to the list's first element.
My question is, how do I sort the heapq so it compares the third element of each list? For example, the above list would be accessed from the heapq in this order:
[[6, 3, 12],
 [2, 6, 44],
 [4, 7, 45],
 [1, 5, 93]]

A:

heapq doesn't support a key function for it's ordering so you will need to manipulate your data structure. Mapping your list to a tuple(sort_value, list) will allow you to do log(n) push and pop:
 In []:
 q = [(x[2], x) for x in n]
 heapq.heapify(q)
 heapq.heappop(q)

 Out[]:
 (12, [6, 3, 12])

 In []:
 l = [2, 5, 1]
 heapq.heappush(q, (l[2], l))
 heapq.heappop(q)

 Out[]:
 (1, [2, 5, 1])

Alternatively, define your own list and implement the comparison function for that list:
class MyList(list):
    def __lt__(self, other):
        return self[2] < other[2]

q = [MyList(x) for x in n]

Note: you should implement the other comparison functions (see functools.total_ordering on how to do that easily).


Q:

In c how can I detect if any bit of a byte equal 0

I was able to check for 1's using (x && 0xf), but I have no idea how to detect 0's.
check_zeros(int y){

} //return 1 if 0 is found

A:

You could do this:
int check_zeros(int y) {
    return (y & 0xff) != 0xff;
}

The 0xff represents a byte with all bits set to 1.


Q:

Keep only one occurrence of substring in a string

I'm looking for a function that removes all occurrences of a substring in a string except the first one, so for example
function keepFirst(str, substr) { ... }
keepFirst("This $ is some text $.", "$");

should return: This $ is some text .
I could do it using split() and then for(){}, but is there a nicer solution?

A:

This could be the shortest code that is somewhat efficient. It uses destructuring assignment.
function keepFirst(str, substr) {
  const [
    first,
    ...rest
  ] = str.split(substr);

  return first + (rest.length
    ? substr + rest.join("")
    : "");
}


Q:

Como confirmar borrado de fila

Me gustaria preguntar si quieren o no eliminar un Paciente mediante un SI o NO algo sencillo...
Lo he intentado y me pide si quiere borrarlo mediante Javascript, pero, no hace nada...
<a href='pagines/esborrar.asp?id=<%=rs("Numero")%>&que=<%=nomfitxer%>'>

Esto es lo que he probado:
Script

function irAWeb() {

  if (confirm("¿Quieres ir a la página del Mensajeitor?")) {

    document.location.href = 'pagines/esborrar.asp?id=<%=rs("Numero")%>&que=<%=nomfitxer%>';
  }
}
<a onclick="irAWeb(); return false;" href='pagines/esborrar.asp?id=<%=rs("Numero")%>&que=<%=nomfitxer%>'>

A:

El problema es que estás cancelando el evento sí o sí con ese return false.
Además, si el href indica el destino no necesitas el document.location.href.
Si delegamos el valor de return a la llamada funcionará como deseas:

function irAWeb(event) {
  if (confirm("¿Quieres ir a la página del Mensajeitor?") == false) {
    event.stopPropagation();
    event.preventDefault();
    return false;
  }
  return true;
}
<a onclick="return irAWeb(event);" href='pagines/esborrar.asp?id=<%=rs("Numero")%>&que=<%=nomfitxer%>'> [Pulse para borrar]

Tras dar más detalles en el chat hice una última modificación para cancelar la propagación de eventos con Event.stopPropagation() para evitar que el elemento padre (un
 con otro evento onclick) hiciera una acción al cancelar el borrado.
Es importante pasar el evento como parámetro a la función con onclick="return irAWeb(event);".


Q:

How to optimize this pandas iterable

I have the following method in which I am eliminating overlapping intervals in a dataframe based on a set of hierarchical rules:
def disambiguate(arg):

    arg['length'] = (arg.end - arg.begin).abs()

    df = arg[['begin', 'end', 'note_id', 'score', 'length']].copy()

    data = []
    out = pd.DataFrame()
    for row in df.itertuples():

        test = df[df['note_id']==row.note_id].copy()

        # get overlapping intervals:
        # https://stackoverflow.com/questions/58192068/is-it-possible-to-use-pandas-overlap-in-a-dataframe
        iix = pd.IntervalIndex.from_arrays(test.begin.apply(pd.to_numeric), test.end.apply(pd.to_numeric), closed='neither')
        span_range = pd.Interval(row.begin, row.end)
        fx = test[iix.overlaps(span_range)].copy()

        maxLength = fx['length'].max()
        minLength = fx['length'].min()
        maxScore = abs(float(fx['score'].max()))
        minScore = abs(float(fx['score'].min()))

        # filter out overlapping rows via hierarchy
        if maxScore > minScore:
            fx = fx[fx['score'] == maxScore]

        elif maxLength > minLength:
            fx = fx[fx['length'] == minScore]

        data.append(fx)

    out = pd.concat(data, axis=0)

    # randomly reindex to keep random row when dropping remaining duplicates: https://gist.github.com/cadrev/6b91985a1660f26c2742
    out.reset_index(inplace=True)
    out = out.reindex(np.random.permutation(out.index))

    return out.drop_duplicates(subset=['begin', 'end', 'note_id'])

This works fine, except for the fact that the dataframes I am iterating over have well over 100K rows each, so this is taking forever to complete. I did a timing of various methods using %prun in Jupyter, and the method that seems to eat up processing time was series.py:3719(apply) ... NB: I tried using modin.pandas, but that was causing more problems (I kept getting an error wrt to Interval needing a value where left was less than right, which I couldn't figure out: I may file a GitHub issue there).
Am looking for a way to optimize this, such as using vectorization, but honestly, I don't have the slightest clue how to convert this to a vectotrized form.
Here is a sample of my data:
begin,end,note_id,score
0,9,0365,1
10,14,0365,1
25,37,0365,0.7
28,37,0365,1
38,42,0365,1
53,69,0365,0.7857142857142857
56,60,0365,1
56,69,0365,1
64,69,0365,1
83,86,0365,1
91,98,0365,0.8333333333333334
101,108,0365,1
101,127,0365,1
112,119,0365,1
112,127,0365,0.8571428571428571
120,127,0365,1
163,167,0365,1
196,203,0365,1
208,216,0365,1
208,223,0365,1
208,231,0365,1
208,240,0365,0.6896551724137931
217,223,0365,1
217,231,0365,1
224,231,0365,1
246,274,0365,0.7692307692307693
252,274,0365,1
263,274,0365,0.8888888888888888
296,316,0365,0.7222222222222222
301,307,0365,1
301,316,0365,1
301,330,0365,0.7307692307692307
301,336,0365,0.78125
308,316,0365,1
308,323,0365,1
308,330,0365,1
308,336,0365,1
317,323,0365,1
317,336,0365,1
324,330,0365,1
324,336,0365,1
361,418,0365,0.7368421052631579
370,404,0365,0.7111111111111111
370,418,0365,0.875
383,418,0365,0.8285714285714286
396,404,0365,1
396,418,0365,0.8095238095238095
405,418,0365,0.8333333333333334
432,453,0365,0.7647058823529411
438,453,0365,1
438,458,0365,0.7222222222222222

A:

I think I know what the issue was: I did my filtering on note_id incorrectly, and thus iterating over the entire dataframe.
It should been:
    cases = set(df['note_id'].tolist())

    for case in cases:
        test = df[df['note_id']==case].copy()
        for row in df.itertuples():

            # get overlapping intervals:
            # https://stackoverflow.com/questions/58192068/is-it-possible-to-use-pandas-overlap-in-a-dataframe
            iix = pd.IntervalIndex.from_arrays(test.begin, test.end, closed='neither')
            span_range = pd.Interval(row.begin, row.end)
            fx = test[iix.overlaps(span_range)].copy()

            maxLength = fx['length'].max()
            minLength = fx['length'].min()
            maxScore = abs(float(fx['score'].max()))
            minScore = abs(float(fx['score'].min()))

            if maxScore > minScore:
                fx = fx[fx['score'] == maxScore]

            elif maxLength > minLength:
                fx = fx[fx['length'] == maxLength]

            data.append(fx)

        out = pd.concat(data, axis=0)

For testing on one note, before I stopped iterating over the entire, non-filtered dataframe, it was taking over 16 minutes. Now, it's at 28 seconds!


Q:

adam module sensing AC motion detector

I have been trying to setup a custom security system for my house.  I am using Milestone's XProtect system with multiple cameras and one Adam 6050 module.
I use the Adam 6050 module for magnetic door sensors to tell the system when a door is opened or closed.  I would like to incorporate IR motion detectors into the mix since my cameras do not have IR capabilities.
Traditional indoor motion detectors have 4 to 6 posts, 2 of them power the device, 2 are the NO (Normal Open) or NC (Normal Closed) motion trigger, and the last 2 are often a NO or NC tamper alarm to alert if the device is being opened.
Unfortunately traditional indoor motion detectors are far too sensitive to be used outdoors.  So I purchased an outdoor DC motion detector that typically triggers a flood light.  It has lux and other settings to help me tune it for the lighting.  However, it only has three wires coming out of it, the positive and negative for power, and the motion activated wire which is supposed to run to the light and grounds to the same negative that is used for power.
I would like to know how to wire this motion detector into my system so my Adam module can actually sense it being tripped.  Short of the Adam module itself providing the power (which it is not designed nor I believe capable of), I cannot figure out a circuit that would allow me to sense that third wire being tripped.
If this is not possible, is there another type of outdoor IR motion detector with the 4 to 6 posts like the indoor one that is designed for a security system?  I have been unable to find such an outdoor motion detector.

A:

I happened to find the answer in the adam module forums, which I did not realise existed until this morning.
My biggest problem was that I was only thinking of an on or off switch, and I did not realise that the adam module has two different modes that the Digital In ports can detect signals using.  The DI ports send out a constant 3VDC current which it can then detect if the circuit is completed or not.  However, if you have a device that is already powered separately the adam module can also be triggered to an off state when the incoming voltage is below 3VDC but not 0VDC, and triggered to an on state when it is greater than 3VDC.
An excerpt from the forum:
"
The datasheet shows the values that the module is expecting; >10VDC for "1" and <3VDC for "0".  Even though you say the device is measuring 0VDC when not detecting anything - that is not the complete picture.  The circuit is actually "floating", also known as a Open Circuit.
"
The post then gives this image as the proper way to wire up an externally powered sensor.  Notice the resistor which shorts the DI to the Iso Gnd port, this reduces the steady 3VDC to less than 3VDC from DI2 allowing the adam module to be triggered to a non 0 value less than 3VDC when no current is incoming from the signal terminal.


Q:

adding static time interval panel in Grafana Prometheus

I am trying to add a static panel to show total number of request for the current year in grafana prometheus
I am using sum(http_server_requests_seconds_count{}) for the current interval selection in grafana
Is any way i can do that for current year

A:

Use increase(http_server_requests_seconds_count[1y]). But it's not going to be fast. Or easy on Prometheus. Also, make sure you're using it as instant query (the Instant switch below the query textarea) or it's going to be even worse.


Q:

research in the DB by the start of the name symfony

I would need a little help. I'm trying to implement a search bar with symfony, this search bar in the database. What I can do but the problem is that I absolutely have to put the full name to find the person (s) corresponds to that name. Except that I would like to be able to retrieve all the people starting with the beginning of the name I entered. For example :
 I type "dub" and I find: "Dubois", "Dubost", "Dubububu", ....
 public function searchAction (Request $request)
{
    $defaultData = array('search' => 'Type your search here');
    $form = $this->createFormBuilder()
        ->add('search', TextType::class, array('label'=>'Surname ?','required'=>true))
        ->add('send', SubmitType::class)
        ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();
            $repository = $this
                    ->getDoctrine()
                    ->getManager()
                    ->getRepository('PegasusWebBundle:Clients')
                ;

                //$clients = $repository->findBySurname($form->get('search')->getData()); // Method 1
                $clients = $repository->myFindname($form->get('search')->getData());   // Method 2 with Repository
                return $this->render('PegasusWebBundle:Default:searchresult.html.twig',array(
                'clients'=> $clients ));
            }
    else

    return $this->render('PegasusWebBundle:Default:search.html.twig', array(
        'form' => $form->createView(),
    ));
}

The repository for the method 2
`class ClientsRepository extends \Doctrine\ORM\EntityRepository
{
     public function myFindname($name)
    {
    // Method 2
    $qb = $this->createQueryBuilder('a');
    $qb->where(
    $qb->expr()->like('a.surname' ,':surname'))
        ->setParameter('surname', $name);

    return $qb
        ->getQuery()
        ->getResult();
    }

}`

A:

Try adding the wildchar  eg:
$query = $repo->createQueryBuilder('a')
           ->where('a.surname LIKE :surname')
           ->setParameter('surname', '%'.$name.'%')
           ->getQuery();


Q:

How to Add Vue Component as an HTML Tag

I'm new to using VueJS, and I'm working on a learning project right now.
I have a component called "Draggable", and another one called "ModalPage".
"ModalPage" is as follows:

The code for this page is below:
<template>

{{ msg }}

    <button @click="propagate">Propagate</button>

Vue Modals

</template>

I also have a component called "Draggable" and its code is as follows:
<template>

        <VueDragResize :isActive="true" :w="200" :h="200" v-on:resizing="resize" v-on:dragging="resize">

Hello World!

{{ top }} х {{ left }}

{{ width }} х {{ height }}

        </VueDragResize>

</template>

What i want to do is to be able to click the "Propagate" button on the page, and have a <draggable></draggable> html element appended to the page, as follows:

    <draggable></draggable>

I'm completely stumped with this. Can anyone help me please?

A:

v-if will do your job
Updated
You can use v-for as discussion:
<template>

{{ msg }}

    <button @click="propagate">Propagate</button>

Vue Modals

       <draggable v-for="index in count" :key="index>
       </draggable>

</template>


Q:

Remove and ignore all files that have an extension from a git repository

I'm working on a django project with a few other developers and we have recently realized that all the .pwc files in our app cause the commits and repository to be cluttered.
Is there any way I can remove all .pwc files from all child directories in my git repository and then ignore them for any future commit?

A:

Plenty of ways to remove them:
git ls-files | grep '\.pwc$' | xargs git rm

find . -name *.pwc | xargs git rm

Note: If you haven't committed them, just use rm, not git rm.
To ignore them in the future, simply add *.pwc to the .gitignore. (If you don't have one, create a file named .gitignore at the top level of your repository, and just add a single line saying "*.pwc")

A:

You can also use the following:
git rm -r '*.pwc'

and then make those files ignored by git:
echo '*.pwc' >> .gitignore

The last one is in case if you already have .gitignore file, if not, us single '>' sign.

A:

Jefromi's answer will remove them for the present and the future...you could also remove them in the past using git filter-branch. Of course this has some other ramifications, like requiring everyone else working on the repo to re-checkout (and possibly rebase any work they haven't pushed to the main repo). Depends how big the PWC files are, you may want to do this if they are wasting a lot of diskspace in your repo (since every time you clone a git repo, you get every file and every revision)


Q:

Can't display BLOB stored in database

I've got an problem when I want to convert an image in blob format stored in my database.
When iç just echo $content I can actualy see the blob file printed out so there is no problem with my queries.
The problem is that my code only displays an broken image instead of the Image in the database.
Does anyone know how to display the image properly?
Thanks in advance
        $content = mysql_result($result,$i,'Image');

        echo '<img src="data:image/jpeg;base64,<?php echo base64_encode($content); ?>" width="100" />';

A:

The best way to do it would be to use a separate page to display the image like the following:
<?php
header("Content-Type: image/jpeg");
// Do your query
$content = mysql_result($result,$i,'Image');
echo $content;
?>

Then in another page do

It's also answered in this question: How to display an BLOB image stored in MySql database?


Q:

Xerces SAX parser ignore the xmlxs:xsi attribute as an attribute of an element

Using Xerces SAX parser I try to retrieve all elements and their attributes of this XML file:
-------------- Begin XML file to parse ---------------->
<?xml version="1.0" encoding="UTF-8"?>
 <invoice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="my.xsd">
 <parties>
(...)
-------------- End XML file to parse ---------------->
When getting the attributes for the element 'invoice', Xerces++ does not insert the 'xmlns:xsi' attribute in the list of 'Attributes' for the element 'invoice'.
However, the attribute 'xsi:noNamespaceSchemaLocation' is inserted in the list.
Why? Is there a specific reason from an XML standard point of view ?
Is there a way to configure Xerces++ SAX parser so that it inserts this attribute as well?
(The documentation on setting the parser properties does not tell how).
Thanks for your help.

A:

SAX treats namespace declarations differently from attributes. Attributes are notified in the startElement() event, namespaces are notified (if requested) in the startPrefixMapping() event.


Q:

Beautify url with controller and action as query string

I am creating a custom PHP MVC pattern from scratch. This is how my url looks like
http://domain.com/post/create

I could achieve this with the following htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+) index.php?controller=$1&action=$2 [L]

So, when I print my $_GET, I am getting this
Array ( [controller] => post [action] => create )

Up to this is fine. But my issue is, if I have any extra parameter in query string, I am not able to get that.
ie. if I print $_GET for http://domain.com/post/create?id=1, I am not getting id.
Any help would be greatly appreciated

A:

This is exactly where the QSA flag is created for. By default, if you don't specify a query string, it will re-use the query string of the original request. If you specify a query string, it will overwrite it. If you use the QSA or qsappend (query string append) flag, it will append the original query string to the new query string. See this documentation document for more information.
Your rule would end up looking like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+) index.php?controller=$1&action=$2 [QSA,L]


Q:

opencv_core.inRange() not allowing opencv_core.Scalar as input type

frame=cv2.imread('lena.jpg')
    hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    l_b=np.array([110,50,50])
    u_b=np.array([130,255,255])

    mask=cv2.inRange(hsv,l_b,u_b)
    cv2.imshow('frame',mask)

Error- OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp:1758:
  error: (-209:Sizes of input arguments do not match) The lower boundary
  is neither an array of the same size and same type as src, nor a
  scalar in function 'cv::inRange'

I am programming in python in opencv and this error comes up. Is there any way I can avoid this and get the output?

A:

Instead of converting the frame into grayscale, you have to convert it to HSV.
#Change this line
hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)


Q:

Fortran type variables are zero when accessed with the % operator

I'm trying to access elements of a data type with the % operator, but the result is zero.  I have some example code below.
The line print*, t%tsum always prints out zero.  However when I print tsum within the subroutine it's what it should be.
MODULE statistics

PUBLIC :: TimeMarker , start , finish , avgTime , begin , end_ , tsum ,  counts

TYPE TimeMarker
  REAL*8 :: begin , end_ , tsum
  INTEGER :: counts = 0
    CONTAINS
            PROCEDURE :: start => start_time
            PROCEDURE :: finish => finish_time
            PROCEDURE :: avgTime => averageTime
END TYPE TimeMarker

CONTAINS

        SUBROUTINE start_time(this)
        CLASS(timeMarker) , INTENT(INOUT) :: this
        CALL CPU_TIME(begin)
            END SUBROUTINE start_time

            SUBROUTINE finish_time(this)
        CLASS(timeMarker) , INTENT(INOUT) :: this
        CALL CPU_TIME(end_)
        tsum = tsum + end_ - begin
        counts = counts + 1
            END SUBROUTINE finish_time

            SUBROUTINE averageTime(this)
        CLASS(timeMarker) , INTENT(INOUT) :: this
        WRITE(*,*) "Average time : " , tsum/counts
            END SUBROUTINE averageTime

END MODULE statistics

program test
  use statistics
  implicit none
  type(TimeMarker) :: t
  integer :: n , m
  real*8 :: a

  do m=1,50
    call t%start
    do n=1,20000000
      a = sqrt(a)
    end do

    print*, t%tsum

  end do
  call t%avgTime

end program test

A:

Within the type bound procedures, components of the passed object are still referenced using the syntax argument_name % component_name.  There is no implicit "this" variable for the passed object, as you might find in other languages.  You've used this as the name of the passed argument - so for example the begin component must be referenced as this % begin, not just begin.
In the scope of the module, implicit typing is in effect - the module does not have an IMPLICIT NONE statement.  Consequently, the variables that you are manipulating in your type bound procedures are implicitly declared module variables, which means the compiler reports no errors.
There are other logic errors in the example code, that will need to be dealt with once the component references have been fixed.
(% is not an operator in Fortran, it is just part of the syntax.)


Q:

How do I reload an existing map object in my Angular app?

I have an Angular/Ionic javascript app in which I have google maps loaded in a view. When I run a build of the app on my iPhone, I notice that whenever Google Maps loads, it consumes quite a bit of memory. In 1 session, I'm finding a user sees a map 30-40 times. Each time a user gets back to the map view from a different view, I believe a new map object is created and more memory is consumed. As a result, I'm finding my app crashes after particularly longer sessions.
My question: instead of creating a new map object each time, how do I reload the same map again when the user goes to that specific view? Here is the relevant part of the code:
Controller:
    .controller('GuessCtrl', function($scope, $state, $stateParams, $ionicPopup, $ionicLoading, $ionicHistory) {

            $scope.initialise = function() {
              var myLatlng = new google.maps.LatLng(37.758446, -122.411789);
              var markersArray = [];

              //Initial settings for the map
              var mapOptions = {
                      center: myLatlng,
                      zoom: 2,
                      mapTypeId: google.maps.MapTypeId.ROADMAP,
                      styles: [{ featureType: "poi", elementType: "labels", stylers: [{ visibility: "off" }]}]

                  };

              //Load the initial map
              console.log(map); //null
              var map = new google.maps.Map(document.getElementById("map"), mapOptions);
              console.log(map); //map object details

              $scope.map=map;

            };

            google.maps.event.addDomListener(document.getElementById("map"), 'load', $scope.initialise());

    })

View:
<ion-view view-title="Guess" cache-view="false"  can-swipe-back="false">
  <ion-content scroll="false">

  </ion-content>
</ion-view>

A:

Seem to be having a problem with the API key in the sample below but you can get the gist.  Can create an element that you just append to the directives element as you navigate between views, caution here though this means only one of these elements can be in view at once.
Some stuff in here for dealing with when an array of markers changes and compiling the infowindow contents too so buttons with ng-click and whatnot would work in there.  The bounds related stuff is just to change the zoom level to contain some set of markers added to the map, can be removed if you don't need that, but this should give you good base.

/**
* itSimpleGoogleMap Module
*
* Just a google maps api wrapper
*/

(function(){
  'use strict';
  angular.module('itSimpleGoogleMap', [])

  .directive('itSimpleGoogleMap', function($compile, $timeout){
    // Runs during compile
    var _currentMarkers = [];

    var newdiv = document.createElement('div');
    newdiv.style.width = "100%";
    newdiv.style.height = "100%";
    var map = new google.maps.Map(newdiv, {
      center:  {lat: 41.90, lng: -87.65},
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.SATELLITE
    });

    return {
      scope: {
        markers:'=',
        overlays:'=',
        triggerResize:'='
      }, // {} = isolate, true = child, false/undefined = no change

      link: function(scope, iElm) {
        console.log(newdiv);
        iElm[0].appendChild(newdiv);

        _.each(_currentMarkers, function(marker){
          marker.setMap(null);
        })
        google.maps.event.trigger(map, 'resize');

        scope.$watch('triggerResize', function(){
          google.maps.event.trigger(map, 'resize');
        });

        $timeout(function(){

          var mapOptions = {
            center:  {lat: 41.90, lng: -87.65},
            zoom: 10
          };

          scope.$watchCollection('markers', function(){
            if(!scope.markers || !scope.markers[0] || !scope.markers[0].coords.latitude)
            {
              return;
            }

            _.forEach(_currentMarkers, function(curMarker){
              curMarker.setMap(null);
              google.maps.event.clearInstanceListeners(curMarker);
            });

            _currentMarkers = [];

            var bounds = new google.maps.LatLngBounds();

            var infowindow = new google.maps.InfoWindow();

            if(scope.markers.length==0){
              map.setCenter({lat: 41.90, lng: -87.65});
              return;
            }

            _.forEach(scope.markers, function(markerData){
              var marker = new google.maps.Marker({
                  position: new google.maps.LatLng(markerData.coords.latitude,markerData.coords.longitude),
                  map: map,
                  icon:markerData.icon
                  // title:markerData.data['Growing Site Name'].answer
              });

              bounds.extend(marker.position);

              var infoWindowElement;

              $compile(markerData.infoWindow)(scope, function(cloneElm){
                infoWindowElement = cloneElm[0];
              });

              google.maps.event.addListener(marker, 'click', function() {
                infowindow.close();
                infowindow.setContent(infoWindowElement);
                infowindow.open(map,marker);
              });
              _currentMarkers.push(marker);
            });
            map.fitBounds(bounds);
          });

        },500)
      }
    };
  });
})();

<it-simple-google-map
  markers="model.mapOpts.markers"
  trigger-resize="resizeMap">
</it-simple-google-map>


Q:

R Shiny can you have a navigation bar AND have a fluid page layout

I would like to create a shiny app with a navigation bar BUT ALSO be able to configure the layout on the page using fluid row() and fluid Column().
I read the "NAV BAR PAGES" and "FLUID GRID SYSTEM" areas here http://shiny.rstudio.com/articles/layout-guide.html  and under FLUID GRID SYSTEM it says "To create a layout based on the fluid system you use the fluidPage() function."  so here is my example:
server.r
shinyUI(navbarPage("",
                   tabPanel("test",
                            #THIS IS THE SIDEBAR INPUT PANEL
                            column(2,wellPanel(
                              selectInput("x", "x:", c(5, 10,30,60),selected = 5)
                            )),

                            #THIS IS THE MAIN CONTENT
                            column(10,
                                   fluidRow( plotOutput("plot3")) #,

                                              #fluidRow(
                                              #   column(width=5, plotOutput("plot2")),
                                               #  column(width=5, plotOutput("plot3"))
                                             # )
                            )#end of main body columns
                   )#end tab panel

                                      ,
                                      tabPanel("summary",
                                               verbatimTextOutput("summary")
                                      ),
                                      navbarMenu("More Info",
                                                 tabPanel("Test1",
                                                          dataTableOutput("table")
                                                 )
                                      )
))

ui.r

library(shinydashboard)
library(reshape)
library(quantmod)
library(ggplot2)
library(reshape2)
library(scales)

shinyServer(function(input, output, session) {
  output$plot1 <- renderPlot({
    #plot(cars, type=input$plotType)
    plot(c(1))
  })

  output$plot2 <- renderPlot({
    #plot(cars, type=input$plotType)
    plot(c(100))
  })

  output$plot3 <- renderPlot({
    #plot(cars, type=input$plotType)
    plot(c(-2001))
  })

  output$summary <- renderPrint({
    summary(cars)
  })

  output$table <- renderDataTable({
    cars
  }, options=list(pageLength=10))
})#### END OF SHINY SERVER FUNCTION

So the above code works and it has a navigation bar.  BUT I would like to add another fluid row on the ui.r page in the "test" tab panel. You can see I commented out these lines:
                                  #fluidRow(
                                  #   column(width=5, plotOutput("plot2")),
                                   #  column(width=5, plotOutput("plot3"))
                                 # )

I would like to uncomment them and show a fluid row with 2 columns. BUT when I uncomment those lines the application does not return anything.
So is it possible to have a nav bar page and do fluid layouts like this?
Or do i need to use fluidPAge() instead of navBarPage()?  BUT THEN how do you do a nav bar with fluidPage??

A:

Yes, you can.
It says in the documentation that you can turn this on with fluid = TRUE:

fluid   TRUE to use a fluid layout. FALSE to use a fixed layout.


Q:

Why Can't Computers Off My Network See the Site?

Have just set up Apache, PHP, MySQL, etc. on my Ubuntu OS, and I was wondering why computers that are not on my network can not see the basic index.html that Apache uses as the default. I set up the static ip address for my computer, and I use 192.168.1.100 for computers to view the simple site.
Is there something I am missing that will allow others to access my site? (It is REALLY simple; no graphics, CSS, etc.)

A:

Not exactly clear, but if your computer is in a network behind a NAT router, you will probably need to forward port 80 from that router to your computer.
Of course, that means you will need to give your router/ISP IP out instead of your computer IP. You could, of course, use a dynamic DNS setup that you have a domain name that gets updated every time your IP change. From there, you can give out that domain name to other people instead. Here is one service that provides that setup and instructions:
http://dyn.com/dns/
That said, this may not be allowed by your ISP. Please consult your TOS or AUP that is provided with your Internet access account.

A:

192.168.1.100 is a non-routable, local IP address. Other machines on other networks will not be able to reach your machine with that IP address. In fact, they may have their own local machine with that same IP address. The 192.168 range is specifically reserved for local use.


Q:

After adding .edmx file what is the need to add `Code generation item`?

I have working on mvc3 application.
I want to know some specific answer about :

After adding .edmx file what is the need to add Code generation item like
  Poco , dbContext etc.

Please explain it.

A:

The code generation items will give you POCOs.  http://msdn.microsoft.com/en-us/library/dd456853.aspx
It will create objects (classes) that you can then use in your application.
This article is really useful to help you create POCOs using dbcontext tt.
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx


Q:

Is there a monero address monitoring service?

Is there a monero monitoring service where it will email/sms me if it receives any coins? I'm assuming you'd have to give this service your public view and public spend keys in order for them to see anything?

A:

There is none so far. You'd need to give it also your private view key, and it would have to spend some CPU resources to keep scanning. I assume that's one of the reasons nobody created such service.


Q:

MVC 3 ninject bind lazy evaluated parameter

I want o bind my controller with a parameter that is lazy evaluated.
 protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        try
        {
            return controllerType == null
                       ? null
                       : (IController) _ninjectKernel.Get(controllerType);
        }
        catch (Exception ex)
        {
            throw;
        }
    }

And I have the next binding:
_ninjectKernel.Bind<IFilesRepository>().To<FilesManager>().WithConstructorArgument("storageFolderAbsolutePath", c => c.ToString());

The problem is at the lambda function. I want to return Server.MapPath("/") ... but I don't have the request context in the c object. How can I sent it?

A:

I'm not overly familiar with Ninject, but you should be able to register a provider with the container to be able to resolve a HttpContextBase. By doing so, the IFilesRepository can now take a HttpContextBase as a constructor argument, which will be injected by the container, using the provider, when creating an instance of IFilesRepository.
To register a provider (using a delegate to resolve the service),
Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current));

Be aware however, that the life style of an IFilesRepository would most likely need to change to a "per Web Request" lifestyle, as the HttpContext.Current is created per web request, so you wouldn't want to go holding onto that in an IFilesRepository that had a longer life style. You may want to abstract out the "mapping paths" functionality so that you can have an IFilesRepository with a longer lifestyle.


Q:

Is it possible to import a generic promise in typescript?

I'd like to import PromiseT from sequelize.  I currently have this import statement:
import { sequelize, Instance, Model, DataTypes, Base } from './sequelize';

I found that this doesn't work:
let p: sequelize.PromiseT<MyModel[]>;

I can import the entire package:
import s = require('sequelize');
let p: s.PromiseT<UserInstance[]>;

Is there syntax to just import PromiseT?  Here is the relevant decls from sequelize.d.ts:
declare module "sequelize"
{
    ...
    module sequelize {
        ...
        interface PromiseT<T> extends Promise { ...  };
        ...
   }

    var sequelize: sequelize.SequelizeStatic;

    export = sequelize;
}

Thanks!

A:

Yes, it is possible - it works like any other type.  The above didn't work because it wasn't exported, as correctly indicated by sdgluck above.


Q:

Linux chmod command error: chmod: invalid mode:

I want assign the privilege to directory app, my command as below：
sudo chmod -R hduser /app

hduser is username in Linux, however, I got error message:

chmod: invalid mode: `hduser'

anything need update?

A:

I think the command you're searching for is chown.
http://linuxcommand.org/man_pages/chown1.html
Enter somethink like :
sudo chown -R username[:groupname] /app


Q:

SQL - Categorize employee entrance time

I have a SQL table where I store every employee IN and OUT timestamp.
There are employees that punch the card more than once (because they don't hear that the card was read), other employees that punch the card for some reason (maybe they meet a friend and stay talking for 1 or 2 min) they wait some minutes before they punch again to access the turnstile.
The sample SQL table data looks like this (3 employees only):

Now, I would like to categorize each time to know what timestamp is correct, etc.
For example:

In you see EMP_01 (Yellow record) the LAST_LEAVE technically was 00:38:21 but it's obvious that the employee punch twice that's why the really LAST_LEAVE was 00:38:16.
But, EMP_04 has some other issues, if you see the last 4 records, he has 3 IN's in a row, but those aren't because he didnt hear the beep from the sensor, those are because he leave from other door without punch who knows when, but we know he enter 1 hour after again, and so on.
So, any recommendation on how to deal with this? and how to assign my "Status" flags?
UPDATE:
If EMP_04 has 3 consecutives timestamps of the same type (IN's or OUT's) for example:

9:04:27am (IN)
9:04:35am (IN)
9:04:40am (IN)

My tolerance will be 120 seconds between times, so the first time 9:04:27 is OK, but the next 2 consecutive timestamps should be INACTIVE because my tolerance is 120 seconds.
But, for example if EMP_04 has the following consecutive timestamps:

9:04:27am (IN)
9:04:35am (IN)
9:08:10am (IN)

Then the only time marked as INACTIVE will be 9:04:35am. Because between 9:04.35 and 9:08:10am is greater than 2 min.

A:

First, acknowledging @RamRS put the hard work into the trigger, here is one that is tested and should get your started. Clearly some robust testing is needed for corner cases:
CREATE TRIGGER TS_FindDups ON dbo.TS FOR INSERT
AS
BEGIN

;WITH DupRecords
AS
(
        SELECT i.EmployeeId, i.[TimeStamp]
          FROM inserted i
    INNER JOIN dbo.TS SRC ON i.EmployeeId = SRC.EmployeeId AND i.EntranceType = SRC.EntranceType
         WHERE SRC.[Status] != 'Inactive'
               /* same day (nice...thanks to RamRS) */
               AND CAST(i.[TimeStamp] AS date) =  CAST(SRC.[TimeStamp] AS date)
               /* only checking newer timestamps (also need this so DATEDIFF <= 2 works correctly) */
               AND i.[TimeStamp] > SRC.[TimeStamp]
               /* newer timestamps are less than two minutes for same Employee, same day, same EntranceType */
               AND DATEDIFF(MINUTE, SRC.[TimeStamp], i.[TimeStamp]) <= 2
)

      UPDATE dbo.TS
         SET [Status] = 'Inactive'
        FROM dbo.TS SRC
  INNER JOIN DupRecords ON SRC.EmployeeId = DupRecords.EmployeeId AND SRC.[TimeStamp] = DupRecords.[TimeStamp]

END


Q:

Plupload not working with internet explorer 8/9

I am using plupload plugin to upload file and Server side I am using Spring MVC. It is working fine with IE 10+ and chrome, firefox but not with IE 8/9. In IE 8/9 I get HTTP error 406.
Below is my Server side code:
 @ResponseBody
 @RequestMapping(method = RequestMethod.POST, params="uploadFile")
 public MyJsonResponse uploadPoHardCopy(final HttpServletRequest request){
    MyJsonResponse jsonRespone = new MyJsonResponse();
    //
    //  populate jsonResponse
    //
    return jsonRespone; // return populated jsonResponse
}

javascript code:
 FileUploaded: function(up, file, info) {
     var jResponse = info.response;
     var result = $.parseJSON(jResponse);

}

To correct the error, I controverted the Object to JSON using Gson and returned it as a String as below:
@ResponseBody
@RequestMapping(method = RequestMethod.POST, params = "uploadFile")
public String uploadPoHardCopy(final HttpServletRequest request){
    MyJsonResponse jsonRespone = new MyJsonResponse();
    //
    //  populate jsonResponse
    //
    return new Gson().toJson(jsonRespone); // return populated jsonResponse
}

Now, it is working fine with IE 8/9 but with other browsers I need to parse the response 2 times to get JSON object as below.
FileUploaded: function(up, file, info) {
     var jResponse = info.response;
     var result = $.parseJSON(jResponse);
     result = $.parseJSON(result);

}

Could any one please suggest a better solution.

A:

Using Fiddler I checked HTTP request/response and observed that IE 8/9 were sending Headers -  Accept:*/* . While other browsers were sending  Accept: application/json .
So,  I added below option in js code :
headers:{Accept : "application/json; charset=utf-8"},

and reverted the earlier changes that I made for IE 8/9 i.e. change in controller code to return String and in js code to parse response 2 times
Now, it is working fine with all the browsers.


Q:

What is the difference between gnuplot and AquaTerm?

What is the difference between AquaTerm and gnuplot.
Also is it true that Octave uses AquaTerm instead of X11?
I know AquaTerm might be more rendering of the actual graphic and gnuplot is probably the engine but what does that means?

A:

AquaTerm is a graphics renderer.  Basically, it is a library with an API with allows various programming languages to display graphics on the screen.  gnuplot is a plotting utility.  In a lot of ways, gnuplot functions like a special purpose programming language used for creating plots.  It is able to write those plots to a whole bunch of different devices ("terminals").  examples of some devices are files (png, pdf, postscript) printers and graphics libraries (X11, AquaTerm).  Ultimately, any graph that you can make with gnuplot + AquaTerm for the display on the backend could be made without gnuplot.  Gnuplot's purpose is to abstract the details of the output device away from the user as much as possible so that if you make a plot and display it using AquaTerm, you can then easily save that plot to a png file for future reference.  In reality, there are always some terminal dependent behaviours, but most of the time it doesn't actually matter.


Q:

WSO2 API Manager sandbox keys are accepted by production servers

I just started working with wso2 api manager version 1.6 and it seems that sandbox and production keys can be used interchangeably. Is that a bug?

A:

When using a Sandbox key, it'll send the request to the sandbox url specified when creating the API. If the sandbox url points to a production backend then, you won't see a difference when switching key types.


Q:

mysql combine select from 3 tables with one different column

I have 3 similar tables with 1 different column
id | user_id | post_id | other_id | favorite(tinyint) | date

id | user_id | post_id | other_id | like(tinyint) | date

id | user_id | post_id | other_id | comment(tinyint) | date

Is there a way to return all combined where user_id = 1 and order by date ?

A:

I suppose you want something like this:
SELECT * FROM (
SELECT id, user_id, post_id, other_id, 'favorite' as type, date FROM table1
UNION
SELECT id, user_id, post_id, other_id, 'like' as type, date FROM table2
UNION
SELECT id, user_id, post_id, other_id, 'comment' as type, date FROM table3
) AS t ORDER BY date


Q:

What happens when I do an iTunes Connect phased release?

iTunes Connect now lets me release an app with a phased release. Here's the web UI that explains this.

What actually happens once the update is released to users? What control and feedback do I get?

A:

Apple have summarised the process in the help text pretty well. It brings up most of the salient points.
Here's the UI that you get in iTunesConnect during a phased release.

Here's a summary of a few things – several obvious, some less so:

New users get the update, not the old version.
Users can download the update manually if they wish – it is only automatic updates that are phased.
You can pause the roll out (for up to 30 days). – I presume you can do this multiple times.
There is a button (at the top right App's page) that allows you to "Release to all users" immediately.

The progress of the phased release is not linear. It is very gradual initially, then ramps up at the end. This means you test the water on day one with 1% of users. The roll out is shaped like this:

Day 1 – 1% get the update – 1% are on update.
Day 2 – 1% more get the update – 2% are on update.
Day 3 – 3% more get the update – 5% are on update.
Day 4 – 5% more get the update – 10% are on update.
Day 5 – 10% more get the update – 20% are on update.
Day 6 – 30% more get the update – 50% are on update.
Day 7 – 50% more get update – 100% are on update.

Pausing Releases
If you choose to pause a release, then the interface will give you some further information about this state.

In particular, note that users can still update to this version manually if they chose to. So, pausing the phased release doesn't let you completely stop updates if you find a critical issue with your release. However it should be pretty effective as most users probably don't check for updates manually.
Providing An Update
During a phased release, you can create a new update. You can create the update if the phased release is paused.
So, if we create an update B that we see early on in the phased release has critical issues, then we can pause that phased release and create a new update F to fix the problems.
Until F is available, users can manually update to B if they choose to, but most probably won't manually update.
Unanswered Questions
A few remaining points I'll add answers for if I become aware of them.
Is the phasing order by users or by devices? The text mentions "users", but it's not very explicit. If the ordering is by device, a user might have their phone update on day 1, their iPad day 3, their watch day 6, and Apple TV day 7.
Are future rollouts ordered the same way? Or is a fresh ordering picked so that different users go first and last? Or is the order not explicit and just random? In particular, this has implications for a bad release that you are patching with a fix. You might just release the fix if you're sure it doesn't have any problems of its own. But if you phase the fix, half of the users that got the bad release could be stuck with it for a week.


Q:

Converting VB.Net to C# -type or namespace not found

I am converting a VB.Net project to C#. I declare some public structures in one module and access them in another. I get a "The type or namespace name 'ItemInfo' could not be found." - where ItemInfo is one of the structures. Here is code snippet where I declare the structure:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Data.Common;
using System.IO;
using System.Net.Mail;
using dbAutoTrack.DataReports;
using dbAutoTrack.DataReports.PDFExport;

namespace PlanSchedule
{

    static class PlanScheduleBLL
    {

        #region "Structures"

        public struct ItemInfo
        {
            // LinearProcessTime = sum of bll level resource requirements;
            // when more than one resource on a level, uses max time required;
            // not saved in database, used in order processing only
            public string ItemNumber;
            public string Description;
            public string MakeBuy;
            public long TotalShelfLife;
            public long ReceivedShelfLife;
            public float YieldPercentage;
            public float BatchSize;
            public float SafetyStock;
        }

...and this is where I reference it:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;

namespace PlanSchedule
{
public partial class BuildToStockOrderEntry
{

    // slItemList
    // Key = <item number> - <item description> Value = item number
    private SortedList<string, string> slItemList = new SortedList<string, string>();
    // slItems
    // Key = item number Value = item info
    private SortedList<string, ItemInfo> slItems = new SortedList<string, ItemInfo>();

I do not know C# so I may have a problem in my syntax. Is my declaration of the SortedList using ItemInfo correct?
TIA,
John

A:

You currently have the ItemInfo struct nested in the static class PlanScheduleBLL. You have two options:

Pull it out of that class, and just into the namespace.
If you really want it nested, you need to make PlanScheduleBLL public, and refer to it like PlanScheduleBLL.ItemInfo


Q:

PHP: String replace with Regex

Ive tried to get the Regex to work for this script.
What I need it to do is take the width and height from the youtube code that is inserted and replace it with a specified height and width.
$youtube = str_replace('width="' * ' "','width="500"' $_POST['youtube']);

Can anyone help with this?

A:

Assuming your code is:
$code = 'width="100" and height="200"';

And then perform the below regex replace using preg_replace()
$code = preg_replace('/width="\d+"/', 'width="XXX"', $code);
$code = preg_replace('/height="\d+"/', 'height="XXX"', $code);

\d+ means any number of digit starting from length one.


Q:

Argument of type 'X' is not assignable to parameter of type 'X'

Good day. I'm new to Type Script, using VSCode.
Getting following errors:

error TS2322: Type '() => string' is not assignable to type 'string'.

error TS2322: Type '() => number' is not assignable to type 'number'.

The Code:
DTO.ts
interface DTO {

    getId(): number;
    getValue(): string;
}
export = DTO;

LinkedObject.ts
class LinkedObject {

    public value: string = "Not Set";
    public id: number = 0;

    constructor(value?: string, id?: number) {
        this.value = value;
        this.id = id;
    }
}
export = LinkedObject;

I am trying to instantiate LinkedObject class using above mentioned interface methods:
TravelClientFormPopulator.ts
class TravelClientFormPopulator {

    public populateComboBoxUsingDTOs(dataObjects: Array<DTO>, comboBoxID: string): void {

        // Get the combo box
        var selectElement = <HTMLSelectElement> document.getElementById(comboBoxID);
        // Reset the options
        selectElement.options.length = 0;

        var linkedObjectsToAdd: LinkedObject[] = new Array<LinkedObject>();

        var defaultLinkedObject: LinkedObject = new LinkedObject("Not Selected", 0);

        linkedObjectsToAdd.push(defaultLinkedObject);

        for (var i = 0; i < dataObjects.length; i++) {
            var value: string = dataObjects[i].getValue; // Error here
            var id: number = dataObjects[i].getId; // And here
            var linkedObject: LinkedObject = new LinkedObject(value, id);
        }
    }
}

Any help will be highly appreciated.

A:

You miss parenthesis:
var value: string = dataObjects[i].getValue();
var id: number = dataObjects[i].getId();

A:

For what it worth, if anyone has this problem only in VSCode, just restart VSCode and it should fix it. Sometimes, Intellisense seems to mess up with imports or types.
Related to Typescript: Argument of type 'RegExpMatchArray' is not assignable to parameter of type 'string'

A:

Also adding other Scenarios where you may see these Errors

First Check you compiler version, Download latest Typescript compiler
  to support ES6 syntaxes
typescript still produces output even with typing errors this doesn't
  actually block development,

When you see these errors Check for Syntaxes in initialization or when Calling these methods or variables,
Check whether the parameters of the functions are of wrong data Type,you initialized as 'string' and assigning a 'boolean' or 'number'
For Example
1.
 private errors: string;
    //somewhere in code you assign a boolean value to (string)'errors'
    this.errors=true
    or
    this.error=5

2.
 private values: Array<number>;
    this.values.push(value);  //Argument of type 'X' is not assignable to parameter of type 'X'

The Error message here is because the Square brackets for Array Initialization is missing, It works even without it, but VS Code red alerts.
private values: Array<number> = [];
this.values.push(value);

Note:
Remember that Javascript typecasts according to the value assigned, So typescript notifies them but the code executes even with these errors highlighted in VS Code
Ex:
 var a=2;
 typeof(a) // "number"
 var a='Ignatius';
 typeof(a) // "string"


Q:

Checking for double email addresses which are encrypted in the database

People can register for a newsletter on my website.
Their email address and other personal information will be encrypted in the database.
Now for that registration form I'd like to check if the newly inputted email address is already in my database, but as all emails are encrypted, I can't really check unless I loop through every possible email address, decrypt it and see if it matches the newly inputted email? Is that correct? Or is there a more efficient way to do this?

A:

If you use the same encryption key all the time, you can simply search for the encrypted version. If you do not, you can still store a hash of the addresses additionally and compare against that.


Q:

Position of points in an isometric image after rotation

I'm developing a game using isometric images for the units.
Each units has weapons represented in red on the first image below.
To attach animations to the weapons, I have to be able to calculate the position of each of those points after a rotation of X degrees (units move in 8 directions).
The isometric view is set with an angle of 45 degrees top down :
Points on the image for the main angle
My goal is to find a way to manually spot the red dots on one angle, and then apply a mathematical transformation to get the position of those points for all others angles.
Image after a rotation
Image after an other rotation
I have no clue on how to approach the problematic and I'd be happy to get some help here !
The 3 images are properly scaled if you want to give it a try.
Here is the first point coordinates in pixels on each image, from the top left corner (0,0) :
Point A - 0 degree rotation : (89,522)
Point A - 45 degree rotation : (573,550)
Point A - 90 degree rotation : (609,207)

So the goal is to have (89,522) and deduce (573,550) and (609,207) from that.
Thanks a lot !
G.
Edit :
It seems that a rotation on one frame around a given center point would not work as shown in that picture, probably because of the 45 degree top down angle.

A:

You need to know not just the angle of the rotation, but also what axis the rotation is about. A 30 degree rotation about the x-axis is going to give a much different location than a 30 degree rotation about the y-axis. And a rotation about the y-axis passing through the ankles is going to give a different result than the same rotation about the y-axis passing through the shoulders.
Game developers tend to prefer quaternion to matrix notation for these rotations, and I find it hard to believe you don't already such rotations built into your application. If you really haven't worked out how to move the camera around, then I urge you to put aside your immediate problem and start working your way through the wealth of material out there that explains how it's done, because it is far more than I (or anyone else) can adequately explain in a forum post.
I don't have much need for 3D rotations, so I never remember how quaternion rotation works, but if you are interested, this is how it works by vectors:
Suppose you want to rotate the point $\mathbf p$ by $\theta$ degrees about the axis passing through the point $\mathbf q$ and extending in the direction of the vector $\hat n$, where $\|\hat n\| = 1$, and $\theta$ is positive when rotating in the same direction as the fingers of your right-hand curl when your extended thumb points in the direction of $\hat n$.
Let $\mathbf o = \mathbf q + ((\mathbf p - \mathbf q)\cdot \hat n)\hat n$ and let $\vec p = \mathbf p - \mathbf o$ be the vector pointing to $\mathbf p$ from $\mathbf o$. Then $\mathbf o$ is the point on the axis of rotation that is closest to $\mathbf p$, and $\vec p$ is perpendicular to $\hat n$. Let $\vec r = \hat n \times \vec p$. The rotated point that you want is
$$\mathbf p' = \mathbf o + \vec p\cos \theta  + \vec r\sin\theta $$

FYI - the reason for the somewhat unusual mixture of bold and $\to$ notation is that the bold letters represent points in space, while $\vec v$ represents a vector (direction and magnitude only). And the hat notation $\hat n$ is a common way of denoting unit vectors.


Q:

Over(Partition by ) Column not being recognized. Invalid column

When I execute the following query:
SELECT
    MH.MemberKey,
    ROW_NUMBER() OVER(PARTITION BY MH.MemberKey ORDER BY MH.MemberKey ASC) AS "NewRow",
    MH.FirstName,
    MH.LastName,
    MH.BirthDate,
    MH.AddressLine1,
    MH.AddressLine2,
    MH.AddressLine3,
    MH.City AS MemberCity,
    MH.StateCode AS MemberState,
    MH.ZipCode AS MemberZip
FROM MembershipHistory MH
WHERE NewRow = 1;

I get the following error:

Msg 207, Level 16, State 1, Line 36
  Invalid column name 'NewRow'.

I tried keeping AS, removing AS, removing ""....nothing seems to work. It just wont recognize the column.

A:

The evaluation of the row_number function in the SELECT is done after the WHERE clause has been applied so the alias is not recognized, you can use a subquery to get the result:
select
    MH.MemberKey,
    NewRow,
    MH.FirstName,
    MH.LastName,
    MH.BirthDate,
    MH.AddressLine1,
    MH.AddressLine2,
    MH.AddressLine3,
    MH.City AS MemberCity,
    MH.StateCode AS MemberState,
    MH.ZipCode AS MemberZip
from
(
    SELECT
        MH.MemberKey,
        ROW_NUMBER() OVER(PARTITION BY MH.MemberKey ORDER BY MH.MemberKey ASC) AS NewRow,
        MH.FirstName,
        MH.LastName,
        MH.BirthDate,
        MH.AddressLine1,
        MH.AddressLine2,
        MH.AddressLine3,
        MH.City AS MemberCity,
        MH.StateCode AS MemberState,
        MH.ZipCode AS MemberZip
    FROM MembershipHistory MH
) MH
WHERE NewRow = 1;

In SQL Server the Logical Processinf Order of the SELECT Statement is (from MSDN Docs):

FROM
ON
JOIN
WHERE
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP

A:

Another approach is to use a CTE:
;WITH x AS (SELECT MH.whatever, ROW_NUMBER() ... AS NewRow FROM dbo.table)
SELECT * FROM x WHERE NewRow = 1;


Q:

Mongoose populate embedded

I use Mongoose.js and cannot solve problem with 3 level hierarchy document.
There 2 ways to do it.
First - without refs.
C = new Schema({
    'title': String,
});

B = new Schema({
    'title': String,
    'c': [C]
});

A = new Schema({
    'title': String,
    'b': [B]
});

I need to show C record. How can i populate / find it, knowing only _id of C?
I was try use:
A.findOne({'b.c._id': req.params.c_id}, function(err, a){
    console.log(a);
});

But i dont know how to get from returnet a object only c object that i need.
Second if working with refs:
C = new Schema({
    'title': String,
});

B = new Schema({
    'title': String,
    'c': [{ type: Schema.Types.ObjectId, ref: 'C' }]
});

A = new Schema({
    'title': String,
    'b': [{ type: Schema.Types.ObjectId, ref: 'B' }]
});

How to populate all B, C records to get hierarchy?
I was try to use something like this:
A
.find({})
.populate('b')
.populate('b.c')
.exec(function(err, a){
    a.forEach(function(single_a){
        console.log('- ' + single_a.title);
        single_a.b.forEach(function(single_b){
            console.log('-- ' + single_b.title);
            single_b.c.forEach(function(single_c){
                console.log('--- ' + single_c.title);
            });
        });
    });
});

But it will return undefined for single_c.title. I there way to populate it?
Thanks.

A:

As of Mongoose 3.6 the ability to recursively populate related documents in a query has been added. Here is an example of how you might do it:
 UserList.findById(listId)
         .populate('refUserListItems')
         .exec(function(err, doc){
             UserListItem.populate(doc.refUserListItems, {path:'refSuggestion'},
                   function(err, data){
                        console.log("User List data: %j", doc);
                        cb(null, doc);
                   }
             );
          });

In this case, I am populating an array of id's in 'refUserListItems' with their referenced documents. The result of the query then gets passed into another populate query that references the field of the original populated document that I want to also populate - 'refSuggestion'.
Note the second (internal) populate - this is where the magic happens. You can continue to nest these populates and tack on more and more documents until you have built your graph the way you need it.
It takes a little time to digest how this is working, but if you work through it, it makes sense.

A:

in Mongoose 4 you can populate multilevel like this (even in different database or instance)
A
.find({})
.populate({
  path: 'b',
  model: 'B',
  populate: {
    path: 'c',
    model: 'C'
  }
})
.exec(function(err, a){});

A:

In Mongoose 4 you can populate documents across multiple levels:
Say you have a User schema which keeps track of the user's friends.
var userSchema = new Schema({
  name: String,
  friends: [{ type: ObjectId, ref: 'User' }]
});

Firstly populate() lets you get a list of user friends. But what if you also wanted a user's friends of friends? In that case, you can specify a populate option to tell mongoose to populate the friends array of all the user's friends:
User.
  findOne({ name: 'Val' }).
  populate({
    path: 'friends',
    // Get friends of friends - populate the 'friends' array for every friend
    populate: { path: 'friends' }
  });

Taken from: http://mongoosejs.com/docs/populate.html#deep-populate


Q:

GridGain Off Heap doesn't work

could, please, someone take a quick look, what is wrong with my code, that is supposed to store cache in Off Heap Memory through GridGain?
My configuration is quite the same, as on the wiki page (http://doc.gridgain.org/latest/Off-Heap+Memory)
My configuration is following:
<!-- Enable OffHeap -->
<property name="offHeapMaxMemory" value="#{2L * 1024L * 1024L * 1024L}"/>

<!-- Always store cache entries in off-heap memory, evict to Swap. -->
<property name="memoryMode" value="OFFHEAP_TIERED"/>

However, jconsole shows, that data is still written to the heap memory, as it is fluctuating and when I try to get data, that I've stored, I get the zero result.
Code is following:
final GridCache<String, Object> cache = grid.cache("partitioned");
for (long i = 0; i < 1000; i++) {
    cache.putx(String.valueOf(i), hundredBytes.clone());

    if (i % 1024 * 1024 == 0) {
        System.out.println(i + "bytes inserted");
    }
}

System.out.println("Cache size: " + cache.size());

The last one line shows me "Cache size: 0". That's strange, probably, I do not quite understand, how to access Off Heap memory. Is there other/separate API for that?
Thanks in advance

A:

Correct, there is another one API
GridCache<String, Object> cache = grid.cache("partitioned");
Iterator<Map.Entry<String, Object>> localIterator = cache.offHeapIterator();

However, pay attention, that 'grid.cache("partitioned")' in case of storing data on heap returns the cache for whole cluster, but 'cache.offHeapIterator()' in case of storing data off heap returns only data for the local node in a cluster.
This confused me a bit.


Q:

Wallis integral and gamma function

I would like to ask if anyone would help me to explain how to reach the following relation.
\begin{equation}
\int_0^1 \left( 1-x^{\frac{1}{p}} \right)^q dx= \frac{p!\,q!}{(p+q)!}
\end{equation}
If we substitute one half for p and q
\begin{equation}
\int_0^1 \sqrt{ 1-x^2} dx = \frac{\pi}{4}
\end{equation}
then
\begin{equation}
\frac{p!\,q!}{(p+q)!} \rightarrow (1/2)!^2 \rightarrow (1/2)! = \frac{\sqrt{\pi}}{2}
\end{equation}
I just proved that one half of the factorial is $\frac{\sqrt{\pi}}{2}$.
Thank you in advance.

A:

Do the substitution $x=t^p$ to get
\begin{eqnarray*}
p \int_0^1 t^{p-1}(1-t)^q dt.
\end{eqnarray*}
This is the beta function ... https://en.wikipedia.org/wiki/Beta_function


Q:

which end of a packet is up

Source: The DHCP Handbook, 2nd Edition by Ralph Droms and Ted Lemon (2003)
Example:

Thanks to Cisco, Bucknell University, Vint Cerf and the Corporation for National Research Initiatives, Joe D’Andrea and my other friends at Quadritek Systems (now a part of Lucent Technologies), and Mike Carney of Sun Microsystems for supporting my activities as chair of the DHCWG and making it possible to write this book. Doug Comer first gave me an opportunity to learn which end of a packet is up.

I suppose this is some sort of joke or a pun on something. Any idea what exactly he is talking about?

A:

"To not know which end is up" means "to be totally clueless and ignorant" about something; and a "packet" is one of the most basic concepts in various networking protocols; so the author is saying that he had been completely clueless about networking before Doug Comer first gave him the chance to learn about it (which was, presumably, many years ago).


Q:

Using Warbler, how do I exclude Active Record from the bundled gems?

When using Warbler, what line(s) do I need to add to config/warble.rb to keep it from including Active Record in the bundled gems. I already have excluded Active Record in config/environment.rb as shown below.
config.frameworks -= [ :active_record ]

I tried the same thing only using config.gems in config/warble.rb, but to no avail.

A:

I haven't been able to try either of these ideas, but looking at Nick Sieger's examples :-

Does the gem name have to be a String rather than a Symbol?
It looks like activerecord maybe being included implicitly because config.gems includes rails and config.gem_dependencies = true. Maybe you need to change config.gem_dependencies to false and explicitly include rails, actioncontroller, etc in config.gems.

It might be instructive to print out or log the value of config.gems from within the warble.rb file.


Q:

80/160m Shortened Dipole Trap Questions

I seem to have forgotten some things I learned years ago for my amateur radio exams.  If I am building a 2 band shortened dipole and want a trap between 80 and 160 do I make the trap resonant on 80 or 160 or elsewhere?  I guess I may be mistakenly viewing the trap as a gate that allows certain frequencies and not others.  Is this correct thinking (albeit simplified)?  Can anyone tell me what I should be shooting for here or help me understand the function of traps in a shortened dipole and how I would go about making a trap for a 80/160 dipole?  Full length 80 is fine, with a short 160, would be best.

A:

Traps are L-C cicuits that become high impedance at their resonant frequency.  It's common to make traps by winding lengths of coax around circular forms like PVC pipe of various diameters.  The center conductor of one end is soldered to the shield of the other end, and the remaining center conductor and shield connections are connected to the antenna elements.
The series-connected inner conductor and shield of the coiled coaxial-cable act like a bifilar or parallel-turns winding, forming the trap inductor, while the same inner conductor and shield, separated by the coaxial-cable dielectric, serve as the trap capacitor.
The resultant parallel-resonant LC circuit exhibits a high impedance at the resonant frequency of the trap and effectively disconnects everything after the trap from the antenna. Any inner traps (which are operating below their resonant frequency) function as loading coils and shorten the overall physical length of the antenna.
In your case you'll want at least 3 traps.  One will be resonant at the lower end of the 80m band.  This will disconnect the 160m portion of the antenna when you are transmitting on 80m.  You'll want one between there and the feedpoint with a resonant frequency above the highest frequency you'll use on this antenna.  This one is really a loading coil to make up for the physcilally short antenna length.  The other will be between the 80m trap and the end of the entenna.  This one should be resonant below the 160m band and will serve as a loading coil on 160m.
A couple of notes are in order:

Coaxial-cable traps have a relatively high Q, which results in a relatively sharp frequency resonance.
Which means traps need to be tuned for their resonant frequency, you can't use a cookbook approach here, if they are not right on, you've just made a dummy load.  To tune the traps, you'll need a dip meter or a sufficiently featured antenna analyzer
Top band (160m) is a harsh mistress.  It rewards the dilligent worshiper who builds full size antennas and punishes all others.  You might consider a folded dipole if you have room for a full sized 80m dipole.

A Further Edit:
A folded dipole is a dipole antenna with the ends folded back around and connected to each other, forming a loop as shown below:

The folded dipole antenna is resonant and radiates well at odd integer multiples of a half-wavelength (0.5λ, 1.5λ, etc.), when the antenna is fed in the center like a regular dipole. It can be made resonant at even multiples of a half-wavelength ( 1.0λ, 2.0λ, etc.) by offsetting the feed of the folded dipole (closer to the top or bottom edge of the folded dipole in the picture).
So you could make an off-center fed folding 80m dipole that will also be resonant on 160m.  The feed point impedance will be higher than for a typical dipole, but that's usually not a problem.


Q:

is it "safe" to expose your RxJS Subjects to the "outside world"

I read this good article on
Angular onPush Change Detection Strategy
at some potin he wrote:

It’s an anti-pattern to expose your subject to the outside world, always expose the observable, by using the asObservable() method.

but he doesn't explain why. Does this mean that I shouldn't do somthing like this?
export class ExampleComponent {

  public drawerTrigger$ = new Subject<{}>();
}

and in the HTML
  <button  class="hamburgher-button" type="button"
     (click)="drawerTrigger$.next($event)">
    <i >menu</i>
  </button>

if no, which is the proper way?

A:

In general, you shouldn't expose Subjects because this gives anyone using your service possibility to uncontrollably call drawerTrigger$.next() even in incorrect use-cases.
Even worst situations is that anyone can use drawerTrigger$.error() or drawerTrigger$.complete(). Subjects have internal state and if they emit error or complete the Subject is marked as stopped and will never ever emit anything. If you expose your Subject then you let anyone emit these notifications.
The officially recommended way of exposing Subjects from TypeScript classes is just forcing their types to Observable. You don't need to use asObservable() (RxJS itself doesn't internally use asObservable() anywhere in its codebase):
export class ExampleComponent {
  private drawerTriggerSubject = new Subject<{}>();
  public drawerTrigger$: Observable<{}> = this.drawerTriggerSubject;
}


Q:

MVC Best practices (view acquiring data directly from model) and Yii Framework

I'm using Yii for a few years and only right now I realized, that their demo application (empowered by CRUD auto-generation tool -- Gii) seems to be breaking key MVC architecture pattern. I'd like to discuss this here.
As long as I've been using MVC (about four years), I was always told, that view should not acquire data directly from model. Every piece of text about MVC, I've read so far, was always underlining, that both view and models should be completely separate and the controller is the only element, that spins them together. If I need any model data in view (most often used mechanism) I should let my controller to retrieve it and feed view with it.
Correct me, if I'm wrong, but finding this question and an answer to it makes me sure, that I'm right: while it is technically possible, it should be avoided.
So, in terms of Yii, that would be:
$probes = Probes::model()->getAllProbesForCurrentUser;

$this->render('index', array
(
    'probes'=>$probes
))

(quite obvious, I think -- controller retrieves data from model and renders view, feeding it with that model)
If all above is right, then how should I explain this:
<?php $this->widget('CGridView', array
(
    'id'=>'users-grid',
    'dataProvider'=>$model->search(),
    'columns'=>array
    (
        'name',
        'email',
        'level'
    )
)); ?>

(a widget placed in view acquires data directly from model)
What am I missing?

A:

The array can also called a ViewModel, it is different from the Model because it carries the data the view needs while the Model represent the application business entities. For simple CRUD form they are likely to be identical. But for complex form, a ViewModel can be combined from many models.


Q:

Return XML Data up to next h2 only using XSL

I’m wondering how I can return only a portion of XML data up to the next h2 tag. So I have xml node called SUMMARY as shown below with some example text:

heading One

paragraph text under heading one

Heading Two

paragraph text under heading two

Heading Three

paragraph text under heading three

I currently am using this but it's not quite working
         <xsl:choose>
          <xsl:when test="contains(SUMMARY, ':')">
            <xsl:value-of select="substring-before(SUMMARY, '.')"/>.
            </xsl:when>
          </xsl:choose>

Any help would be appreciated

A:

In XSLT 1.0, for retrieving content belonging to a specific milestone (in this case a heading element), I suggest one of the two following methods. Replace the <xsl:copy-of> part in these examples with whatever you want to do with the retrieved content.
1. Using keys:
<xsl:key name="content-by-heading" match="SUMMARY/p"
  use="generate-id(preceding-sibling::*[self::h1|self::h2|self::h3|self::h4|self::h5|self::h6][1])"/>

<xsl:template match="h2">
  <xsl:copy-of select="key('content-by-heading', generate-id())"/>
</xsl:template>

2. Iterating over the following siblings of the heading:
<xsl:template match="h2">
  <xsl:apply-templates select="following-sibling::*[1]" mode="get-heading-content"/>
</xsl:template>

<xsl:template match="*" mode="get-heading-content">
  <xsl:copy-of select="."/>
  <xsl:apply-templates select="following-sibling::*[1]" mode="get-heading-content"/>
</xsl:template>

<xsl:template match="h1|h2|h3|h4|h5|h6" mode="get-heading-content"/>


Q:

Extracting character-number pairs from a string

Character-values pairs are received continuously from serial port in the following format
h135v48s167

,where h has value 135, v has 48 and s has 167 (the numeric values ranges from 0 to 2000).
I am using if-else statement to perform specific actions based on values of h, v and s.
I tried regex as v(\d+) to get the value of v, which gives v48 as result.

How can i get the numeric value only?

I have to use regex 3 times to get the values of h, v and s. Can a single regexp statement works?

Is there any other better way without using regex?

Following is the section of the code where I am using this -
        if (port.IsOpen) {
      if (port.BytesToRead > 0) {
          //  port.WriteLine ("p");

          string data = port.ReadExisting ();

          if (!string.IsNullOrEmpty (data)) {

              h = Regex.Match (data, @"h\d+").Value;
              v = Regex.Match (data, @"v\d+").Value;
              s = Regex.Match (data, @"s\d+").Value;

              if (h > 150) {
                  // do something
              }

              if (v < 30) {
                  // do something
              }

          } else {
              // default
          }

      }
  }

A:

Using Regex is fine. To allow for arbitrary letters, use [a-z] (or use [hvs] instead if you only want to catch these letters). You may capture both the letter and the number by parantheses and refer to them using the Match.Groups collection.
var data = "h135v48s167";

foreach (Match m in Regex.Matches(data, @"([a-z])(\d+)"))
{
    var variable = m.Groups[1].Value[0];
    var value = Convert.ToInt32(m.Groups[2].Value);
    Console.WriteLine("{0}={1}", variable, value);
    switch (variable)
    {
        case 'h':
            // do something
            break;
        case 'v':
            // do something
            break;
        case 's':
            // do something
            break;
    }
}

gives:
h=135
v=48
s=167


Q:

How to specify any number as a valid property key in Mongoose?

I want to store sensor data in MongoDB, say at a frequency of 1hz. To do this efficiently I want to do it the way this article recommends, namely storing multiple data points in the same document, using the number of seconds elapsed as object properties.
This is how I want a typical document to look:
const record = {
    startingHour: 'Sun Sep 11 2016 03:00:00', // Date object
    values: {
        0: { // minute
            0: { lat: 52.0001, lon: 13.0001 },
            // ... all other seconds
            59: { lat: 52.9999, lon: 13.9999 }
        },
        // ... all other minutes
        59: {
            0: { lat: 53.0001, lon: 14.0001 },
            // ...
            59: { lat: 53.9999, lon: 14.9999 }
        }
    }
}

How could I specify in Mongoose that I want each document t represent an hour with 60 properties, each key being a number from 1 to 59 - one for each minute - and each of those properties to have 60 properties in turn, and those records to represent the actual location values?
So to save a new record I would do record.values.59.59 = { lat: 53.9999, lon: 14.9999 }
How could I represent this kind of schema in Mongoose?

A:

I managed to do it by creating functions to generate the objects I want. I then use those generated objects as schemas, embed one within the other and put those in the final schema:
/**
 * Functions to generate objects for Minutes and Seconds
 * Each object containing 60 keys, going from 0 to 59
 */
function second() {
    let obj = {};
    for (var i = 0; i < 60; i++) {
        obj[i] = Location;
    }
    return obj;
}
function minute() {
    let obj = {};
    for (var i = 0; i < 60; i++) {
        obj[i] = Second;
    }
    return obj;
}

const Location = new Schema({
    latitude: { type: Number, required: true },
    longitude: { type: Number, required: true }
});

// Instantiates Second and Minute objects as schemas
const Second = new Schema(second());

const Minute = new Schema(minute());

// Actual schema
const RecordSchema = new Schema({
    startingHour: {
        type: Date,
        required: true
    },
    values: {
        type: Minute
    }
});

This allows me to save objects like these:
{
    startingHour: new Date(),
    values: {
        0: {
            0: {
                location: { latitude: 0.03, longitude: 51.7 }
            },
            1: {
                location: { latitude: 0.03, longitude: 51.7 }
            }
            // ...
        },
        // ...
        59: {
            // ...
            59: {
                location: { latitude: 0.03, longitude: 51.7 }
            }
        }
    }
}


Q:

Aside from the Force, is there magic in Star Wars?

Is there any sort of magic, besides the Force, existing in the Star Wars universe?
What triggered me to ask this question were the Nightsisters. The Wookieepedia article refers to their powers as "magicks" and seems to present deeds unseen in other force users:

The most powerful of them could use that ichor to summon objects out of the thin air, transform people into ghostly versions of their true forms, or even reanimate the dead.

I have found one description of them in Star Wars Encyclopedia that almost alludes to the Dark Side of the Force once; however it does so without a proper citation, and only actually says "gifted with the power to wield dark magicks", avoiding the topic.

A:

As far as I'm aware, there's NO magic that is explicitly canonically noted to be NOT force based (with one disputed exception - see #2).
In other words, anytime a magic or something similar is mentioned, it's either:

Force abilities being called "magic", by either practitioners or laypeople

This includes things like Sith magic/alchemy, Nightsisters, Rakata, various Ewok etc... shamans.
covered in some detail in Wookieepedia article on magic

More rarely, unknown magical connection that is NOT specifically noted to NOT be Force-based; but most likely is.

Notable exception:
Nightsister Mother Talzin claimed to use non-Force magic in Clone Wars Episode "Disappeared part 2" . However that assertion seems false - it's based on her OWN claim to have "no connection to the force". Which may or may not be true, we aren't told.

Evidence for: Her own statement:

"I am not a natural Force wielder like the Jedi or Sith. I use dark magic to achieve power".

However, her own claim aside, we aren't told what evidence there exists that said "dark magic" isn't simply another form of Force use, like all other magics in Star Wars.
Evidence contrary:

Palpatine wanted to learn her "magics". That seems to indicate they were Force-based
Her son (Maul) was Force-sensitive
It's known from the rest of canon and Legends that Nightsisters in general were Force users.

Research done:

Somewhat surface text search of all of my digitized Star Wars Legends material. Excludes comics/cartoons.
Full search on Wookieepedia. That isn't conclusive in and out of itself, but a good indicator.
Generally good knowledge of canon.