text:
Q: Should I declare permission "com.android.alarm.permission.SET_ALARM" when using Alarm Manager in Android? I've seen many tutorials using AlarmManager, some did declare com.android.alarm.permission.SET_ALARM and some didn't.
When should I declare it and when I shouldn't ?
My app use is setting an Alarm to go off and execute onReceive() of the receiver at specific time.

A: You don't need to declare "com.android.alarm.permission.SET_ALARM" to use the AlarmManager. That permission is needed when you use AlarmClock.


text:
Q: How to reconstruct an sf object from the coordinate matrix made by st_coordinates? st_coordinates provides a matrix of coordinates for all rings in a simple feature column (for each simple feature geometry, outer rings and holes of all polygons). Is there a way to do the reverse, i.e. to build an sfc from a matrix of the same format as the output of st_coordinates?
As a reminder, here is the structure of a st_coordinates output:
        X   Y L1 L2 L3
 [1,]   0   0  1  1  1
 [2,] -10   0  1  1  1
 [3,] -10 -10  1  1  1
 [4,]   0 -10  1  1  1
 [5,]   0   0  1  1  1
 [6,]   1   1  1  1  2
 [7,]  11   1  1  1  2
 [8,]  11  11  1  1  2
 [9,]   1  11  1  1  2
[10,]   1   1  1  1  2
[11,]   2   2  2  1  2
[12,]   3   2  2  1  2
[13,]   3   3  2  1  2
[14,]   2   3  2  1  2
[15,]   2   2  2  1  2
[16,]   5  -2  1  2  2
[17,]  10  -2  1  2  2
[18,]  10  -1  1  2  2
[19,]   5  -1  1  2  2
[20,]   5  -2  1  2  2

corresponding to this image:

How to make the sf object?

A: Via using a data.frame one could do:
library(sf)
library(tidyverse)
d <-
  structure(list(X = c(0L, -10L, -10L, 0L, 0L, 1L, 11L, 11L, 1L,
                       1L, 2L, 3L, 3L, 2L, 2L, 5L, 10L, 10L, 5L, 5L),
                 Y = c(0L, 0L, -10L, -10L, 0L, 1L, 1L, 11L, 11L, 1L, 2L, 2L, 3L,
                       3L, 2L, -2L, -2L, -1L, -1L, -2L),
                 L1 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
                        2L, 1L, 1L, 1L, 1L, 1L),
                 L2 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                        1L, 2L, 2L, 2L, 2L, 2L),
                 L3 = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                        2L, 2L, 2L, 2L, 2L, 2L)),
            class = "data.frame", row.names = c(NA, -20L))   %>%
  st_as_sf(coords = c("X", "Y")) %>%
  group_by(L1, L2, L3) %>%
  summarise(do_union = FALSE) %>%
  st_cast("LINESTRING")
# to visualise
d %>%
  ggplot() +
  geom_sf()
# to generate polygons
d %>%
  st_cast("POLYGON") %>%
  ggplot() +
  geom_sf()

Addendum
Response to the righteous comment by Jean-Luc Dupouey with respect to hole, I guess this code should address that:
d.po <-
  d %>%
  group_by(L2, L3) %>%
  summarise(do_union = FALSE) %>%
  st_cast("MULTILINESTRING") %>%
  st_cast("MULTIPOLYGON") %>%
  ungroup()
# visualise
d.po %>%
  unite("group", L2:L3) %>%
  ggplot() +
  geom_sf(aes(fill = group))

A: Yes, you can. A possible approach is to use sf::st_polygon() call.
The call expects argument in format of a list - the first item is outer boundary, and then holes as required.
As an example consider this code, built on top of the well known & much loved NC shapefile.
What it does is that it decomposes the Mecklenburg county to coordinate matrix of boundaries, and then builds it up to a sfg >> sfc >> sf object.
library(sf)
library(dplyr)
library(ggplot2)

shape <- st_read(system.file("shape/nc.shp", package="sf")) %>%
  filter(CNTY_ID == 2041) # Mecklenburg, as in Charlotte of Mecklenburg-Strelitz

#coordinates of Mecklenburg cnty
coords <- st_coordinates(shape)

class(coords)
[1] "matrix" "array"

head(coords)
             X        Y L1 L2 L3
[1,] -81.04930 35.15153  1  1  1
[2,] -81.02396 35.14903  1  1  1
[3,] -81.00728 35.16325  1  1  1
[4,] -81.00152 35.19599  1  1  1
[5,] -81.01405 35.24990  1  1  1
[6,] -80.97964 35.33327  1  1  1

#a polygon from coords
meck_cnty <- st_polygon(x = list(coords[, 1:2])) %>%  # just X and Y please
  st_sfc() %>%  # from sfg to sfc
  st_sf() # from sfc to sf

class(meck_cnty)
[1] "sf"         "data.frame"

plot(meck_cnty)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does every program have to go through the shell to complete the process they willing to make? I have seen somewhere that "bash is used to communicate with the Linux kernel."
Is it applicable only to the terminal? Or does every program (including programs which has GUIs) have to go through the shell to complete the process they willing to make?
(Consider we are coloring a photo. How does bash know what we are doing? Is there a third party between gimp and bash to convert them to bash?)
It would be really helpful if can you take an example to explain :)

A: Nope. Only users have to go through a shell to communicate with the Kernel. Applications use APIs.
For example, if I want to delete a file, I have to use one shell or the other, and then an application to delete the file:

*

*With a Command-Line Interface (CLI) shell, such as bash, I can use the rm command to delete the file.

*With a GUI shell (like Unity, or GNOME Shell), I can use something else, such as the File Manager to delete the file. The GUI shell does not, in turn, need to use a CLI shell.

Both the File Manager and rm in turn may use the unlink(3) (or the higher level remove(3)) function (or system call) to do the actual work.


text:
Q: How to get chain of all connected edges on DAG (pandas\networkx) i have DAG that i'am convert to pandas_DF
the DF is:
df=pd.DataFrame({'dad':[1, 2, 3, 4,5, "T1", "T2"],
          'children':["T1","T1","T2","T2",6,"T3","T3"]})
print (df)

i want to get list of all the nodes\edges that connected in my DAG (graph)
so it will look like this
df=pd.DataFrame({'dad':[1, 2, 3, 4,5, "T1", "T2","T3"],
          'children':["T1","T1","T2","T2",6,"T3","T3","X"],
           'chain':[0,0,0,0,0,[1,2],[3,4],[1,2,3,4,"T1","T2"]] })

i like to know the connection between the edges all over the chain, like the new column "chain" . its can be a new column like here ,and the order is not important too
i use pandas and networkx, but i will be happy to know a new library of DAG like networkx for python.
The graph looks like it has 2 trees inside

A: You can use networkx as @QuangHoang suggests like this:
import pandas as pd
import networkx as nx

df=pd.DataFrame({'dad':[1, 2, 3, 4,5, "T1", "T2"],
          'children':["T1","T1","T2","T2",6,"T3","T3"]})
G = nx.from_pandas_edgelist(df, 'dad','children', create_using=nx.DiGraph())
df['chain'] = df['dad'].transform(lambda x: list(G.predecessors(x)))
df

Output:
  dad children   chain
0   1       T1      []
1   2       T1      []
2   3       T2      []
3   4       T2      []
4   5        6      []
5  T1       T3  [1, 2]
6  T2       T3  [3, 4]

I think you need all the components of the DiGraph... here is a way to generate those subgraphs with chains.
import pandas as  pd
import networkx as nx

df=pd.DataFrame({'dad':[1, 2, 3, 4,5, "T1", "T2"],
          'children':["T1","T1","T2","T2",6,"T3","T3"]})
G = nx.from_pandas_edgelist(df, 'dad','children', create_using=nx.DiGraph())
df['chain'] = df['dad'].transform(lambda x: list(G.predecessors(x)))

w_list = list(nx.weakly_connected_components(G))
df_comp = pd.DataFrame({'dad': [list(n)[-1] for n in w_list],
              'children':['X' for _ in w_list],
              'chain': [list(x) for x in w_list]})

df_out = pd.concat([df, df_comp])
df_out

Output:
  dad children                     chain
0   1       T1                        []
1   2       T1                        []
2   3       T2                        []
3   4       T2                        []
4   5        6                        []
5  T1       T3                    [1, 2]
6  T2       T3                    [3, 4]
0  T3        X  [1, 2, 3, 4, T1, T2, T3]
1   6        X                    [5, 6]


text:
Q: PHP DOMElement::getElementsByTagName - Anyway to get just the immediate matching children? is there a way to retrieve only the immediate children found by a call to DOMElement::getElementsByTagName? For example, I have an XML document that has a category element. That category element has sub category elements (which have the same structure), like:
<category>
    <id>1</id>
    <name>Top Level Category Name</name>
    <subCategory>
        <id>2</id>
        <name>Sub Category Name</name>
    </subCategory>
    ...
</category>

If I have a DOMElement representing the top level category,
$topLevelCategoryElement->getElementsByTagName('id');

will return a list with the nodes for all 'id' elements, where I want just the one from the top level. Any way to do this outside of using XPath?

A: I don't use PHP, but if PHP actually implements the DOM API as specified the W3C, there is required to be a childNodes property on any Node object.  You should be able to iterate over all of the direct children and test their tag name to see if they're the one you're looking for.  Depending on what your tree looks like, this may be slower than getting all the elements by tag name and testing their tree position, or it may be significantly faster.

A: I'm afraid not. You'll have to iterate through the children or use XPath.
for ($n = $parent->firstChild; $n !== null; $n = $n->nextSibling) {
    if ($n instanceof DOMElement && $n->tagName == "xxx") {
        //...
    }
}

Example with XPath and your XML file:
$xml = ...;
$d = new DOMDocument();
$d->loadXML($xml);
$cat = $d->getElementsByTagName("subCategory")->item(0);
$xp = new DOMXpath($d);
$q = $xp->query("id", $cat); //note the second argument
echo $q->item(0)->textContent;

gives 2.

A: Something like this should do
/**
 * Traverse an elements children and collect those nodes that
 * have the tagname specified in $tagName. Non-recursive
 *
 * @param DOMElement $element
 * @param string $tagName
 * @return array
 */
function getImmediateChildrenByTagName(DOMElement $element, $tagName)
{
    $result = array();
    foreach($element->childNodes as $child)
    {
        if($child instanceof DOMElement && $child->tagName == $tagName)
        {
            $result[] = $child;
        }
    }
    return $result;
}

edit: added instanceof DOMElement check

A: You can compare elements using ===. This will avoid instantiating a Xpath object.
$dom = new DOMDocument();
$dom->loadXML($xmlString);

$return          = array();

//find your top level element
$topLevelElement = $dom->getElementsByTagName('category');
//find all `id` child elements recursively
$idElements      = $topLevelElement->getElementsByTagName('id');

if ($idElements->length > 0) {
    foreach ($idElements as $idElement) {
        if ($idElement->parentNode === $topLevelElement) {
            $return[]   = $idElement;
       }
    }
}

//$return now holds non nested child elements

Depending on the size of your XML document you might find Xpath performs better. However in terms of elegance this solution is cleaner.


text:
Q: Collecting all AWS EBS volume details in csv format I am trying to create a boto3 script to fetch the EBS volumes details like (VolumeID,InstanceID) and am not able to get an idea on how to use the paginate since there are more than 50 EBS volume . Please help

A: The describe_volumes() method seems to return up to 500 volumes.
You can call the function again, passing the NextToken that was returned from the previous call into the NextToken field of the subsequent call. This will continue from where the previous result set finished.
Alternatively, you can use the describe_volumes() paginator:
import boto3

ec2_client = boto3.client('ec2')

paginator = ec2_client.get_paginator('describe_volumes')

response_iterator = paginator.paginate()

for page in response_iterator:
    for volume in page['Volumes']:
        print(volume['VolumeId'])


text:
Q: How to use an INDIRECT inside a range? I want to use an indirect in a range that is nested in an index.
Here's an example. Instead of:
=INDEX($D$2:$AR$2,MATCH(MAX(D3:AR3),D3:AR3))

I want to do something like this:
=INDEX($D$2&":"&INDIRECT(AC25),MATCH(MAX(D3:AR3),D3:AR3))

If AC25 is AR3, why doesn't this work?
I get the following error:
Function INDEX parameter 3 value is 24. Valid values are between 0 and 1 inclusive.

A: It shouldn't have the quotes around "$D$2" - the start of the range should be a reference, not a string. So it should look like this:
=INDEX($D$2:INDIRECT(AC20),MATCH(MAX(D3:AR3),D3:AR3))

I'm assuming AC20 contains AR2 so that it is on the same row as the start of the range, D2.

I can't fully answer the question of why you get the message Function INDEX parameter 3 value is 24. Valid values are between 0 and 1 inclusive.
Assuming AR2 is blank, the first part of the Index function evaluates to the string "2:". Since this is a single value, not an array or range, the only valid value for the second part of the index is 1 or 0.
=Index("2:",1) is valid

=Index("2:",0) is valid

=Index("2:",24) or any other number is invalid.

However the error is in parameter number 2 of the Index statement, not parameter number 3, so I can only conclude that the error message itself may be incorrect and constitutes a possible bug.


text:
Q: Dompdf output contains weird borders I'm currently trying to convert a HTML file into PDF file using DOMPDF. However the converted pdf files contains these red and yellow borders. Is there any way to remove these borders?

Part of my html:
<!DOCTYPE html>

    <meta charset="UTF-8">

Version date: 26 Aug 2015

Research and Consultancy Office

Graduate Studies and Research Education

Conference Participation Proposal

This form will be used by Coordinating Supervisors to recommend their research students for
            conference participation. File Naming Instruction for 2015. For an applicant associated with the
            FECS Faculty, intending to participate in the conference CONF2015, please save the form with a
            file name like this: 2015 FECS Student Name (CONF2015
                Participation Proposal).docx

                STUDENT DETAILS

                Student ID

                Student Name

                Course (MBus/MSc/PhD)

                Date of Enrolment

                Research Focus or Topic

                Coordinating Supervisor

My controller:
class Welcome extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        require_once(APPPATH.'third_party/dompdf/dompdf_config.inc.php');
    }
    public function index()
    {
        $dompdf = new DOMPDF();
        $data = "123";
        $html = $this->load->view('CPP_form/Conference_Participation_Proposal.html',$data,true);
        $dompdf->load_html($html);
        $dompdf->render();
        $dompdf->stream('CPP_Form.pdf',array('Attachment'=>0));
        //$this->load->view('CPP_form/Conference_Participation_Proposal.html');
    }
}

A: You seem to have put DOMPDF_DEBUG_LAYOUT constants to true in dompdf.config.php


text:
Q: Nested form undefined method `model_name' I have nested forms dealing with 3 models. Job, Employer, User
The form on the jobs controller needs to create a job, employer and user.
The Job and Employer forms are working correctly, however when I add the User nested form I get the error "undefined method `model_name' for NilClass:Class"
I'm completely confused as to why.
Here is my code:
Job Model
  attr_accessible :category, :employer_id, :employer_attributes, :user_attributes

  belongs_to :employer
  accepts_nested_attributes_for :employer, :user
  has_many :applications
  has_many :users, :through => :applications

Employer model
 attr_accessible :companyname, :email, :logo, :password, :url
has_many :jobs
 belongs_to :user

User Model
attr_accessible :admin, :cv, :name, :password, :website, :password_confirmation

  has_many :applications
  has_many :jobs, :through => :applications
  has_one :employer

_form.html.erb
<%= form_for(@job) do |f| %>
    <%= f.label :title %>
    <%= f.text_field :title %>

<%= f.fields_for :employer do |builder| %>
     <%= builder.label :companyname, "Company Name" %>
      <%= builder.text_field :companyname %>
<% end %>

<%= f.fields_for :user do |builder| %>
    <%= builder.label :email, "Email" %>
     <%= builder.text_field :email %>
 <%= builder.label :password, "Password" %>
        <%= builder.text_field :password %>
<% end %>

<div class="actions">
    <%= f.submit %>
  </div>

<% end %>

Job Controller
def new

  @job = Job.new
  @job.employer = @job.build_employer
  @job.user = @job.build_user

A: To doesn't look like your Job model has a user method. You may need to add
belongs_to :user


text:
Q: Existence of a (classical) FOL-Formula satisfiable by ONLY an uncountable model? It's easy to find satisfiable FOL-Formulas that are satisfiable by countably finite or infinite models.
If we have a formula with a countably infinite model, we can prove the existence of an uncountable model for that formula (Upward Löwenheim-Skolem Theorem).
But, to my knowledge (and please correct me if I'm wrong), classical FOL does not give us the tools to formally denote such an uncountable model.
Then, the question arises whether there exist classical FOL formulas that ONLY have uncountable models (no finite or infinite countable ones). My answer would be no, because we always get a model of lesser cardinality due to the Downward Löwenheim-Skolem Theorem.
So my questions:

*

*Why is it impossible to define uncountable models in FOL? What "tools" would be needed to do that?

*Is my reasoning about the non-existence of FOL-Formulas with only uncountable models correct?

A: You're right, no such sentence exists: if $\varphi$ is a sentence true in an uncountable structure $\mathcal{M}$, by the downward Lowenheim-Skolem theorem there is a countable $\mathcal{N}\preccurlyeq\mathcal{M}$, and clearly $\mathcal{N}\models\varphi$.
I'm assuming the language is finite, but that's WLOG - the sentence $\varphi$ itself can only use finitely many symbols.

"Why is it impossible to define uncountable models in FOL?"

The essential point that makes downward Lowenheim-Skolem work is Skolem functions. Given a structure $\mathcal{M}$, we can consider an expansion $\mathcal{M}^+$ of $\mathcal{M}$ by all the relevant Skolem functions. Now it's easy to see that any substructure of $\mathcal{M}^+$ corresponds to an elementary substructure of $\mathcal{M}$, so we can find a countable elementary substructure of $\mathcal{M}$ just by using the fact that closing a countable starting set under countably many (since there are only countably many sentences in the first place) finite-arity (since formulas only have finitely-many quantifiers) functions results in an at-most-countable set.
What could break this? Well, in second-order logic, witnesses are no longer elements but sets, and so the entire approach breaks down. In infinitary logic meanwhile, we seem to have too many Skolem functions to handle - while a weak downward Lowenheim-Skolem still does wind up holding for individual $\mathcal{L}_{\omega_1\omega}$-sentences, it's harder to prove, and it fails for higher infinitary logics like $\mathcal{L}_{\omega_1\omega_1}$. A third option would be to look for logics where the notion of Skolem function doesn't even make sense in the first place, but I'm not familiar with these.
So that's how you escape downward Lowenheim-Skolem: work in a logic where Skolem functions either $(i)$ are of too high type, $(ii)$ wind up occurring implicitly too many times in a given sentence, or $(iii)$ (hypothetically) don't even make sense in the first place.


text:
Q: Destructuring bind for regex matches In elisp, how can I get a destructuring bind for regex matches?
For example,
;; what is the equivalent of this with destructuring?
(with-temp-buffer
  (save-excursion (insert "a b"))
  (re-search-forward "\\(a\\) \\(b\\)")
  (cons (match-string 1)
        (match-string 2)))

;; trying to do something like the following
(with-temp-buffer
  (save-excursion (insert "a b"))
  (cl-destructuring-bind (a b) (re-search-forward "\\(a\\) \\(b\\)")
    (cons a b)))

I was thinking I would have to write a macro to expand matches if there isn't another way.

A: Here is one way: you first extend pcase to accept a new re-match pattern, with a definition such as:
(pcase-defmacro re-match (re)
  "Matches a string if that string matches RE.
RE should be a regular expression (a string).
It can use the special syntax \\(?VAR: to bind a sub-match
to variable VAR.  All other subgroups will be treated as shy.

Multiple uses of this macro in a single `pcase' are not optimized
together, so don't expect lex-like performance.  But in order for
such optimization to be possible in some distant future, back-references
are not supported."
  (let ((start 0)
        (last 0)
        (new-re '())
        (vars '())
        (gn 0))
    (while (string-match "\\\\(\\(?:\\?\\([-[:alnum:]]*\\):\\)?" re start)
      (setq start (match-end 0))
      (let ((beg (match-beginning 0))
            (name (match-string 1 re)))
        ;; Skip false positives, either backslash-escaped or within [...].
        (when (subregexp-context-p re start last)
          (cond
           ((null name)
            (push (concat (substring re last beg) "\\(?:") new-re))
           ((string-match "\\`[0-9]" name)
            (error "Variable can't start with a digit: %S" name))
           (t
            (let* ((var (intern name))
                   (id (cdr (assq var vars))))
              (unless id
                (setq gn (1+ gn))
                (setq id gn)
                (push (cons var gn) vars))
              (push (concat (substring re last beg) (format "\\(?%d:" id))
                    new-re))))
          (setq last start))))
    (push (substring re last) new-re)
    (setq new-re (mapconcat #'identity (nreverse new-re) ""))
    `(and (pred stringp)
          (app (lambda (s)
                 (save-match-data
                   (when (string-match ,new-re s)
                     (vector ,@(mapcar (lambda (x) `(match-string ,(cdr x) s))
                                       vars)))))
               (,'\` [,@(mapcar (lambda (x) (list '\, (car x))) vars)])))))

and once that is done, you can use it as follows:
(pcase X
  ((re-match "\\(?var:[[:alpha:]]*\\)=\\(?val:.*\\)")
   (cons var val)))

or
(pcase-let
    (((re-match "\\(?var:[[:alpha:]]*\\)=\\(?val:.*\\)") X))
  (cons var val))

This has not been heavily tested, and as mentioned in the docstring it doesn't work as efficiently as it (c|sh)ould when matching a string against various regexps at the same time.  Also you only get the matched substrings, not their position.  And finally, it applies the regexp search to a string, whereas in manny/most cases regexps searches are used in a buffer.  But you may still find it useful.


text:
Q: How to retrieve a List from Firebase avoid asynchronous I know that when we retrieve data from Firebase ,it will be asynchronous, so ussally i will put all the code inside addChildEventListener, like example i want to sort userList below. But i am confused, if the List is really big, like million Users, so it means the method sortUser(user) will be called million times ? Can anyone explain this to me, I'm new to firebase
myRef.child("User").addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            User user= dataSnapshot.getValue(User.class);
            userList.add(user);
            sortUser(userList);
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

A: You should probably retrieve the data sorted server side by using order-by methods and then listen to that one.
var userRef = firebase.database().ref('posts').orderByChild('Users');

If I guess correctly, you would not need separate sorting client side.
You can also filter data. Do refer the docs

A: You currently use a ChildEventListener, which means your onChildAdded gets called for each child node immediately and then later whenever a new child is added. This indeed can be a lot of invocations.
If you use a ValueEventListener, its onDataChange will only be called once for the initial data (no matter how many child nodes there are), and then once for each change.
By adding a ValueEventListener to your current set up, you can keep things simple: add the child nodes to the lit like you're already doing, but only sort in onDataChange.
myRef.child("User").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
      sortUser(userList);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
};

Firebase will only synchronize the data for the User node once, even when you have two listeners on it.


text:
Q: Redirecting / to /index.html in NancyFX I'm serving static content in a self-hosted Nancy and have overridden the root path, and also added a static content convention to redirect / to Content in my custom bootstrapper like so:
conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/", "Content"));

This works fine when requesting a URL like http://localhost/index.html but I would like http://localhost to redirect to index.html. This doesn't seem to work by default though. What am I doing wrong?

A: Nancy will discover and auto-hook any IRequestStartup classes. Just create a class like this, and all will be fine :) (super-duper)
public class RootRedirector : IRequestStartup
{
    public void Initialize(IPipelines pipelines, NancyContext context)
    {
        if (context.Request.Url.Path == "/")
        {
           throw new RouteExecutionEarlyExitException(new RedirectResponse("/index.html"));
        }
    }
}

A: I ended up solving this with a simple module like so:
public class IndexModule : NancyModule
{
    public IndexModule()
    {
        Get["/"] = _ => Response.AsFile(Settings.Instance.GetFullContentPath("index.html"));
    }
}

Settings.Instance.GetFullContentPath is my own method which returns a full path on disk to the specified file.


text:
Q: How to get all results for api/issues/search (not just first 500)? I am trying to use the SonarQube web service API api/issues/search to extract the information of all issues. But I see that the maximum number of results from the API is only 500 with filters like pageSize.
Is there a different way of using this API so that I can get all the issues in the resultlist?

A: The web service results are paginated. Use ps (page size) and p to step through the result set.
That said, there's a hard limit of 10k.


text:
Q: Is there any systematic way to pick two colors for a chloropleth showing a candidate's margin of victory I have a simple 2-color map showing which candidates won in which precinct. Now I want to make one showing margin of victory within a precinct. So if candidate A won by a lot it would be dark green, if candidate A won by a little it would be light green, if candidate B won by a lot it would be dark yellow and if candidate B won by a little it would be light yellow. (These are local elections so red and blue don't make sense). I used color brewer to pick my initial two color scheme. I have zero design sense. How do I go about picking the colors for the margin of victory map?

A: If you need to get color dynamically on a website, I would give you the advice of using the excellent chroma.js library. The library is easy to use and implements a scale mechanism which would fit to your needs :
scale = new chroma.ColorScale({
colors: ['#F7E1C5', '#6A000B']
})
scale.getColor(0.23)

*

*More on chroma.scales in the dedicated wiki page : https://github.com/gka/chroma.js/wiki/Color-Scales

*Predefined colors are listed here. 'OrRd' (red ramp) and 'Blues' (blue ramp) could be useful to you. See also 'spectral'.

A: There is the ColorBrewer Option in QGIS:
From the Layer Properties > Style > choose Categorized > from Colour Ramp choose New Colour Ramp > Select type Colour Brewer:

Or use the ColorBrewer website: http://colorbrewer2.org/
Pick a diverging colour scheme, maybe 5 data classes, then pick a colour scheme...
You can use those colours in whatever your mapping client is.


text:
Q: Character Encoding Issue in IE Character Encoding Issue in IE
Here is a paragraph text which is not properly rendering in IE
Original Text - The evolutionary improbability of 'generalism' in nature, with special reference to insects
Shows in IE - The evolutionary improbability of 'generalism' in nature, with special reference to insects
Is there any way in Javascript/jQuery to rectify this issue provided the text is wrapped in a 'p' tag?

A: This happens when you have not specified page encoding. add this in Head section.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">


text:
Q: Select com 3 tabelas no SQL SERVER

Eu preciso fazer um select na tabela maquina, porem quando executo meu comando
select maq.maqNip, equi.* from tblMaquina maq
join tblEquipamento equi on equi.equId = maq.maqTipoEqui;

sai o seguinte resultado e eu queria que aparecesse o nome da marca, o modelo e não somente o seu ID.
Alguém poderia me ajudar a relacionar essas três tabelas?

A: Basta adicionar mais um INNER JOIN com a outra tabela de Marca:
SELECT *
  FROM tblMaquina maq
 INNER JOIN tblEquipamento equi
    ON equi.equId = maq.maqTipoEqui;
 INNER JOIN tblMarca marca
    ON equi.marcaId = marca.marcaId;

Observação: Não se esqueça de alterar os nomes das tabelas e campos para ficarem iguais ao seu modelo. Fiz dessa forma de exemplo, pois não possuo os nomes dos seus campos.

A: Tente fazer assim:
select maq.maqNip, equi.*, marc.* from tblMaquina maq
inner join tblEquipamento equi on equi.equId = maq.maqTipoEqui
inner join tblMarca marc on marc.marcId = equi.equMarca

A: Tente executar a seguinte query
select
   maq.Nip,
   equip.tipo,
   marc.nome
from
   Maquina maq,
   Marca marc,
   Equipamento equip,
where
   maq.tipo = equip.id
and
   equip.marca = marc.id;

A: Inclui também um (NOLOCK) para não alocar as tabelas em tempo de processamento
SELECT *
  FROM tblMaquina (NOLOCK) maq
 INNER JOIN tblEquipamento (NOLOCK) equi
    ON equi.equId = maq.maqTipoEqui;
 INNER JOIN tblMarca (NOLOCK) marca
    ON equi.marcaId = marca.marcaId;


text:
Q: How to determine the end of a touch-events set? I have a small app, which uses a fullscreen activity and where I can drag an ImageView.
Now my solution works like this: I change the position of the ImageView according to the drag of the finger, so basically I'm adding the delta x (previousX - currentX) to the position of the ImageView. Now the problem is determining the previousX. It works fine for the first time, since I'm testing whether it's 0, if it's null it means the app is just started and the previous x can become the new x, however the dragging movement becomes ugly as soon as you move the finger away after dragging and start dragging again by putting the finger in a different spot than you finished dragging the first time (because it's virtually impossible to put it in the same place. So the previousX is the one from the last drag, so when you start the second drag it jumps the x difference from the previous x to the new one. I either need to change a different way of calculating this, or determine when the finger gets away from screen and the series of drag events are finished.
This is what my code for the touch event looks like:
@Override
        public boolean onTouch(View v, MotionEvent event) {
            LayoutParams layoutParams = (LayoutParams) img
                    .getLayoutParams();
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:

                int x_cord = (int) event.getRawX();
                int y_cord = (int) event.getRawY();

                if (x_cord > windowWidth) {
                    x_cord = windowWidth;
                }
                if (y_cord > windowHeight) {
                    y_cord = windowHeight;
                }

                if (previousX == 0) {
                    previousX = x_cord;
                }
                if (previousY == 0) {
                    previousY = y_cord;
                }

                layoutParams.leftMargin = layoutParams.leftMargin
                        + (x_cord - previousX);
                layoutParams.topMargin = layoutParams.topMargin
                        + (y_cord - previousY);

                img.setLayoutParams(layoutParams);

                previousX = x_cord;
                previousY = y_cord;

                break;
            default:
                break;
            }
            return true;
        }
    });


text:
Q: Atomic reads/writes of 64 bit values in 32 bit mode with gcc Is there any intrinsic or other way in gcc of persuading it to do 64 bit reads and writes atomically rather than as 2 32 bit writes? (At least in one or two places).
Currently I'm having to do __sync_lock_test_and_set and __sync_fetch_and_add to get it to do the reads/writes atomically, but the CPUs in question have 64 bit fetch and store instructions.
I'd prefer not to write loads of inline assembler (presumably one for each CPU we have to support) with #ifs spread around.
I'm currently using gcc 4.4.6 and am unlikely to get that upgraded in the short term.

A: If you use "long long" the memory access won't be atomic.
However maybe a "double" memory access may be atomic when using a 64-bit CPU (even in a 32 bit program):
union {
    long long ll;
    double d;
} u;

u.ll = my_value;
*(double *)&my_long_long_variable = u.d;

However if the number "my_value" in this example will result in a "signalling NaN" value for u.d then you may get an exception when doing this this way!
Maybe the compiler will not even use FPU registers for this code. In this case the memory access won't be atomic and assembler programming will be needed. You'll definitely need to use either FPU registers or XMM/MMX/... registers for atomic 64-bit accesses.


text:
Q: How to Use Cytoscape.Js Extension in TypeScript? I tried to use CytoscapeJS with an extension - Cytoscape-Node-Editing - in a Typescript project. After reference this Q&A, I changed a line in @types/cytoscape However, I am lost in dark to set up index.d.ts because I am unfamiliar with it, so would like to got any advise, how to implement it? Or any problems with other places? Sincerely.
@types/cytoscape/index.d.ts
function use(module: Ext, module2?: Ext, module3?: Ext): void;

canvas.ts
import cytoscape from "cytoscape";
import $ from 'jquery';
import Konva from 'konva';
import nodeEditing from "cytoscape-node-editing";

cytoscape.use(nodeEditing, Konva, $);

var cy = (window.cy = cytoscape({

...

})

cy.nodeEditing();

Then got Error message
Argument of type 'typeof Konva' is not assignable to parameter of type 'Ext'.
  Type 'typeof Konva' provides no match for the signature '(cytoscape: (options?: CytoscapeOptions | undefined) => Core): void'.

A: According to the usage instructions at: https://github.com/iVis-at-Bilkent/cytoscape.js-node-editing your code should read more like this:
import cytoscape from 'cytoscape';
import $ from 'jQuery';
import nodeEditing from 'cytoscape-node-editing';
import konva from 'konva';

nodeEditing( cytoscape, $, konva ); // register extension

I'm unfamiliar with cytoscape, but it's pretty rare to have to mess with the .d.ts files the @types/packages contain. Is there something I'm missing?


text:
Q: Prevent mpv's progress bar from covering video I have managed to set mpv's progress bar as always visible by adding visibility=always to ~/.config/mpv/script-opts/osc.conf. However, the bar occludes part of the video.
Is there a way to resize the video area so that it is not covered by the bar (like in VLC)?
I have found --window-scale, --autofit and its variants in the manual, but none of them solved my problem, they only change the window size.

A: The option you are looking for is boxvideo, which is available for mpv 0.31 and above (see relevant git commit). Just add:
boxvideo=yes

in your ~/.config/mpv/script-opts/osc.conf and your video should be displayed above the progress bar.
Also make sure to change the vertical position of the subtitles, because they will be probably covered from the OSC now, by adding the sub-margin-y option in your ~/.config/mpv/mpv.conf file as:
sub-margin-y=<size>

where <size> represents the top and bottom screen margin for the subs in scaled pixels.

To install the latest version of mpv, if it isn't included in the default repositories of your Ubuntu version, you can add mpv's PPA by running the following commands:
sudo add-apt-repository ppa:mc3man/mpv-tests
sudo apt-get update

Then reinstall mpv:
sudo apt install --reinstall mpv


text:
Q: Custom Wordpress Query Posts based on meta values I have a simple wordpress query that I need to write as part of a theme I am creating.
I have most of it but need a little push in the right direction to filter the returned results pragmatically based upon a custom meta field of the custom post type.
If the post meta field 'completion date' or 'published date' is equal to or before the current date, put posts into Published Research table.
If the posts meta field 'completion date' or 'published date' is a date ahead of the current date, put the posts into Ongoing Research.
* UPDATED *
Currently I have this:

ONGOING RESEARCH

                Type
                Title
                Summary / Abstract
                Keywords
                Type of Research
                Principle Investigator
                Completion Date

        <?php $wp_query_ongoing = new WP_Query( array( 'post_type' => 'research', 'posts_per_page' => 5, 'order' => 'asc' ) ); ?>
        <?php while ( $wp_query_ongoing->have_posts() ) : $wp_query_ongoing->the_post(); //start of the loop ?>

        <?php
            $post_id = get_the_ID();
            $completion_date = get_post_meta( $post_id, "duration_end", true );
            $publication_date = get_post_meta( $post_id,  "publication_date", true );
        ?>
            <?php if (strtotime($publication_date) >= strtotime("now") || strtotime($completion_date) >= strtotime("now")) { ?>

                <?php echo do_shortcode('[wpuf-meta name="_hidden_type"]' ); ?>
                <?php the_title(); ?>
                3
                4
                5
                6

                    <?php echo do_shortcode('[wpuf-meta name="duration_end"]'); ?>
                    <?php echo do_shortcode('[wpuf-meta name="publication_date"]'); ?>

            <?php } ?>

        <?php endwhile; //end of the loop ?>

PUBLISHED RESEARCH

                Type
                Title
                Summary / Abstract
                Keywords
                Author
                Type of Research
                Open Access
                Date Published

        <?php $wp_query_published = new WP_Query( array( 'post_type' => 'research', 'posts_per_page' => 5, 'order' => 'asc' ) ); ?>
        <?php while ( $wp_query_published->have_posts() ) : $wp_query_published->the_post(); //start of the loop ?>

        <?php
            $post_id = get_the_ID();
            $completion_date = get_post_meta( $post_id, "duration_end", true );
            $publication_date = get_post_meta( $post_id,  "publication_date", true );
        ?>
            <?php if ( strtotime($publication_date) <= strtotime("now") || strtotime($completion_date) <= strtotime("now")){ ?>

                <?php echo do_shortcode('[wpuf-meta name="_hidden_type"]' ); ?>
                <?php the_title(); ?>

                    <?php echo do_shortcode('[wpuf-meta name="synopsis"]'); ?>
                    <?php echo do_shortcode('[wpuf-meta name="abstract"]'); ?>

                    <?php echo do_shortcode('[wpuf-meta name="keywords"]'); ?>

                    <?php
                        $terms = get_the_terms($post->ID, 'keywords');
                        foreach ($terms as $keyword) {
                            $myKeywords[] = $keyword->name;
                        }
                        echo implode( ', ', $myKeywords );
                        $myKeywords = null;
                    ?>

                <?php echo do_shortcode('[wpuf-meta name="author"]' ); ?>
                <?php echo do_shortcode('[wpuf-meta name="type_of_research"]'); ?>
                <?php echo do_shortcode('[wpuf-meta name="open_access"]'); ?>

                    <?php echo do_shortcode('[wpuf-meta name="duration_end"]'); ?>
                    <?php echo do_shortcode('[wpuf-meta name="publication_date"]'); ?>

            <?php } ?>

        <?php endwhile; //end of the loop ?>

* New related question *
Currently the ongoing research table works correctly, only showing posts that have a meta date set somewhere in the future. However, the published table is the correct posts BUT also the posts that should only be in ongoing. ????

I have never worked with dates in php.  How can I modify the above code to return posts according to the the date provided in a meta field.
N/B we are not concerned with the posts actual published date, only the date set in a custom meta field.
https://www.dropbox.com/s/0hddjypw9adj9qj/29_alcoholresearchdirectory_browse-research_1-1.png?dl=0
Thanks for any pointers, I have not worked with php and dates.


text:
Q: How to execute alternatives with puppet? I write a puppet module that will install on a RHEL 7 server Tomcat 7 and Oracle Java 8. The problem is that RH Tomcat's package has a requirement for OpenJDK.
Installing the packages manually, I can solve the Java version issue easily by running the "alternatives" script and manually selecting the correct Java version.
UPDATE:
Using bash, I can run the alternatives quite easily:
alternatives --set java $(rpm -ql oracle-java-1.8.0 | grep -e "jre/bin$")

So, what I need now, is to "execute" the
$(rpm -ql oracle-java-1.8.0 | grep -e "jre/bin$")

using puppet. I would like to avoid facter, and custom fact scripts because I don't have the experience to actually do it.
So, any ideas?


text:
Q: SharePoint website name not changing in the start page after changing it from the sites settings I have a SharePoint website which I changed its name from settings -> site information -> site name.
However, in SharePoint's start page where I can see the frequent and followed sites, that site's name didn't change.
I couldn't figure out why that's the case so I would really appreciate your help. Thought I'd give it some time but the same issue happened with a different site and I waited more than 10 days but still the name didn't change in the start page.

A: I can reproduce the issue in my end.
As a workaround, you could unfollow the site then follow the site again, the site name will change in the start page.


text:
Q: apache proxy_fcgi - The timeout specified has expired - Error dispatching request I have an application in PHP which returns me:
[Thu Oct 05 22:10:59.351244 2017] [proxy_fcgi:error] [pid 3733:tid 139869435164416] (70007)The timeout specified has expired: [client IPADDRESS HIDDEN:46777] AH01075: Error dispatching request to : (polling)
[Thu Oct 05 22:16:27.701213 2017] [proxy_fcgi:error] [pid 3732:tid 139869359630080] (70007)The timeout specified has expired: [client IPADDRESS HIDDEN:46988] AH01075: Error dispatching request to : (polling)
[Thu Oct 05 22:21:52.971235 2017] [proxy_fcgi:error] [pid 3733:tid 139869426771712] (70007)The timeout specified has expired: [client IPADDRESS HIDDEN:47055] AH01075: Error dispatching request to : (polling)
[Thu Oct 05 22:25:23.561216 2017] [proxy_fcgi:error] [pid 3732:tid 139869351237376] (70007)The timeout specified has expired: [client IPADDRESS HIDDEN:47115] AH01075: Error dispatching request to : (polling)
[Thu Oct 05 22:30:47.591237 2017] [proxy_fcgi:error] [pid 3733:tid 139869418379008] (70007)The timeout specified has expired: [client IPADDRESS HIDDEN:47321] AH01075: Error dispatching request to : (polling)
[Thu Oct 05 22:39:10.211214 2017] [proxy_fcgi:error] [pid 3733:tid 139869443557120] (70007)The timeout specified has expired: [client IPADDRESS HIDDEN:47407] AH01075: Error dispatching request to : (polling)
[Thu Oct 05 22:39:38.591259 2017] [proxy_fcgi:error] [pid 3733:tid 139869376415488] (70007)The timeout specified has expired: [client IPADDRESS HIDDEN:47412] AH01075: Error dispatching request to : (polling)
[Thu Oct 05 22:45:13.951238 2017] [proxy_fcgi:error] [pid 3733:tid 139869582505728] (70007)The timeout specified has expired: [client IPADDRESS HIDDEN:47615] AH01075: Error dispatching request to : (polling)
[Thu Oct 05 22:50:36.491214 2017] [proxy_fcgi:error] [pid 3732:tid 139869460342528] (70007)The timeout specified has expired: [client IPADDRESS HIDDEN:47668] AH01075: Error dispatching request to : (polling)
[Thu Oct 05 22:54:57.661219 2017] [proxy_fcgi:error] [pid 3733:tid 139869326059264] (70007)The timeout specified has expired: [client IPADDRESS HIDDEN:47726] AH01075: Error dispatching request to : (polling)

I think the above messages are - in some way - connected to the following random errors:

Note, the XMLHttpRequests (AJAX-call) is coming from the same domain and sometimes does not perform with the errors above. However, normally they do execute?
From what script is this message coming and how can I fix it? There is only one script I can think of which might exceed the default max execution time, however this script is allowed to run longer, using ini_set at the top of the page for the max execution time?
I have no idea where to look and how to fix this issue

A: I know the question is old but I had this problem with WordPress while doing multiple post deletes and I found it hard to find a solution so I'm putting this down for me (in the future) as much as everyone else with the same problem.
For CentOS 8 ensure you have installed fast cgi and optionally php-fph
yum install mod_fcgid php-fpm

Then if no php-fpm edit:
vi  /etc/httpd/conf.d/fcgid.conf

adding the lines
FcgidIdleTimeout 1200
FcgidProcessLifeTime 1200
FcgidConnectTimeout 1200
FcgidIOTimeout 1200

If php-fpm is installed
edit/create:
vi /etc/httpd/conf.modules.d/00-proxy_timeout.conf

and add the lines
Timeout 1200
ProxyTimeout 1200

The restart php-fpm - if installed and httpd

A: Add the following lines into httpd.conf or apache2.conf (depending on your system) file:
Timeout 600
ProxyTimeout 600

and restart apache
sudo /etc/init.d/apache2 restart

A: You can add timeout= to the ProxyPassMatch .
ProxyPassMatch ^/(.+\.php.*)$ fcgi://127.0.0.1:9000/<docroot>/$1 timeout=1800
Have look here .Hope this will help.

A: This may help someone else.
If you are using Centos 8, I discovered that the following will resolve the problem - in your php.conf, near where SetHandler is called, add this:
<IfModule !mod_php5.c>
  <IfModule !mod_php7.c>
    # Enable http authorization headers
    SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1

    <FilesMatch \.(php|phar)$>
        SetHandler "proxy:unix:/run/php-fpm/www.sock|fcgi://localhost"
    </FilesMatch>
  </IfModule>
</IfModule>

<Proxy "unix:/run/php-fpm/www.sock|fcgi://localhost">
    ProxySet connectiontimeout=600 TimeOut=600
</Proxy>

A: I am not sure about the error but it is quite possible that your PHP code application taking a quite longer time than the configured time.i suggest to troubleshoot this using CLI version of PHP.
i can surely say your code stuck in some loop try to use CLI version of PHP it will surely help.

A: <IfModule reqtimeout_module>

    # mod_reqtimeout limits the time waiting on the client to prevent an
    # attacker from causing a denial of service by opening many connections
    # but not sending requests. This file tries to give a sensible default
    # configuration, but it may be necessary to tune the timeout values to
    # the actual situation. Note that it is also possible to configure
    # mod_reqtimeout per virtual host.

    # Wait max 20 seconds for the first byte of the request line+headers
    # From then, require a minimum data rate of 500 bytes/s, but don't
    # wait longer than 40 seconds in total.
    # Note: Lower timeouts may make sense on non-ssl virtual hosts but can
    # cause problem with ssl enabled virtual hosts: This timeout includes
    # the time a browser may need to fetch the CRL for the certificate. If
    # the CRL server is not reachable, it may take more than 10 seconds
    # until the browser gives up.
    RequestReadTimeout header=20-40,minrate=500

    # Wait max 10 seconds for the first byte of the request body (if any)
    # From then, require a minimum data rate of 500 bytes/s
    RequestReadTimeout body=10,minrate=500

</IfModule>

The above seems to be the default on Debian - in my case I just had to modify these values to increase the assumed timeout.

A: Finally I solved this problem.
After increase the ProxyTimeout I startet to got this error. In my case the problem was in the WAF (web application firewall) configuration. Taking a look inside the access.log (or your_virtual_host.access.log) I realised that all source IP was the masquerated to the firewall IP not the real IP source from the internet. Changing this configuration Apache log started knowing the real source IP and the problem was solved.


text:
Q: Why is this code reporting function object is not scriptable @pytest.fixture
def settings():
    with open('../config.yaml') as yaml_stream:
        return yaml.load(stream=yaml_stream)

@pytest.fixture
def viewers(settings):
    try:
        data = requests.get(settings['endpoints']['viewers']).json()
        return data[0]['viewers']
    except Exception:
        print('ERROR retrieving viewers')
        raise(SystemExit)

@pytest.fixture
def viewers_buffer_health(viewers):
    print(viewers)
    viewers_with_buffer_health = {}
    for viewer in viewers:
        try:
            data = requests.get(settings['endpoints']['node_buffer_health']).replace('<NODE_ID>', viewer)
        except Exception as e:
            print('ERROR retrieving buffer_health for {}'.format(viewer))
            raise(SystemExit)
        viewers_with_buffer_health[viewer] = data[0]['avg_buffer_health']
    return viewers_with_buffer_health

The fixture viewers_buffer_health is failing all the time on the requests because 'function' object is not subscriptable

Other times I have seen such error it has been because I was calling a variable and a function by the same name, but it's not the case (or I'm blind at all).
Although it shouldn't matter, the output of viewers is a list like ['a4a6b1c0-e98a-42c8-abe9-f4289360c220', '152bff1c-e82e-49e1-92b6-f652c58d3145', '55a06a01-9956-4d7c-bfd0-5a2e6a27b62b']

A: Since viewers_buffer_health() doesn't have a local definition for settings it is using the function defined previously. If it is meant to work in the same manner as viewers() then you will need to add a settings argument to its current set of arguments.

A: settings is a function.
data = requests.get(settings()['endpoints']['node_buffer_health']).replace('<NODE_ID>', viewer)


text:
Q: How to determine a projected (if 3D) aspect ratio (if set) of a figure in Matlab to specify a proper paper size? I saw many Q&A here about squeezing space out of Matlab figures. However I want to squeeze space resulted from a possibly fixed aspect, i.e. to choose proper paper size for figure printing when aspect is fixed.
Quite often I work with DEM/map/image thus I use axis image. Now if I want to produce a high resolution image I do something like
set(gcf,'PaperUnits','inches','PaperPosition',[0 0 4 3])
print('-dpng','-r300','somefile.png')

as described in Matlab KB.
The problem here is to determine a proper aspect such that I can specify proper paper size that would leave no white/background stripes on either sides.
Apparently if I have a map (let's say 1000x2000 cells) with aspect ratio of 0.5, and I'm printing it on 4"x3" paper, I'll get background stripes on the sides. This is quite annoying as I'd prefer 1.5"x3" paper + axes & labels or so. Right now I have to manually adjust paper size.
This is inconvenient as I'd like a universal solution. For instance I may print a plot into file that I expect to occupy 4"x3" as well that has no fixed aspect. Or I may want to print a 3D figure. I'm aware of daspect and pbaspect, but how can I know how it is currently drawn?
Perhaps I can derive current 2D aspect from get(gca,'Position') and then scale it to my maximum allowed desired size (e.g., 4"x3") while respecting whether DataAspectRatioMode (?) property is set to manual. Is it the way to proceed or is there a better way?

A: I am not exactly sure if I understand your problem exactly, but I have used the following commands to create pdf images that are sized exactly to the size of the figure. I have used this for both 2D and 3D figures. The "handle" variable is simply your figure handle.
set(handle,'Units','inches');
set(handle,'PaperUnits','Inches','PaperPositionMode','auto');
P = get(handle,'Position');
set(handle,'PaperSize', [P(3),P(4)]);


text:
Q: In a linear mixed model what does the F value represent? I am examining the output of my linear mixed model in SPSS and need to decide how to report my findings. I was considering just reporting the p-values. However, my supervisor wants me to provide more information. One figure that I have seen reported is the F value from the 'Type III Tests of Fixed Effects' output table.
Could somebody tell me if this is a useful piece of information to include in my paper? What does it represent?     Is it associated with the F value ANOVA tables or is it something completely different?


text:
Q: Selenium ChromeDriver allow cookies ( default profile) I did a search and I couldn't find this type of problem posted on stack overflow.
And I did read documentation on the https://chromedriver.chromium.org/capabilities but couldn't find any meaningful examples. I found examples about add cookies but not about allow a cookie.
The problem:
Basically, I try to access and scrape a site but as soon as I try to access the url with:
webDriver.get(urlAddress);

a pop-up window appears which prompt me to accept all cookies.
My work around now is to click the button like in the code below.
 List<WebElement> acceptAllCookies =
             webDriver.findElements(By.id("ccc-notify-accept"));

 if (!acceptAllCookies.isEmpty()) {
     acceptAllCookies.get(0).click();
     WebDriverWait wait = new WebDriverWait(webDriver, 2);
 }

And then proceed with scraping.
I went to chrome://settings and add the site on to the "Sites that can always use cookies" and the pop up doesn't show when I access it manually. But when I try programmatically the pop-up appears again.
I do not know how to load my chrome profile . I tried
ChromeOptions options = new ChromeOptions();
//Path to your chrome profile which allows
//cookyes from londonstockexchange
options.addArguments("user-data-dir= My User Data\\Default");
driver = new ChromeDriver(options);

But didn't seem to work. I do not know how to configure the capabilities to allow cookies only for that specific site
Will be something like:
options.setCapability("____", _____);

I don't know what to add in the blanks to always allow cookie for a specific site.
Can someone please help fill in the blanks above or point me to some examples?


text: Q: Why does flexdashboard sidebar resize instead of all the columns? I have a flex dashboard with multiple tab. On one of the tabs, the sidebar resizes when I resize the whole windows and not the plots. I don't want this to happen but can't figure out why. Has anyone had this before?


text:
Q: Table of Contents in LaTeX I wanna add some of the headings like Acknowledgments, Abstract, etc. in TOC. The problem I'm having is that, when I give the command of \tableofcontents, the heading following the command show up but the above mentioned heading which are above the command of \tableofcontents do not show up. How can I fix this?
Also by giving the command of \tableofcontents, a heading of CONTENTS also comes in TOC. Is this possible to avoid the head "Contents" in TOC? Like can I give the heading of contents on my own?


text:
Q: typescript. defining an addition to prototype One of the external library I use add a format method to string prototype.but, I cannot use it.
error TS2094: The property 'format' does not exist on value of type 'string'.

I defined an interface for this type.
 interface String {
        format : (any) => string;
    }

and tried like
var test:String =  "test".format({});

which gives error
error TS2012: Cannot convert 'string' to 'String':

if I define the format method myself like
String.prototype.format = function (d:any) : string {
...
}

the error disappears. But, I don't want to define it myself, it is given by the external library. tried casting with <String>. didn't work. How to do this.
--
Edit:
@basarath showed how it works. But, this is the way I was using it. It doesn't work, if I define the interface within the module
see
// interface String {
//        format:(any) => string;
//}
module test {
    interface String {
        format:(any) => string;
    }
    class Clazz {
        constructor() {
            this.fn();
        }

        fn() {
            var url:string = "test".format({});
        }
    }
}

is it because the changes to string prototype would not be visible outside the module?

A: The following code should just work
interface String {
    format : (any) => string;
}

var test:string =  "test".format({});

And indeed it does
Note that String is not the same as string :
var strObject = new String('foo');
var strValue = 'foo';

strValue = strObject; // Error

And the reason is the way javascript works. One is an object, the other is not:


text:
Q: Android: ERROR: A resolved Google Play services library dependency depends on another at an exact version I tried to add Stripe sdk to my Android project and I started getting this error

FAILURE: Build failed with an exception.

*

*What went wrong: Failed to capture snapshot of input files for task ':MyApp:checkDebugClasspath' property 'compileClasspath' during
  up-to-date check.

In project 'MyApp' a resolved Google Play services library dependency depends on another at an exact version (e.g. "[1.
    3.1,2.3]", but isn't being resolved to that version. Behavior exhibited by the library will be unknown.
     Dependency failing: com.nimbusds:nimbus-jose-jwt:7.2.1 -> net.minidev:json-smart@[1.3.1,2.3], but json-smart version was
    2.3.
     The following dependencies are project dependencies that are direct or have transitive dependencies that lead to the art   ifact
    with the issue.   -- Project 'MyApp' depends onto
    com.stripe:stripe-android@9.3.5
     For extended debugging info execute Gradle from the command line with ./gradlew --info :MyApp:assembleDebug to see the    dependency
    paths to the artifact. This error message came from the
    google-services Gradle plugin, report issues at https
    ://github.com/google/play-services-plugins and disable by adding
    "googleServices { disableVersionCheck = false }" to you   r
    build.gradle file.

I am not able to understand how to fix this especially since we aren't allowed to make changes in the support library versions unless absolutely required. I tried updating the google play libs to the latest but still got the error. These are my gradle dependencies.
dependencies {
    implementation project(':ratemyapp')
    implementation 'com.google.code.gson:gson:2.8.2'
    implementation 'com.mcxiaoke.volley:library:1.0.18'
    implementation 'com.android.support:multidex:1.0.3'
    implementation files('libs/gcm.jar')
    // Facebook SDK Core only (Analytics)
    implementation 'com.facebook.android:facebook-core:4.33.0'
    // Facebook Login only
    implementation 'com.facebook.android:facebook-login:4.33.0'
    implementation 'com.braintreepayments.api:braintree:2.14.2'
    implementation 'com.braintreepayments.api:drop-in:3.4.0'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:customtabs:27.1.1'
    implementation 'com.android.support:animated-vector-drawable:27.1.1'
    /**
     * Google
     */
    implementation 'com.google.android.gms:strict-version-matcher-plugin:1.1.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation 'com.google.android.gms:play-services-base:16.1.0'
    implementation 'com.google.android.gms:play-services-maps:16.1.0'
    implementation 'com.google.android.gms:play-services-identity:16.0.0'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    implementation 'com.google.android.gms:play-services-places:16.1.0'
    implementation 'com.google.android.gms:play-services-nearby:16.0.0'
    implementation 'com.google.android.gms:play-services-gcm:16.1.0'
    implementation 'com.android.support:mediarouter-v7:27.1.1'
    implementation 'com.google.android:flexbox:0.3.2'
    //compile files('libs/splunk-mint-4.2.1.jar')
    implementation 'com.android.support:design:27.1.1'
    // CardView
    implementation 'com.android.support:cardview-v7:27.1.1'
    implementation 'com.pixplicity.multiviewpager:library:1.0'
    implementation 'com.github.aakira:expandable-layout:1.4.1@aar'
    implementation 'me.everything:overscroll-decor-android:1.0.4'
    implementation 'org.apache.httpcomponents:httpmime:4.5.2'
    implementation 'commons-net:commons-net:3.3'
    implementation 'com.android.support:percent:27.1.1'
    /*For Request Server*/
    implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    implementation 'com.artemzin.rxjava:proguard-rules:1.1.6.0'
    /**
     * Animation.
     */
    implementation 'com.nineoldandroids:library:2.4.0'
    implementation 'com.daimajia.easing:library:1.0.1@aar'
    implementation 'com.daimajia.androidanimations:library:1.1.3@aar'
    implementation 'net.soulwolf.widget:ratiolayout:1.0.0'
    implementation 'com.jakewharton:butterknife:8.5.1'
    kapt 'com.jakewharton:butterknife-compiler:8.5.1'
    /**
     * Event Bus.
     */
    implementation 'org.greenrobot:eventbus:3.0.0'
    implementation 'com.wefika:flowlayout:0.4.1'
    /**
     * Ring capcha
     */
    implementation 'com.thrivecom:ringcaptcha:1.0.11@aar'
    /**
     * Zendesk
     */
    implementation 'com.zopim.android:sdk:1.3.7.1'
    implementation 'com.zendesk:support:2.0.0'
    implementation('com.twitter.sdk.android:twitter:3.3.0@aar') {
        transitive = true
    }
    implementation('com.crashlytics.sdk.android:crashlytics:2.9.3@aar') {
        transitive = true
    }
    implementation('io.fabric.sdk.android:fabric:1.3.12@aar') {
        transitive = true
    }
    implementation 'io.branch.sdk.android:library:3.2.0'
    implementation 'com.mixpanel.android:mixpanel-android:5.+'
    implementation 'com.yqritc:android-scalablevideoview:1.0.4'
    implementation 'com.android.support:cardview-v7:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.google.dagger:dagger:2.12'
    kapt 'com.google.dagger:dagger-compiler:2.11'
    implementation 'com.google.dagger:dagger-android-support:2.11'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    kapt 'com.google.dagger:dagger-android-processor:2.11'
    // ViewModel and LiveData
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    kapt "android.arch.lifecycle:compiler:1.1.1"
    // Room
    implementation 'android.arch.persistence.room:runtime:1.1.1'
    kapt "android.arch.persistence.room:compiler:1.1.1"
    // Paging
    implementation 'android.arch.paging:runtime:1.0.1'
    implementation 'com.jakewharton.timber:timber:4.6.0'
    // Test helpers for LiveData
    testImplementation 'android.arch.core:core-testing:1.1.1'
    // Test helpers for Room
    testImplementation 'android.arch.persistence.room:testing:1.1.1'
    implementation 'org.apache.commons:commons-lang3:3.6'
    implementation 'com.github.bumptech.glide:glide:4.5.0'
    kapt 'com.github.bumptech.glide:compiler:4.4.0'
    implementation 'com.github.rubensousa:gravitysnaphelper:1.5'
    implementation 'me.everything:overscroll-decor-android:1.0.4'
    implementation 'com.github.bumptech.glide:recyclerview-integration:4.4.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.8'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
    implementation 'android.arch.persistence.room:runtime:1.1.1'
    implementation 'android.arch.persistence.room:rxjava2:1.1.1'
    implementation 'android.arch.lifecycle:reactivestreams:1.1.1'
    implementation 'com.github.zcweng:switch-button:0.0.3@aar'
    implementation 'com.shuhart.bubblepagerindicator:bubblepagerindicator:1.0.6'
    implementation 'com.iarcuschin:simpleratingbar:0.1.5'
    implementation 'co.omise:omise-android:2.6.4'
    implementation 'com.airbnb.android:lottie:2.5.4'
    implementation 'com.adjust.sdk:adjust-android:4.13.0'
    implementation 'com.android.installreferrer:installreferrer:1.0'
    implementation 'io.card:android-sdk:5.5.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'android.arch.persistence.room:testing:1.1.1'
    androidTestImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test:rules:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.2'
    androidTestImplementation 'org.mockito:mockito-core:2.7.19'
    androidTestImplementation 'org.mockito:mockito-android:2.7.19'
    implementation 'net.cachapa.expandablelayout:expandablelayout:2.9.2'
    implementation project(':menu')
    implementation project(':base')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-perf:16.2.0'
    implementation 'com.google.firebase:firebase-core:16.0.4'
    implementation 'com.google.firebase:firebase-analytics:16.0.4'
    implementation 'com.google.firebase:firebase-appindexing:16.0.2'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.android.instantapps:instantapps:1.1.0'
    implementation 'com.romandanylyk:pageindicatorview:1.0.2'
    implementation 'com.airbnb.android:lottie:2.5.4'
    implementation 'me.grantland:autofittextview:0.2.+'
    //OTP
    implementation 'com.poovam:pin-edittext-field:1.1.2'
    implementation 'jp.wasabeef:glide-transformations:4.0.1'
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'de.hdodenhof:circleimageview:3.0.0'
    implementation 'com.braintreepayments.api:data-collector:2.22.0'

    //Applozic
    implementation 'com.applozic.communication.uiwidget:mobicomkitui:5.33'
    //Places SDK
    implementation ('com.google.android.libraries.places:places:1.1.0'){
        exclude group: 'com.android.volley'
    }

    //Freshchat SDK
    implementation 'com.github.freshdesk:freshchat-android:2.6.0'

    //Freshdesk font
    implementation 'uk.co.chrisjenx:calligraphy:2.1.0'

    //Stripe
    implementation 'com.stripe:stripe-android:9.3.5'
}

Would appreciate any suggestions or help, thanks!

A: I solved it updating Android Gradle Plugin to 3.4.1, Gradle to 5.1.1, and, if you use Kotlin, to 1.3.10. And don´t forget add this to gradle:
apply plugin: 'com.google.gms.google-services'
For Stripe, I use implementation 'com.stripe:stripe-android:9.3.5', and I had to change some functions in the code, like:
Card card = new Card(...) to Card card = Card.create(...)
and token.getCard().getType() to token.getCard().getBrand()

A: It's not one of your play store dependencies.  Your error message clearly is blaming the Stripe Payments library.  That library has an internal reference to a specific play services version.  Most likely solution is your play services are too new for it.  I could check their download site for a new version at the least.  It's a pretty common issue for programmers to forget that the version check they are doing should allow newer versions, and sometimes it's on purpose to force you to update just in case of incompatibilites.


text:
Q: FFmpeg multicast packet filtering with UDP Problem Scenario:
I am trying to capture multiple multicast cameras on a network with FFmpeg. Upon receiving the streams, I find that each FFmpeg instance running is receiving and decoding the packets destined for the other instances. This causes the video of each instance to flicker between the correct image and the images of all the other cameras. Each camera uses the same destination UDP port and I believe this is the reason its happening.
Example
Process 1
ffmpeg -rtsp_transport udp_multicast -i "rtsp://192.168.1.1/stream1m" test1.mp4

Process 2
ffmpeg -rtsp_transport udp_multicast -i "rtsp://192.168.1.2/stream1m" test2.mp4

Expected Output
Each MP4 contains only one, non-interrupted stream
Actual Output
As described above
I've trawled through FFmpeg's docs, as well as extensive 'googling' however I can only see a way to filter incoming packets when using an rtp:// or udp:// input. This isn't possible in this application as I want to use RTSP for the SDP it provides.
Any help is greatly appreciated!

A: I got this to work using different multicast IPs and ports. The trick is the ports - they have to be different on the stream side, even if the IPs are different.
This seems to be a problem with ffmpeg.


text:
Q: SVG Pan and Zoom not working Trying to carry out this svg pan and zoom for two rectangles, I can't seem to get it to work. Really new at this but I was able to come up with this but it just doesn't seem to work . I have added my javascript code as well if anyone can seem t find what is wrong, i Used the group id for the elements to try to pan and zoom based on my js but it doesn't still work
    <!DOCTYPE html>
      <head>

     </head>
      <body>

      <svg  width="24cm" height="16cm" viewBox="-4 -1 26 20"
      xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

       <g id="myfield" transform="scale(1,1) translate(0,0)" >

          <g transform=" scale(1,-1) translate(0,-16)"><g id="togglefield">
           <rect id= "rectangle1" class= "rectangles" x= 2  y= 0  width= 4  height= 6  onClick="fieldDetails(event)"></rect>

       <rect  id="rectangle2" class= "rectangles" x= 2  y= 6  width= 4
         height= 5 onClick="fieldDetails(event)"></rect>

     </g>
     <g id="togglefind">
     <circle class="circles" id="find1" cx= 4  cy= 1  r="0.2" onClick="findDetails(event)"></circle>
       <text class="text" x= 4 y= 1  transform="translate(0 2 ) scale(-1,1) rotate(180)"> 1 </text>

      <circle class="circles" id="find5" cx= 4  cy= 7  r="0.2" onClick="findDetails(event)"></circle>
      <text class="text" x= 4 y= 7  transform="translate(0 14 ) scale(-1,1) rotate(180)"> 5 </text>

      </g>
      </g>
     <rect x="12.6" y="12.4" width="3" height="3" fill="white" stroke="grey" stroke-width="0.05"/>
      <text x="13" y="13.2" font-family="Arial" font-size="0.6">Legend</text>
       <g id="Fieldlgd">
        <rect x="12.8" y="13.6" width="0.6" height="0.6" fill="none" stroke="green" stroke-width="0.04"/>
         <text x="13.6" y="14" font-family="Georgia" font-size="0.5">Field ID</text>
         <text x="13" y="14" font-family="Georgia" font-size="0.5">1</text>
           </g><g id="Findlgd">
          <circle cx="13.1" cy="14.7" r="0.12" fill="blue" stroke="red" stroke-width="0.05"/>
         <text x="13.6" y="14.85" font-family="Georgia" font-size="0.5">Find ID</text>
          <text x="13.2" y="14.7" font-family="Arial" font-size="0.45">1</text>
      </g>
         </g>
          <rect x="-4" y="0.3" width="3.2" height="12" fill="white" stroke="black" stroke-width="0" fill-opacity="0.8"/>
       <text x="-4" y="0.8" font-family="San Serif" font-size="3%">Pan and Zoom </text>
    <text x="-2.7" y="1.8" font-family="Georgia" font-size="4%">N</text>
      <polyline id="panup" onclick="panup_click(evt)" points="-3,2 -2.5,1 -2,2 -2.3,1.9 -2.7,1.9 -3,2" fill="lavender" stroke="cornflowerblue" stroke-width="0.05" fill-opacity="0.6"/>
      <text x="-2.7" y="3.4" font-family="Georgia" font-size="4%">S</text>
       <polyline id="pandown" onclick="pandown_click(evt)" points="-3,2.8 -2.5,3.8 -2,2.8 -2.3,2.9 -2.7,2.9 -3,2.8" fill="lavender" stroke="cornflowerblue" stroke-width="0.05" fill-opacity="0.6"/>
      <text x="-3.3" y="2.6" font-family="Georgia" font-size="4%">W</text>
       <polyline id="panleft" onclick="panleft_click(evt)" points="-2.7,1.9 -3.7,2.4 -2.7,2.9 -2.8,2.6 -2.8,2.2 -2.7,1.9" fill="lavender" stroke="cornflowerblue" stroke-width="0.05" fill-opacity="0.6"/>
      <text x="-2.1" y="2.6" font-family="Georgia" font-size="4%">E</text>
      <polyline id="panright" onclick="panright_click(evt)" points="-2.3,1.9 -1.3,2.4 -2.3,2.9 -2.2,2.6 -2.2,2.2 -2.3,1.9" fill="lavender" stroke="cornflowerblue" stroke-width="0.05" fill-opacity="0.6"/>
      <text x="-2.7" y="2.6" font-family="Georgia" font-size="4%">C</text>
       <circle id="recenter" onclick="recenter_click(evt)" cx="-2.5" cy="2.4" r="0.3" fill="lavender" stroke="cornflowerblue" stroke-width="0.05" fill-opacity="0.6"/>
    <polyline id="zoomcross" points="-2.6,4.2 -2.4,4.2 -2.4,4.6 -2.1,4.6 -2.1,4.8 -2.4,4.8 -2.4,5.3 -2.6,5.3 -2.6,4.8 -2.9,4.8 -2.9,4.6 -2.6,4.6 -2.6,4.2" fill="cornflowerblue"/>
   <rect id="zoomIn" onclick="zoomin_click(evt)" x="-3" y="4" width="1" height="1.5" fill="white" stroke="black" stroke-width="0.05" opacity="0.2"/>
  <rect id="zoomdash" x="-2.9" y="5.9" width="0.8" height="0.2"
   fill="cornflowerblue"/>
   <rect id="zoomOut" onclick="zoomout_click(evt)" x="-3" y="5.7" width="1" height="0.6" fill="white" stroke="black" stroke-width="0.05" opacity="0.2"/>

</svg>

// Pan left function
function panleft_click(evt) {
var root = document.documentElement;
           // variable to get the group transform object
    var myfield  = null;
    myfield  = document.getElementById("myfield");

            // Incase the group has no Id then get the first '<g>' element
    if(myfield  === null)
            myfield  = document.getElementsByTagName('g')[0];

  var goIn = evt.target;  // thus line is currently not used

  // Fetch the current transform state of the group element into a
  var matrix = myfield.getCTM();
  // Read the translate attributes from the matrix into variable x and y
  // Below is the desired leftward change
  var x = (matrix.e + 2) / matrix.a  ; // Divide change by current scale to remove exponential movement
  var y = matrix.f  / matrix.a ;  // To keep motion only along one axis
  // Set the new transform attribute for the group
  myfield.setAttributeNS(null,"transform", "scale(" + matrix.a + "," + matrix.d + ") translate(" + x + "," + y + ")");

}

// Pan right function
function panright_click(evt) {

           // variable to get the group transform object
    var myfield  = null;
    myfield  = document.getElementById("myfield");

            // Incase the group has no Id then get the first '<g>' element
    if(myfield  === null)
            myfield  = document.getElementsByTagName('g')[0];

  var goIn = evt.target;  // thus line is currently not used

  // Fetch the current transform state of the group element into a matrix
  var matrix = myfield.getCTM();
  // Read the translate attributes from the matrix into variable x and y
  // Below is the desired rightward change
  var x = (matrix.e - 2) / matrix.a;   // Divide change by current scale to remove exponential movement
  var y = matrix.f  / matrix.a;      // To keep motion only along one axis
  // Set the new transform attribute for the group
  myfield.setAttributeNS(null,"transform", "scale(" + matrix.a + "," + matrix.d + ") translate(" + x + "," + y + ")");

}

// Pan up function
function panup_click(evt) {

           // variable to get the group transform object
    var myfield  = null;
    myfield  = document.getElementById("myfield");

            // Incase the group has no Id then get the first '<g>' element
    if(myfield  === null)
            myfield  = document.getElementsByTagName('g')[0];

  var goIn = evt.target;  // thus line is currently not used

  // Fetch the current transform state of the group element into a matrix
  var matrix = myfield.getCTM();
  // Read the translate attributes from the matrix into variable x and y
  var x = matrix.e / matrix.a ;     // Divided by scale to keep motion only along one axis

  // Below is the desired upward change
  var y = (matrix.f + 2) / matrix.a;   // Divide change by current scale to remove exponential movement
  // Set the new transform attribute for the group
  myfield.setAttributeNS(null,"transform", "scale(" + matrix.a + "," + matrix.d + ") translate(" + x + "," + y + ")");

}

// Pan down function
function pandown_click(evt) {

           // variable to get the group transform object
    var myfield  = null;
    myfield  = document.getElementById("myfield");

            // Incase the group has no Id then get the first '<g>' element
    if(myfield  === null)
            myfield  = document.getElementsByTagName('g')[0];

  var goIn = evt.target;  // thus line is currently not used

  // Fetch the current transform state of the group element into a matrix
  var matrix = myfield.getCTM();
  // Read the translate attributes from the matrix into variable x and y
  var x = matrix.e / matrix.a;   // Divided by scale to keep motion only along one axis

  // Below is the desired downward change
  var y = (matrix.f - 2) / matrix.a;   // Divide change by current scale to remove exponential movement
  // Set the new transform attribute for the group
  myfield.setAttributeNS(null,"transform", "scale(" + matrix.a + "," + matrix.d + ") translate(" + x + "," + y + ")");

}

   // Zoom in (enlarge) function
   function zoomin_click(evt) {

           // variable to get the group transform object
    var myfield  = null;
    myfield  = document.getElementById("myfield");

            // Incase the group has no Id then get the first '<g>' element
    if(myfield  === null)
            myfield  = document.getElementsByTagName('g')[0];

      var goIn = evt.target;  // thus line is currently not used
  // Fetch the current transform state of the group element into a matrix
  var matrix = myfield.getCTM();
  // Read the scale attributes from the matrix into variable x and y
  // then apply an increment by multiplying
      var x = matrix.a * 1.2;
      var y = matrix.d * 1.2;

    // Set the new transform attribute for the group
    myfield.setAttributeNS(null,"transform", "scale(" + x + "," + y + ") translate(" + matrix.e + "," + matrix.f + ")");

}
   // Zoom out (reduce) function
   function zoomout_click(evt) {

           // variable to get the group transform object
    var myfield  = null;
    myfield  = document.getElementById("myfield");

            // Incase the group has no Id then get the first '<g>' element
    if(myfield  === null)
            myfield  = document.getElementsByTagName('g')[0];

      var goIn = evt.target;  // thus line is currently not used
  // Fetch the current transform state of the group element into a matrix
  var matrix = myfield.getCTM();
  // Read the scale attributes from the matrix into variable x and y
  // then apply a reduction in scale by dividing
      var x = matrix.a / 1.2;
      var y = matrix.d / 1.2;

    // Set the new transform attribute for the group
    myfield.setAttributeNS(null,"transform", "scale(" + x + "," + y + ") translate(" + matrix.e + "," + matrix.f + ")");

}
   // Recenter/reset function
   function recenter_click(evt) {

    // Reset the group to the original transform
    document.getElementById("myfield").setAttributeNS(null,"transform", "scale(1,1) translate(0,0)");
}

A: getCTM is the wrong function to use for this purpose. It includes any transforms applied to the parent SVG due to the viewBox etc.  You are just wanting to manipulate the transform attribute of the "myfield" group.
I would recommend just manipulating the tranform attribute using the predefined DOM functions.
You access the transform attribute DOM by using:
<myfield DOM object>.transform.baseVal

That returns a SVGTransformList object, which is basically an array containing two SVGTramnsform objects. One for the scale() part, and one for the transform() part.  Once you have those objects you can just give them new values, and the SVG will update.

function panup_click(evt) {
  pan(0,-2);
}

function pandown_click(evt) {
  pan(0,2);
}

function panleft_click(evt) {
  pan(-2,0);
}

function panright_click(evt) {
  pan(2,0);
}

// Pan function
function pan(dx, dy) {
  // variable to get the group transform object
  var myfield  = document.getElementById("myfield");
  // Fetch the current value of the transform attribute
  var transformList = myfield.transform.baseVal;
  var translate = transformList.getItem(1);
  // Adjust the translate transform item
  var tx = translate.matrix.e;
  var ty = translate.matrix.f;
  translate.setTranslate(tx + dx, ty + dy);
}

// Zoom in (enlarge) function
function zoomin_click(evt) {
  zoom(1.2);
}

// Zoom out (reduce) function
function zoomout_click(evt) {
  zoom(1 / 1.2);
}

function zoom(scaleFactor)
{
  // variable to get the group transform object
  var myfield  = document.getElementById("myfield");
  // Fetch the current value of the transform attribute
  var transformList = myfield.transform.baseVal;
  var scale = transformList.getItem(0);
  // Adjust the translate transform item
  var s = scale.matrix.a;
  scale.setScale(s * scaleFactor, s * scaleFactor);
}

// Recenter/reset function
function recenter_click(evt) {
  // Reset the group to the original transform
  document.getElementById("myfield").setAttributeNS(null,"transform", "scale(1,1) translate(0,0)");
}
<svg  width="24cm" height="16cm" viewBox="-4 -1 26 20"
      xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

  <g id="myfield" transform="scale(1,1) translate(0,0)" >

    <g transform=" scale(1,-1) translate(0,-16)">
      <g id="togglefield">
        <rect id= "rectangle1" class= "rectangles" x= 2  y= 0  width= 4  height= 6  onClick="fieldDetails(event)"></rect>
        <rect  id="rectangle2" class= "rectangles" x= 2  y= 6  width= 4  height= 5 onClick="fieldDetails(event)"></rect>
      </g>
      <g id="togglefind">
        <circle class="circles" id="find1" cx= 4  cy= 1  r="0.2" onClick="findDetails(event)"></circle>
        <text class="text" x= 4 y= 1  transform="translate(0 2 ) scale(-1,1) rotate(180)"> 1 </text>
        <circle class="circles" id="find5" cx= 4  cy= 7  r="0.2" onClick="findDetails(event)"></circle>
        <text class="text" x= 4 y= 7  transform="translate(0 14 ) scale(-1,1) rotate(180)"> 5 </text>
      </g>
    </g>

    <rect x="12.6" y="12.4" width="3" height="3" fill="white" stroke="grey" stroke-width="0.05"/>
    <text x="13" y="13.2" font-family="Arial" font-size="0.6">Legend</text>
    <g id="Fieldlgd">
      <rect x="12.8" y="13.6" width="0.6" height="0.6" fill="none" stroke="green" stroke-width="0.04"/>
      <text x="13.6" y="14" font-family="Georgia" font-size="0.5">Field ID</text>
      <text x="13" y="14" font-family="Georgia" font-size="0.5">1</text>
    </g>
    <g id="Findlgd">
      <circle cx="13.1" cy="14.7" r="0.12" fill="blue" stroke="red" stroke-width="0.05"/>
      <text x="13.6" y="14.85" font-family="Georgia" font-size="0.5">Find ID</text>
      <text x="13.2" y="14.7" font-family="Arial" font-size="0.45">1</text>
    </g>
  </g>

  <rect x="-4" y="0.3" width="3.2" height="12" fill="white" stroke="black" stroke-width="0" fill-opacity="0.8"/>
  <text x="-4" y="0.8" font-family="San Serif" font-size="3%">Pan and Zoom </text>
  <text x="-2.7" y="1.8" font-family="Georgia" font-size="4%">N</text>
  <polyline id="panup" onclick="panup_click(evt)" points="-3,2 -2.5,1 -2,2 -2.3,1.9 -2.7,1.9 -3,2" fill="lavender" stroke="cornflowerblue" stroke-width="0.05" fill-opacity="0.6"/>
  <text x="-2.7" y="3.4" font-family="Georgia" font-size="4%">S</text>
  <polyline id="pandown" onclick="pandown_click(evt)" points="-3,2.8 -2.5,3.8 -2,2.8 -2.3,2.9 -2.7,2.9 -3,2.8" fill="lavender" stroke="cornflowerblue" stroke-width="0.05" fill-opacity="0.6"/>
  <text x="-3.3" y="2.6" font-family="Georgia" font-size="4%">W</text>
  <polyline id="panleft" onclick="panleft_click(evt)" points="-2.7,1.9 -3.7,2.4 -2.7,2.9 -2.8,2.6 -2.8,2.2 -2.7,1.9" fill="lavender" stroke="cornflowerblue" stroke-width="0.05" fill-opacity="0.6"/>
  <text x="-2.1" y="2.6" font-family="Georgia" font-size="4%">E</text>
  <polyline id="panright" onclick="panright_click(evt)" points="-2.3,1.9 -1.3,2.4 -2.3,2.9 -2.2,2.6 -2.2,2.2 -2.3,1.9" fill="lavender" stroke="cornflowerblue" stroke-width="0.05" fill-opacity="0.6"/>
  <text x="-2.7" y="2.6" font-family="Georgia" font-size="4%">C</text>
  <circle id="recenter" onclick="recenter_click(evt)" cx="-2.5" cy="2.4" r="0.3" fill="lavender" stroke="cornflowerblue" stroke-width="0.05" fill-opacity="0.6"/>
  <polyline id="zoomcross" points="-2.6,4.2 -2.4,4.2 -2.4,4.6 -2.1,4.6 -2.1,4.8 -2.4,4.8 -2.4,5.3 -2.6,5.3 -2.6,4.8 -2.9,4.8 -2.9,4.6 -2.6,4.6 -2.6,4.2" fill="cornflowerblue"/>
  <rect id="zoomIn" onclick="zoomin_click(evt)" x="-3" y="4" width="1" height="1.5" fill="white" stroke="black" stroke-width="0.05" opacity="0.2"/>
  <rect id="zoomdash" x="-2.9" y="5.9" width="0.8" height="0.2" fill="cornflowerblue"/>
  <rect id="zoomOut" onclick="zoomout_click(evt)" x="-3" y="5.7" width="1" height="0.6" fill="white" stroke="black" stroke-width="0.05" opacity="0.2"/>

</svg>


text:
Q: How to find the windows dialing rules in .NET This should be simple, but isn't apparently.  Since..Windows 3 or so, there is a control panel called Phone or Phone & Modem.  In that control panel is a bunch of information about how a modem would dial up, assuming you have a modem hooked up.  For example, do you need to dial 9 to get out, what is the area code, and so forth.  How can i access this information programmatically?  I am using C# .NET 2010.

A: I couldn't find a way to access it through a .Net TAPI wrapper (after a not so long search) so I fired up procmon an found where it was stored in the registry, and here's the code that accesses it (you can adapt it to your specific needs):
RegistryKey locationsKey =
    Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Telephony\Locations");
if (locationsKey == null) return;
string[] locations = locationsKey.GetSubKeyNames();
foreach (var location in locations)
{
    RegistryKey key = locationsKey.OpenSubKey(location);
    if (key == null) continue;
    Console.WriteLine("AreaCode {0}",key.GetValue("AreaCode"));
    Console.WriteLine("Country {0}",(int) key.GetValue("Country"));
    Console.WriteLine("OutsideAccess {0}", key.GetValue("OutsideAccess"));
}

Note :

*

*I recommend to use an official API if there is a .net compatible one.

*This code is not guaranteed to work on other OSes than  Win 7

*If you need to prompt the user to fill in these details you can start the configuration tool using :

Process.Start(@"C:\Windows\System32\rundll32.exe",@"C:\Windows\System32\shell32.dll,Control_RunDLL C:\Windows\System32\telephon.cpl");

A: You are going to need to use Tapi in Windows or pull the information from the registry.  According to Microsoft Tapi 3.0 was not designed to be used from managed code, though the first link seems to have done it.
Some articles to look at:

*

*Tapi3.0 Application Development

*VB.Net accessing TAPI Dialing Rules
From Link #2
Take a look at these TAPI functions:

*

*lineGetTranslateCaps

*lineTranslateAddress

*lineTranslateDialog

*lineSetCurrentLocation

*lineGetCountry

*tapiGetLocationInfo
The info is stored in the Registry at:  HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Telephony\Locations

A: Bit more code to get the prefix
class Program
{
    static void Main(string[] args)
    {
        string rootLocation = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Telephony\Locations";
        getRegistryValues(rootLocation);
        Console.ReadLine();
    }

    public static void getRegistryValues(string rootLocation)
    {
        RegistryKey locationsKey =
        Registry.LocalMachine.OpenSubKey(rootLocation);
        if (locationsKey == null) return;
        string[] locations = locationsKey.GetSubKeyNames();
        Console.WriteLine(locations.Length.ToString());
        foreach (var location in locations)
        {
            Console.WriteLine(location.ToString());
            RegistryKey key = locationsKey.OpenSubKey(location);
            if (key == null) continue;
            foreach (string keyName in key.GetValueNames())
            {

                if (keyName.Equals("Prefixes"))
                {
                    string[] Prefixes = ((string[])(key.GetValue(keyName)));
                    Console.Write("Prefixes ");
                    foreach (string prefix in Prefixes)
                    {
                        Console.Write(prefix);
                    }

                }
                else
                {
                    Console.WriteLine(keyName + " {0}", key.GetValue(keyName));
                }

            }

            getRegistryValues(rootLocation+@"\"+location);

        }

    }


text:
Q: Rails - linking to parent associations I'm trying to make an app with Rails 4.
I have a project.rb and a project_student_eoi.rb.
The associations are:
project has many project student eons
project student eois belong to project

On my project show page, I have a link to a form where students can express interest in joining a project.
<% if can? :read, Project && current_user.profile.has_role?(:student) %>
          <%= link_to  'Join this project', new_project_student_eoi_path %>
        <% end %>

Then on the new page (which nests the form), I have a back link, which should go back to the project itself. The scaffolding structure goes back to an index of all the project student eois. I'm trying to change this so that the path goes back to the project.
I've tried all of these variations and am not getting anywhere. I'm struggling with associations generally. My project student eoi table has an attribute called :project_id. I want to use that to match up to the project which is being used to send the link to the new expression of interest form.

    Express your interest in this project

  <%= render 'form' %>

    <%= link_to 'Back', project_path(:project_id => project.id) %>

I have also tried:
<%= link_to 'Back', project_path(:project_id => :project.id) %>
<%= link_to 'Back', project_path(project_id: @project.id) %>
<%= link_to 'Back', project_path(project_id: => project.id) %>

and several other variations - how do you do this?

A: You need to pass "project_id" param on "Join This Project"
app/views/projects/show.html.erb
<% if can? :read, Project && current_user.profile.has_role?(:student) %>
    <%= link_to  'Join this project', new_project_student_eoi_path(project_id: @project.id) %>
<% end %>

and then make sure project_id attribute is set on "new" action
app/controllers/projects/project_student_eois_controller.rb
class ProjectStudentEoisController < ApplicationController
  def new
    @project_student_eoi = ProjecStudentEoi.new(project_id: params[:project_id])
  end
end

once project_id is set, you can use this :
<%= link_to 'Back', project_path(@project_student_eoi.project) %>


text:
Q: Laravel 4 Redirect::action() "Route not defined" I'm currently having troubles with Laravel 4. I would like to use slugs for forum categories and forum topics (slugs are unique). In order to determinate if the user is in a category or in a topic, I have this route:
Route::get('forum/{slug}', function($slug) {

    $category = ForumCategory::where('slug', '=', $slug)->first();

    if (!is_null($category))
        return Redirect::action('ForumCategoryController@findBySlug', array('slug' => $slug));

    else {

        $topic = ForumTopic::where('slug', '=', $slug)->first();

        if (!is_null($topic))
            return Redirect::action('ForumTopicController@findBySlug', array('slug' => $slug));

        else
            return 'fail';

    }

});

And I have the following error when I try to reach a category:
Route [ForumCategoryController@findBySlug] not defined.
Here is my ForumCategoryController:
class ForumCategoryController extends BaseController {

    public function findBySlug($slug) {

        $category = ForumCategory::where('slug', '=', $slug)->first();

        return View::make('forum.category', array(
            'title'         => 'Catégorie',
            'category'      => $category
        ));

    }

}

Where is the problem ? Is there a way to do it better ? Help please :)

A: Laravel is telling that you have to define a route to use Route::action(), something like:
Route::get('forum/bySlug/{slug}', 'ForumTopicController@findBySlug');

Because it will actually build an url and consumme it:
http://your-box/forum/bySlug/{slug}

For that it must find a route pointing to your action.


text:
Q: jquery a good method to handly last output to page I am looking for a good way to handle a link click of different lines
Each line is added at different times and i want only the most recently added line's links to be clickable. they are all under the same div tag
ex:
line 1:  "this is a line <link here>"  <-- dont want these to be clickable
line 2:  "this is a line <link here>"  <-- but still viewed
line 3:  "this is a line <link here>"  <-- most recent line clickable

hopefully this is being explained correctly
the lines are added with .before function
So i added  to indicate each line. the link are indicated by a class id called talk_action and each line can contain more than one link. so somehow i need to set up an on click for the .talk_action which is clicked under the last paragraph. when the link is clicked it grabs the link id and passes it to a php file
ex:

would you like to shop or talk about quests

A: Assuming all the lines are in a div with id="lines"
$("#lines").on("click","a:last",function(){
     // your action here
});

This uses:

*

*Event delegation to always remain "updated" to the last link

*The :last selector to always match the last one

*The click event

Here is a demo

A: The ':last' selector may suitable for you
$( "a:last" )

A: Hi the below code will work as expected..
http://jsbin.com/afUKiJi/1/edit
$(".clickable").find('a').last().on('click',function(){
alert('last');
})

A: Here is a jsFiddle. This will also take into account recently added anchors and is using event delegation in jquery.
$('div').on('click','a:last', function(){
console.log(this);
});


text:
Q: JWT token parsing failed [31204], how to fix? When I execute Twilio.Device(token) I'm getting an error:  {code: 31204, message: "JWT token parsing failed"}.
This service (https://jwt.io/#debugger-io) is able to decode this tokens, but my js-client is not. In addition, I know that this tokens can be parsed by SDKs for iOS & Android, so I'm intresting what's wrong with my js-app?
I can share the results of #debugger-io's parsing:
[header]{
  "alg": "HS256",
  "cty": "twilio-fpa;v=1",
  "typ": "JWT"
}

[payload]{
  "exp": 1553784490,
  "grants": {
    "identity": "24e7e8b3-bb57-5c6e-8f38-9964e6d4edf7",
    "video": {
      "room": "d45373f6-5c78-5d8f-997f-c6f070be940d"
    }
  },
  "iat": 1553780890,
  "iss": "// some string here",
  "jti": "// some string here",
  "sub": "// some string here"
}

I've already tried to execute Twilio.Device from token that was getting from quick-start-app, and it works fine. Also I'd been using quick-start-app with my token and it was also broken by this error.
The code below is a way how I'm getting token on client:
class CallService{
   constructor(private authService: AuthService, private requestService: RequestService){}

   public getCallToken$(callId: string): Observable<{token: string}>{
    return this.requestService.post('here is our service-url',{
        roomName: callId,
        userName: this.authService.user.uuid
      }
    ).pipe(catchError((err: HttpErrorResponse) => {
      console.warn(err);
      alert(`Can't use calls with those parameters: { roomName: ${callId}, userName: ${this.authService.user.uuid} }`);
      return confirm('Try it again?') ? this.getCallToken$(callId) : throwError(err)
    }))
  }

   public createDevice(token: string): Twilio.Device{
      console.log(token);
      return new Twilio.Device(token, {debug: true})
   }
}

// this code with injected CallService
this.callService.getCallToken$('//random-id').subscribe(
   {token} => {
      const device = this.callService.createDevice(token);
      device.on('error', err => console.warn(err));
      device.on('ready', d => { // ... })
      // ... other manipulations
   }
)

I asked my backend developers whether they transform tokens from twilio-api, and they said 'no'.


text:
Q: Get time value from textbox and perform calculations? I'm trying to retrieve a time value from a textbox and perform calculations on it.
Use case example: User inputted time (8:00 am) - (30 minutes)
I'm getting the value by the getElementById method, but I am unsure how to make it read in a proper time format and do the calculations.
Could someone point me in the right direction, please?


text:
Q: Can Statsvn filter out statistics by date Just wanted to check if there is any configuration or parameter to get statistics in a provided date range rather than it's giving stats from DAY1?

A: Since StatSVN is running on locale log files, it's totally possible:

*

*Check out a working copy of your project from Subversion.
svn co svn://server/repo/trunk/modulename

*Create a Subversion log file, specifying the date range you want:
svn log -v -r {2012-05-01}:{2012-05-31} --xml > logfile.log

*Run StatSVN:
java -jar /path/to/statsvn.jar /path/to/module/logfile.log /path/to/module
This command creates the HTML reports in the current directory.
More details are available from the User Manual.