text:
Q: Server has apache installed. How to install nginx alongside it? Apache is installed and is used to serve mostly Django/Python content. I want to install nginx to serve static content. How to do it and what is a good configuration.
I am on Ubuntu and Apache was installed via apt-get.

A: *

*first option: do you have few ip addreses? bind apache to one of them, nginx to another.
in debian world
for apache in /etc/apache2/ports.conf include:
Listen 1.1.2.3:80

in vhost file in /etc/apache2/sites-enabled change:
NameVirtualHost 1.1.2.3:80;
<VirtualHost 1.1.2.3:80>
..
<VirtualHost/>

for nginx in /etc/nginx/sites-enabled/ add:
listen 1.1.2.4:80

*second option: move apache to listen on different port [ files as above. tell apache to listen on 127.0.0.1:8080 for instance ] and instruct nginx to reverse-proxy dynamic traffic to your apache while serving /static/ by nginx - for instance:
server {
 listen   1.1.2.3:80;
 server_name  some.name another.dname;

 access_log  /var/log/nginx/something-access.log;

 location / {
  proxy_pass http://localhost:8080;
  proxy_redirect off;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 }
 location ~* ^.+\.(jpg|js|jpeg|png)$ {
  root /some/where/on/your/disks;
 }

; put your static hosting config here.
}

btw - think about putting static content on another domain. this should improve end-user speed a little.

A: There are many variations on how to accomplish this.  I prefer to have one application dedicated to deciding on which server handles what kind of content, while the back end servers simply serve the files they've been requested.
To that end, I employ the Varnish reverse proxy on the front end, listening on port 80.  Behind that, I have Apache (port 8880) and nginx (port 8881), both configured for the same domains and pointing to the same directory structure.  In my Varnish config file, I have something like this:
backend apache {
  .host = "192.168.0.2";
  .port = "8880";
}
backend nginx {
  .host = "192.168.0.2";
  .port = "8881";
}

[...]

if (req.url ~ "\.(png|gif|jpg|ico|html|htm|js|css|txt)$") {
  set req.backend = nginx;
} else {
  set req.backend = apache;
}

Of course, there's a little more to it, but you get the idea.
Since you already have Apache and nginx installed, you may want to browse this link, which describes a very simliar situation to yours, but uses nginx as the front end for static content and then passes on requests to Apache.
If you want to go really  simple, you could simply use a reverse caching proxy (such as Varnish or nginx) in front of Apache.  What it will do is cache requests to quickly serve them out to clients, while at the same time relieving the web server itself from serving identical requests.  This, by its very nature, will give the same effect as what you're asking for.  Since static pages and images rarely change, they will be almost always cached by the front end, whereas dynamic pages will be detected as such and always passed on to the back end.


text:
Q: Item still deleted when click on OK in ItemDeleting event CancelWithError     public override void ItemDeleting(SPItemEventProperties properties)
    {
        try
        {
            properties.Status = SPEventReceiverStatus.CancelWithError;
            properties.ErrorMessage = SPUtility.GetLocalizedString("$Resources:MyResources,ER_DeletionError", "MyResources", properties.Web.Language);
        }
        finally
        {
            //_currentContext.Response.Redirect(properties.WebUrl, true);
        }
    }

Now it works fine, it doesn't deletes the item, but when i click on "OK" for error message, item disappears from screen and comes back only when i refresh the page, any clues ?
Edit
It only happens when your list is opened in "Edit in Datasheet" view, otherwise it takes you to another window with error.

A: Not a solution for everyone but I used jslink to add a post render method for this custom list, in post render method I am refreshing page after click event on delete error message box.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cloud function is writing NaN to firestore I created a cloud Function to update a following count every time there is a new follower. However, for whatever reason, NaN gets written to the document instead of an incremented count. What is NaN and why is it getting written instead of the appropriate number? This is my code:
var transaction = db.runTransaction(t => {
    return t.get(countRef)
        .then(doc => {
            var new_count = doc.data.following_count + 1;
            t.update(countRef, { following_count: new_count });
        });
}).then(result => {
    console.log('Transaction success!');
})
.catch(err => {
    console.log('Transaction failure:', err);
});

A: NaN is Not a Number. As some commenters said (but without actually posting an answer), this is caused by operations on non-numeric input, such as undefined values or strings.


text:
Q: Error in Lua Repl.it - User Input not functioning correctly In this program: https://repl.it/EvM6, io.read() should cause input to be assigned to a variable, which is then printed to the screen. But, an odd error appears, which reads,

"{"command":"input","data":"foo\n","error":""}".

Why does this error occur? Is there any way to fix it?

A: The function io.read() was substituted with custom one. The result returned by standard io.read() will be different.
A quick-and-dirty way to fix it:
local io_read_orig = io.read
function io.read()
  return (
    loadstring(
      "return "..io_read_orig():match[[^{"command":".-","data":(".*"),"error":".*"}$]]
    )():gsub("\n$","")
  )
end

-- By StarBuck
print("Type something, then press enter.")
local input = io.read()
print(input)

A: this is an engineer at Repl.it. This was a bug in our Lua REPL implementation. It's now fixed. I apologize for the confusion.


text:
Q: How can I find all symlinks linking to a renamed volume? I had a change a volume name and I have dozens of (now broken) symlinks (at least) throughout my system.
How can I easily find all symlinks matching my old volume name?
Let's assume my old volume was named "OldVolume" and my new one is named "NewVolume".
I assume it will be some version of:
find / -type l -ls

A: find . -type l | (while read FN ; do test -e "$FN" || ls -ld "$FN"; done)

will find your broken symlinks. To limit the output, you could simple pipe the above into a grep:
find . -type l | (while read FN ; do test -e "$FN" || ls -ld "$FN"; done) | \
    grep OldVolume


text:
Q: Why does my Ubuntu 20.04 laptop crash often? I've dual booted my laptop with Ubuntu and have been using it for the most part for the past 6 months I'm facing a few issues :

*

*My Laptop crashes most often when battery is low.I assume its a hardware problem I often hear loud fan noises too

*I checked into my Hard disks status and found this:
Disk is OK, 609 bad sectors (40° C / 104° F)
How do I resolve this issue?I know I'll have to backup as soon as possible.
Model : ST1000LM035-1RK172 (LCM2)
Size : 1.0 TB (10,00,20,48,86,016 bytes)
RAM : 8 GB


text:
Q: Hilbert curve scheduling not theoretically well defined? In high-dimensional task scheduling, it is common to use a Hilbert-curve ordering. Given a set of points $\{p_i\}_{i=1}^N \subset \mathbb{R}^d$ the goal is to linearly order them such that points nearby in space are also nearby in order. The heuristic behind Hilbert curve scheduling is that ordering based on distance along a Hilbert curve tends to preserve locality.
In practice, you divide space into sufficiently small dyadic boxes, round the location of the points to the centers of those boxes, then order the points based on their distance along the finite order Hilbert curve approximation that passes through each of the boxes exactly once, as demonstrated on the blue points in the following image

On the other hand, since $[0,1]$ is not homeomorphic to $[0,1]^2$ and since the fully infinite Hilbert curve is onto and continuous, it can't be 1-1. Thus it seems to me that Hilbert curve ordering is not a well-defined concept - for a point that is mapped to twice, it has no clearly defined "Hilbert distance" along the Hilbert curve.
Is this right, or is there something I'm missing? I think the above reasoning is pretty bulletproof, but I haven't seen the issue even mentioned in the computational literature.

A: The Hilbert curve, understood as the limit of an infinite iterative process, is not one-to-one. But in actual computations one works with an N-th generation of the iterative construction, not with the limit as $N\to\infty$. For example, yours is the 2nd generation curve, and it is a bijection between the linear set $0,1,\dots,15$ and the square matrix $4\times 4$. Maybe it should be called pre-Hilbert curve to emphasize the distinction, but usually it is clear from context whether we have a concept from analysis/topology or from finite mathematics. Computers never let $N\to\infty$, do they?
You may find this relevant: computation of Hilbert distance in Haskell


text:
Q: Is there a way to stack a CardView within a RecyclerView from the bottom instead of from the top? I'm a newbie when it comes to Android coding, so please bear with me. I looked this up for quite some time before posting here, so that I don't waste your time with a question that I could have answered myself through some research.
Here's my issue: I have a CardView and I want the items to start popping up from the bottom instead of from the top. For example, something like this.
I found out that you can do this via the "stackFromBottom" XML attribute in ListViews and GridViews, but it doesn't work for CardViews.
I also noticed that you can change a ListView's gravity, but CardView doesn't seem to support that either.
So is there a simple way to populate the CardView in this way?
Any help would be greatly appreciated.

A: CardView can hold only a single item, so in this case you can have a ViewGroup inside the CardView , and add those items to the ViewGroup.
I'd suggest ConstraintLayout and constraint the first view to the bottom of the layout and next views are constraint to their bottom views so that you can fill them from the bottom.
If your list is big.. You can wrap the ConstraintLayout with ScrollView so that the items can be scrolled; or replace the entire approach by a RecyclerView

A: Since you said that you are using a recycler view you could use a simple property to accomplish what you need.


text:
Q: Конфликт работы якорный ссылки и javascript Переход по якорной ссылке работает только один раз. После этого одного раза просто закрывается менюшка без перехода( речь о мобильной версии). Если js убрать, то переходы идут нормально, но остаётся открытой менюшка.

$('a.small').click(function() {
  var layout = document.querySelector('.mdl-layout');
  layout.MaterialLayout.toggleDrawer();
});
<!doctype html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.light_green-orange.min.css" />
  <link rel="stylesheet" href="style.css" />

          Главная
          Расписание
          Задачи
          Сверхзадачи
          Контакты
          Регистрация

      Игронет

        Главная
        Расписание
        Задачи
        Сверхзадачи
        Контакты
        Регистрация

                                    «ПРОФЕССИИ БУДУЩЕГО»

                                        ОБРАЗОВАТЕЛЬНЫЕ ФОРУМЫ
                                        ДЛЯ ПОДГОТОВКИ ИГРОТЕХНИКОВ
                                        «ПРОФЕССИИ БУДУЩЕГО»
                                        РОССИЙСКОГО ДВИЖЕНИЯ ШКОЛЬНИКОВ

Наша главная задача не передать вам знания, наша задача побороть ваш страх перед незнанием, научить вас учиться.

              Участники:

250-300 человек, педагоги, студенты, специалисты по работе с РДШ

              Фокус-группа:

300-400 детей в каждом регионе

                                    Зарегистрироваться

Наше расписание:

              День 1

                done

                                Открытие

                done

                                Пленарное заседание

                done

                                Брейн Фитнес

                done

                                Обучение игровым кейсам и практикам

              День 2

                done

                                Практикум в школах региона по отработке игр

                done

                                Обучение игровым кейсам и практикам

              День 3

                done

                                Практикум в школах региона по отработке игр

                done

                                Тренинги по выстраиванию образовательных и карьерных траекторий

              День 4

                done

                                Подведение итогов

                done

                                Оформление договоров на аттестацию робототехников

                done

                                Подписание соглашений

                done

                                Торжественное закрытие форума

                done

                                Культурная программа

Наши задачи:

1

Подготовка 10 -15 новых профориентационных игр и использование игр из «Атласа новых профессий»

2

Обучение педагогов и активистов, работающих с РДШ 3 компетенциям:

-проведение тренинговых и активных образовательных форм работы;

-проведение конкретных кейсов деловых игр и отработка на фокус-группах;

- принципы создание собственных деловых игр;

- обучение работе с атласом новых профессий.

3

              Формирование профессионального сообщества игротехников, создание собственных кейсов игр

4

              Проведение чемпионата игротехников, запуск профессионального движения игротехников в образовании

Сверхзадача:

Включение РДШ в работу с Атласом Новых Профессий (фактически привнести атлас в каждую школу)

Создание интерактивной формы образования (в перспективе могут осуществлять сами школьники по принципу старшие-младшим)

Формирование в школах и педагогической среде повестки НТИ

Создание готовой программы ежедневной работы для актива РДШ в регионах

            <input class="mdl-mega-footer__heading-checkbox" type="checkbox" checked>

Партнёры

РАНХиГС

Школа Будущих Президентов

Агенство Стратегических Инициатив

Общественная палата РФ

Администрация Президента РФ

Российское движение школьников

Школа Будущих Президентов

О нас

Контакты

A: Если в onclick='' каждого элемента меню прописать window.location="index.php#main"; var layout = document.querySelector(".mdl-layout");layout.MaterialLayout.toggleDrawer(); return false; всё будет работатью


text:
Q: Error while mail trigger I have the program for mail trigger. I have access rights for mail trigger from my machine to SMTP server. Even I am able to telnet and ping to 10.242.175.70/25 . But when I am running my program on my machine I am facing error as below. Please help me to resolve this and also let me know where I am doing wrong. I have provided the activatio.jar and mail.jar, if I am missing any other jar then let me know that too.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail
{
   public static void main(String [] args)
   {
      // Recipient's email ID needs to be mentioned.
      String to = "mohit.darmwal@cognizant.com";

      // Sender's email ID needs to be mentioned
      String from = "mohit.darmwal@cognizant.com";

      // Assuming you are sending email from localhost
      String host = " 10.243.33.234";//"localhost";//"192.168.195.68";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("10.242.175.70", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

A: Checkout JavaMail API for reference which properties to set and how to fill them.
The specific error in this case was setting the hostname wrong:
  // Setup mail server
  //Does not work this way:
  //properties.setProperty("10.242.175.70", host);
  //Use correct property name
  properties.setProperty("mail.smtp.host", "10.242.175.70");


text:
Q: Which .Net component should be used for tcp/ip sockets communication? We need to talk to another system that wants to communicate to us via raw tcp/ip socket communication.  What would be the appropriate .Net object, if any, to use for this?
If you know of a 3rd party component, open source component, etc., that you think is better to use, please feel free to mention that as well.

A: I would use TcpClient.  It sits on top of Socket and is an abstraction upon Socket.  TcpClient has GetStream which returns a Stream object.  Then to read the stream you can simply use a stream reader.
For example:
tcpClient = new TcpClient(host, port)
                            {
                                ReceiveTimeout = readTimeout
                            };
            stream = tcpClient.GetStream();
            streamReader = new StreamReader(stream, Encoding.ASCII);
            streamWriter = new StreamWriter(stream, Encoding.ASCII)
                               {
                                   AutoFlush = true
                               };

            return this;

Which then allows (snippet):
streamReader.Read(myReadBuffer, 0, myReadBuffer.Length)

A: Our company uses Dart Socket.net which basically wraps system.net.sockets.socket into really easy to use methods/components as well as having features of their own. I recommend them for windows form applications. They have lots of examples that come with their demos and have an active support forum that you can post questions and receive support/suggestions from.
Check them out at Dart.com http://www.dart.com/ptsknet.aspx

A: System.Net.Sockets.Socket
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx

A: The TcpClient is the most common, though I prefer the Socket class myself. Either will work.

A: Socket & TCPClient are both pretty easy to manage and efficient.  They'll definitely do what you need. There are a variety of good reasons to use the async modes of either.
Be warned that there are some threading issues.  For instance, some of the async methods will terminate when the calling thread exits.  There are a lot of very inefficient/bad .NET multi-threaded server examples out there too, so be careful.  One last thing to watch out for is the exception handling.  Often you just get a "SocketException" back and have to inspect it to figure out what really happened.  It would be great if there were a few more derived SocketException classes that could be handled independently.
But don't let me discourage you, once you get your code implemented and working it'll continue to "just work" from then on.


text:
Q: Variable references the wrong iterator, even after confirmed reassignment I have the following loop that reassigns to an iterator variable:
currentPrime = None
sieve = iter(range(2, 10))
while True:
    try:
        # The first value should be prime.
        currentPrime = next(sieve)
    except StopIteration:
        # Stop when sieve is empty.
        print(currentPrime)
        break
    print(currentPrime)
    # Filter out all multiples of currentPrime.
    sieve = (x for x in sieve if x % currentPrime)
    #print(tuple(sieve))

Even though I apply a filter on each iteration of the loop, the output goes through the entire range:
2
3
4
5
6
7
8
9
9

If I uncomment the last print call, I see (3, 5, 7, 9), which means the filter and assignment to sieve work correctly, but the next(sieve) call somehow accesses the original iterator which no variable points to.
Any idea what's happening here? I'm using Python 3.7.0.

A: As user2357112 said, "currentPrime is looked up on use, not on generator creation."
One solution is to use filter with a lambda that localizes the current value of currentPrime. Note how the lambda uses a default argument to create a local variable:
currentPrime = None
sieve = iter(range(2, 10))
while True:
    try:
        # The first value should be prime.
        currentPrime = next(sieve)
    except StopIteration:
        # Stop when sieve is empty.
        print(currentPrime)
        break
    # Filter out all multiples of currentPrime.
    sieve = filter(lambda x, prime=currentPrime: x % prime, sieve)

A: There is a stack of generators if I'm not wrong.
What happens (TL;DR: all generators refer to one currentPrime instance and refer lazy):

*

*Get value 2 from range iterator.

*Create generator expression (A). Variable currentPrime = 2 now and is NOT free (not in closure). Generator consume rest of range (3..9).

*Get value 3 from generator A (3 % 2 is True)

*Create generator expression (B).  Variable currentPrime = 3 for both generators (A, B). Generator consume rest of generator A (4..9).

*Get value 4 from generator B. See: next() → B.next(A) → A yields 4 (A checks: 4 % 3 is True), then B checks 4 % 3 is True.

*Create generator expression (C) ... and so on.
Variable in in generator is not in closure, see:
>>> a = 5
>>> gen = (a for i in range(3))
>>> a = 3
>>> list(gen)
[3, 3, 3]


text:
Q: How to replace all td elements inside tr? I have html table on my parent page that has some data:
Begin Date  End Date    City
03/28/2017              Toronto
03/25/2017  03/26/2017  Miami
03/22/2017  03/24/2017  Chicago
03/16/2017  03/21/2017  Dallas
03/10/2017  03/15/2017  Austin

After use update the element from specific row I would like to replace entier content of that row. Each row had unique id. I have to do this with plain JavaScript Vanilla. Here is my example what I have so far:
fnObj.DATA is numeric and I get that after my ajax call is successfully completed. I use the id from that callback function to detect the row that I want to update. I'm not sure what is the best technique to replace all the td tags. This technique works with one exception. There is no id on the row that I have replaced the data. If anyone knows better way to do this please let me know. Thank you.
window.parent.document.getElementById("New_"+fnObj.DATA).outerHTML = ""+document.getElementById("newBegDt").value+"	"+document.getElementById("newEndDt").value+"	document.getElementById("newCity").value	";
                        window.parent.document.getElementById(dType+"_"+fnObj.DATA).id = 'New_'+fnObj.DATA;

A: Try this:
var newtr = "
"+document.getElementById("newBegDt").value+"	"+document.getElementById("newEndDt").value+"	" + document.getElementById("newCity").value + "
";

$("#New_"+fnObj.DATA ).replaceWith(newtr);

If you don't want to use jquery you can use something like:
var currentTr = document.getElementById("New_"+fnObj.DATA), parent = currentTr.parentNode,
tempDiv = document.createElement('div');

tempDiv.innerHTML =  "
"+document.getElementById("newBegDt").value+"	"+document.getElementById("newEndDt").value+"	" + document.getElementById("newCity").value + "
";

var input = tempDiv.childNodes[0];

parent.replaceChild(input, currentTr);


text:
Q: Querying an array of objects in postgres myTable
{
 "creator": "xyz@gmail.com",
 "data": {
  "sections" : [],
  "sharing": [
    {
     "key": "value",
      "user": "abc@gmail.com"
    },
    {
     "key": "value",
     "user": "xyz@gmail.com"
    },
    {
     "key": "value",
     "user": "qwe@gmail.com"
    }
   }
}

I have above table stored in postgres, and data column stored in jsonb format, I want to query with user email eg. user : qwe@gmail.com
I have tried below query but the response is slow
SELECT creator, data - 'sections' AS data FROM myTable WHERE (data->'sharing')::text LIKE '%qwe@gmail.com%' ORDER BY xmin::text::bigint DESC

A: Use the contains operator @>
select ..
from mytable
where data -> 'sharing' @> '[{"user": "qwe@gmail.com"}]'


text:
Q: [tag:]s in meta profiles wrongly(?) link to meta-tag I've noticed that tags inside a user's profile description, i.e. [tag:tagname], when viewed from the meta profile, sometimes link to the meta-tag, not to the main-site tag like it normally does in meta-posts or comments.
This can be seen on my stackoverflow profiles: main-site, meta.
Strangely, on my puzzling profiles (main-site, meta) this doesn't occur anymore, all the tags link to the main site. If I remember correctly, this "fix" happened once I edited my profile again, trying out if meta-tag works on one of the tags. (Edit: This has been reset, it now links to the meta tags again, but I still have the screenshot of it linking to the main site below (2nd one))

*

*Screenshot of Meta-SO-Profile linking to the meta tag

*Screenshot of Meta-Puzzling-Profile linking to main-site tag

I've read the official formatting help, but it in the section Tags it only says

To talk about a tag on this site, like-this, use
See the many questions tagged [tag:elephants] to learn more.
The tag will automatically be linked to the corresponding tag info
  page.

and in the section Comment Formatting it furthermore says

*

*[tag:tagname] and [meta-tag:tagname] – link to the given tag's page.    Link text is the name of the tag. meta-tag only works on meta
  sites.

which both don't seem to help me with my problem. Please also note that the [tag:like-this] example only links to meta here (I guess that's because you can't ask questions directly on the main site of this meta and therefore there also aren't any tags there) , on every other meta site I've tried it would link to the main-site.

Is this a bug that needs to be fixed?

A: This appears to be an old bug that has been long-since fixed, but the issue is that we store both the markdown and the rendered HTML in the database, serving the rendered HTML when possible. Because of the old bug, the HTML for your profile had relative links, i.e. /questions/tagged/java. I've forced it to re-bake your HTML, and you now have absolute links, i.e. http://stackoverflow.com/questions/tagged/java - although actually, I suspect this should really be a protocol-relative link, i.e. //stackoverflow.com/questions/tagged/java.


text:
Q: SQL error code #1452 I am trying to create foreign key for my database. My database is for a gym system.
I have the table called user. Within that table I have user_id which is my primary key.
I have another table call member within this table I also have user_id which I want to make a foreign key so it relates to my user_id within the user table.
But i keep getting the following error..

#1452 - Cannot add or update a child row: a foreign key constraint fails (Gym_System.#sql-247a_3c1, CONSTRAINT #sql-247a_3c1_ibfk_1 FOREIGN KEY (user_id) REFERENCES members (user_id))

Can anyone help?


text:
Q: Configuração Rede via prompt Como desativo via prompt de comando as caixas de seleção "Usar script de configuração automática" e também "Não usar servidor proxy para endereços locais"?
Para desabilitar o proxy, estou usando o comando:
 "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f

Gostaria de saber como posso desativar as outras duas caixas de seleção seguindo a mesma ideia do comando que ja tenho. Assim deixo tudo em um .bat

A: Crie um arquivo com a extensão .reg(exemplo: proxy.reg) com o código abaixo:
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
"MigrateProxy"=dword:00000001
"ProxyEnable"=dword:00000001
"ProxyHttp1.1"=dword:00000000
"AutoDetect"=dword:00000000
"ProxyServer"="http://seu_servidor_proxy:80"
"ProxyOverride"=""

Aqui você ativa ou desativa o proxy
Ativo
"ProxyEnable"=dword:00000001

inativo
"ProxyEnable"=dword:00000000

Para ativar novamente o "Usar script de configuração automática", modifique a linha
"AutoDetect"=dword:00000000

para
"AutoDetect"=dword:00000001

Para ativar novamente o "Não usar servidor proxy para endereços locais", modifique a linha
"ProxyOverride"=""

para
"ProxyOverride"="<local>"

E para colocar o seu .reg em um .bat é simples:
REGEDIT.EXE  /S  "proxy.reg"

A: Faz da seguinte maneira que vai dar certo:
dim oShell
set oShell = Wscript.CreateObject("Wscript.Shell")
configURL = "script_de_proxy"
configURL0 = ""

if msgbox("Navegar com Proxy?", vbQuestion or vbYesNo) = vbYes then
oShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\AutoConfigURL", configURL, "REG_SZ"
else
oShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\AutoConfigURL", configURL0, "REG_SZ"
end if

Set oShell = Nothing

A: Faz da Seguinte maneira:
dim oShell
set oShell = Wscript.CreateObject("Wscript.Shell")
configURL = "AQUI SEU SCRIPT DE CONFIGURAÇÃO"

if msgbox("Habilitar Proxy?", vbQuestion or vbYesNo) = vbYes then
oShell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\AutoConfigURL", configURL, "REG_SZ"
else
oShell.RegWrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable", 0, "REG_DWORD"

End if

Set oShell = Nothing


text:
Q: Swift - Put Red Dot on iPhone App Icon Any ideas how to apply a red dot to the iPhone App icon - like the Mail or Messages' Icon with the number of unread messages in it?

A: Try this:
Swift 2:
 UIApplication.sharedApplication().applicationIconBadgeNumber = 1// or you value

Hope this helps!


text:
Q: Textmate Cucumber "Undefined Step" even though it exists After having a lot of issues with Textmate and Cucumber, I've gone through a lot of steps of reinstalling git so that I could update and install a later version of ruby on rvm, changing from the rvm-auto-ruby to rvm-wrapper, I am now getting it to run but 'Undefined step'
Hoever, the step exists and my guard reads it all fine.

*

*I am using the latest rvm and ruby-head

*I am using cucumber/cucumber-rails 1.0.2

*It is definitely using the right Ruby/Gemset

tl;dr
Cucumber Bundle is not reading my steps when I hit Run.

A: In your config/cucumber.yml you might need to add --require features in the standard options, it will probably have a line like this:
std_opts = "--format #{ENV['CUCUMBER_FORMAT'] || 'pretty'} --strict --tags ~@wip"

Change it to read
std_opts = "--format #{ENV['CUCUMBER_FORMAT'] || 'pretty'} --strict --require features --tags ~@wip"


text:
Q: Every point of an interval $[0;1]$ lies in $k$ subintervals $A_i$. Show that $k \le \sum_{i=1}^n |A_i|$ Suppose that every point of an interval $X=[0, 1]$ lies in at least $k$ subintervals $A_i \subset X$, $i=1, ..., n$. Show that $$k \le \sum_{i=1}^n |A_i|$$
where $|A_i|$ denotes the length of $A_i$.
My thoughts:
Let's consider $k$ copies of $X$. We will denote j-th copy as $X^j$.
If we would be able to cover them with $\{A_i\}_{i=1}^n$ then we're done.
(it is also enough to left uncovered the set of measure zero in every copy).
Let's fix an arbitrary point $x \in X^1$. There exists $1 \le i_1 \lt ... <i_k \le n$ such that $x \in A_{i_j}, j=1,...,k$. Then we will use $A_{i_j}$ to cover everything it can on the copy $X^j$. Now, let's choose another point $x \in X^1$ and repeat the process.
There is a hard part in this proof. I can't understand why it can not be the case when we used all our $A_i$ but didn't fully cover every copy $X^j$(or didn't left uncovered the set of measure zero in every copy).

A: This is easy: $\sum_i \chi_{A_i}  (x) \geq k$ for each $x \in X$. [Each term is $0$ or $1$ and at least $k$ terms are equal to $1$].  Integrating we get $k \leq \sum|A_i|$,


text:
Q: Converting old organ keyboard to MIDI I have a very old keyboard, a CASIO MA-100 that I want to convert to a MIDI keyboard:

Being a programmer and a digital electronics enthusiast, I know how to do it, but I could use some help to save time.
I guess the biggest issue is choosing a µC. Something with a USB interface* would be great, something that can also be powered by USB, even better. Then there's the issue of talking MIDI or MIDI-over-USB. I don't know how hard they would be, but I could probably do with some already written code there, too. (Unless they're very simple and don't need much testing.)
I looked around some electronics project sites this morning, trying to find some open source MIDI or MIDI-over-USB controller firmware, but couldn't.
I did find some Arduino projects, but a prototyping board seems a bit overkill for such a simple project.
The key matrix is 10x8 (10 select in * 8 data out), simple boolean logic, no velocity data. (Though two select lines are easily expendable.)
So I guess my simplest option would be a ~1 MHz µC with 8 input, 8 output pins and a serial buffer (+I/O pins) for MIDI. My best would be a project called "USB MIDI device firmware for Make SeriesXX microcontrollers."
Any ideas?
*: An easy USB interface, i.e. not PIC18. (Edit: This was a simple prejudice arising from the state of the organisation and documentation of the PIC USB framework a few years back. I guess it's time to break it.)

A: If easy is what you're after then I would seriously recommend the Arduino UNO and an ICSP programmer.  The Atmel 8U2 chip that powers the USB can be re-flashed with a firmware that emulates a MIDI device (available here).
The number of IO lines can be expanded using any number of methods including simple shift registers, or SPI solutions like the Microchip 23S17 16-port IO chip, or things like 4-to-16 decoders (ideal for "scanning" matrix lines).

A: There is a project called V-USB-MIDI, based on Atmel AVR ATMega16 and Objective Development's software-only USB firmware.
The latter I've tried myself in a few simple projects (using ATMega chips, e.g. ObDev's Metaboard and a few custom devices). It is fairly simple to use V-USB if emulating USB HIDs, like mice and keyboards.
The former, however, I haven't tried personally yet. I do have a broken synth keyboard lying around, so it'd be swell if you posted the results, independent of your final choice. :)

A: Sounds like a PIC 18F2550 is just the thing, or maybe a 18F4550 if the extra I/O lines are needed.  I don't know why you say a PIC 18 is not easy.  You say you are a programmer, so I don't see what you're afraid of.  Perhaps nobody has done a MIDI USB interface ready for you to add the keyboard scanning code to, but certainly there are various examples of the basic USB driver out there.  Microchip has some code, and so do I.  My 18F USB firmware is available from the downloads page, and fits into our PIC development environment.
I've never done a MIDI device, but I sortof vaguely remember there is a USB class standard for that.  If so, then it's really easy since you don't have to write a host driver and it will work with any OS that implements that USB class.  All you have to do is look at the class definition, fill in the right enumeration data in the include file for that purpose, then send/receive data over the appropriate endpoints according to the standard.
Any other microcontroller will require something similar.  Again, short of finding free USB MIDI firmware out there (which you say you can't find), you need to do pretty much what I said above regardless of what flavor microcontroller you use.  USB is USB, so all the USB device peripherals in microcontrollers do pretty much the same thing with only a few details different.

A: If your idea of an "easy USB interface" excludes the 18F PICs, then a 'ready made' USB chip (something like an FT232RL) seems the only solution. Add a microcontroller of your taste and start programming. 1 MHz is peanuts for all modern microcontrollers, and USB provides 5V to run your uC (unless you want a 3V3 chip, in that case add an MCP1702 or the like).


text:
Q: The sql command automatically creates a row number mytable:

name     family
-----------------
a        aa
b        bb
c        cc
d        dd

My desired output by SQL Code(by direction Select):

Row   name     family
-----------------
1     a        aa
2     b        bb
3     c        cc
4     d        dd

A: Use the ROW_NUMBER() function, it is one of the Ranking Functions in SQL Server:
WITH CTE
(
   SELECT
     ROW_NUMBER() OVER(ORDER BY name) AS row,
     name,
     family
   FROM tablename
)
SELECT * FROM CTE;

A: Try this one -
Query:
DECLARE @temp TABLE
(
      name VARCHAR(20)
    , family VARCHAR(50)
)

INSERT INTO @temp (name, family)
VALUES
    ('a', 'aa'),
    ('b', 'bb'),
    ('c', 'cc'),
    ('d', 'dd')

SELECT
      [Row] = ROW_NUMBER() OVER(ORDER BY (SELECT 1))
    , name
    , family
FROM @temp

Output:
Row   name    family
----- ------- -------
1     a       aa
2     b       bb
3     c       cc
4     d       dd


text:
Q: opinion poll, t test or paired test or others Which test should I use to test the difference of monthly opinion poll?
If I want to know whether the poll result of April is significantly different from March, should I use independent t test or paired test?
If I use independent t test, it seems that I am comparing two groups of people instead of change over time, however the samples be totally different between two time points.  So, I am not sure which to use.
Thx!!

A: A paired test is appropriate when you measured something in the same person/animal/unit before and after an intervention. In your scenario, you have two distinct samples of people, Accordingly, the paired t test makes no sense and would be impossible to compute.
Why are you focussing on April and May? Do you have results for every month for a longer period of time, and are only focussing on April and May because you noticed they are quite different? If so, you are P-hacking, and the results won't mean much, because you are implicitly testing lots of hypotheses, not just one.


text:
Q: PHP Errors .htaccess limit folder depth When I have a php error it will go through like 5 folders to get to my file. For example:
    home\admin\domain.com\folder\portfolio
What .htaccess attribute do I need to prevent it from showing the first 2 folders(home\admin)?
I don't want end users to see the first 2 folders in my directory since they're not used often anyway. So for the most part I want to hide "home\admin" for security purposes.

A: To answer the question
You have to change your apache configuration and change to directory root of your website because php will always report the full path ( except if you can set a chroot/jail environment )
Additional explanations about the question : http://discussion.dreamhost.com/thread-45191.html
But it is better to hide the errors from being displayed as it show some vital information about your setup ( not just the /home/admin ) part.
To hide the errors, you can set display_errors to off.
See  http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors

A: TL;DR
Set display_errors = Off in your php.ini, and learn to check your logs.
Longer version:
In your development environment, set error_reporting = -1. This will display all errors. In your production environment, set error_reporting to some slightly milder level and never splash them to the screen.
Learn to check your logs, both Apache, and if configured to log separately, your PHP logs.


text:
Q: Cambiar elemento de un Array Hola tengo el siguiente Array, como puedo modificar el dato "id" del primer elemento del array, he logrado obtenerlo con exito con nombre.get(0).Url esto me imprime "video1.mp4", exactamente lo que le indico, el problema es a la hora de cambiar el dato, he visto algunos tutoriales que lo hacen con `Set, pero en este caso no funciona. COMO HARIA PARA CAMBIAR EL DATO "URL", DEL PRIMER ELEMENTO
[
  {
    "Id" : 1,
    "Url" : "video1.mp4",
    "storyThumbUrl" : "imagen1.jpg",
  },
  {
    "Id" : 2,
    "storyUrl" : "video2.mp4",
    "img" : "imagen2.jpg"
  },
  {
    "Id" : 3,
    "storyUrl" : "video3.mp4",
    "img" : "imagen3.jpg"
  }
]

A: Simplemente tienes que asignar el valor tal que así
lista[0].Url = "nuevo valor"
Pero tienes que asegurarte de estar utilizando una lista de tipo mutable.
Espero ayudarte


text:
Q: Remote desktop in 22.04 from Win 10: Authentication error I mean to connect Remote Desktop from Win 10 to a fresh install of Ubuntu 22.04.
I can ssh.
If I am not logged into the console, I get the error

Remote Desktop can't connect to the remote computer for one of these
reasons:  1) Remote access to the server is not enabled  2) The
remote computer is turned off  3) The remote computer is not available
on the network    Ensure the remote computer is turned on and
connected to the network, and that remote access is enabled.

If I am not logged into the console, I get the error (my translation from the Spanish message)

Authentication error   There are more data available   Remote
computer: <IP of remote>

How can I solve this?

A: remote setup commands

*

*sudo apt install xrdp

*sudo systemctl status xrdp

*sudo systemctl start xrdp

*sudo systemctl enable xrdp

*sudo ufw allow from any to any port 3389 proto tcp

*ip a => [192.168.x.x from your local network]

*RDP from Win10 [ make sure log off from Ubuntu or use another use name]
It should work..


text:
Q: Twitter User Time Line Feed using date parameter I am working on sentiment analysis for which I need twitter feed. I have implemented the php code to get the json feed and parse it as I wanted. the problem is I could not find a way to get json feed as per the date specified.
$query = array(
    'screen_name' => 'twitterapi',
    'count' => '5'
);

Using the above syntax I have to specify the number of tweets but my requirement is to get the feed for specific date. Is it possible to pass date parameter instead of count.
currently I am using $path = '/1.1/statuses/user_timeline.json';
I have also implemented the mechanism to manually filter the date but for that I have to provide very large count for older dates that unnecessarily slows down the code.

A: There are two ways you can do this.
Firstly, read the documentation for the API call you're making.  You can't pass a date - but you can request up to 200 Tweets and, if that isn't enough, page through up to 3,200 of their most recent tweets.
Secondly, read the documentation for Searching Twitter, you can use the until parameter to search for older Tweets.  Twitter's search API only goes back ~7 days.  As they say:

Please note that Twitter's search service and, by extension, the Search API is not meant to be an exhaustive source of Tweets. Not all Tweets will be indexed or made available via the search interface.


text:
Q: APIC Cannot GET /apim while updating schema am new to stackoverflow, and I thought of sharing this regarding an IBM product called APIC.
I did the whole deployment correctly as recommended by IBM on an Ubuntu Environment with mongoDB and MySQL using an AZURE Virtual Machine as Server. Whenever I try to update the schema of the database with the new models, I get an error saying:
Cannot GET /apim/dataSources/partials/dataSourceMigrate.html
Please help or ask me anything in case you need more info, and tell me if it's an error from Azure or IBM or me.
Thanks

A: This exactly happened to me once, and I contacted IBM for several weeks of give and take, to find out it's a bug on their side, not on the cloud side or your side :)
Check it here: https://stackoverflow.com/a/40016171/4694311
In this case, go back to using strongloop until they get it fixed.
Note that his is a bug on the operating system itself, it works on iOS but that would be useless on cloud.


text:
Q: node.js Nerve framework unicode response code:
var nerve = require("./nerve");
var sitemap = [
    ["/", function(req, res) {
        res.respond("Русский");
    }]
];
nerve.create(sitemap).listen(8100);

show in browser:
CAA:89

How it should be correct?

A: Nerve appears to interpret the strings you pass as binary strings, which results in the output you're seeing. You can use the Buffer class to convert your UTF-8 chars to a binary string manually. You also need to set the charset in your headers:
var sitemap = [
  ["/", function (req, res) {
    res.respond({
      headers: {"Content-Type": "text/html; charset=utf-8"},
      content: new Buffer("Русский", "utf8").toString("binary")
    });
  }]
];

If you want to try another framework, Express does a better job handling UTF-8. It interprets strings as UTF-8 and sets the charset correctly by default:
var app = require("express").createServer();

app.get("/", function (req, res) {
  res.send("Русский");
});

app.listen(8100);


text:
Q: Inserting Multiple paragraphs with minimal code I have documents that are generated with OpenXML.  I am working on reducing the amount of code required to generate the document.
I have a document section that has 7 paragraphs in it.  Currently I insert them with:
var paragraph = new Paragraph {};
body.Append(paragraph);`

So my question is, is there a better way to insert multiple paragraphs without inserting the above code 7 times?

A: You don't need to copy the code 7 times. You can do this instead:
foreach (var i in Enumerable.Range(0, 7))
    body.Append(new Paragraph());

Or if you are worried about performance, just use a for loop:
for (var i = 0; i < 7; i++)
    body.Append(new Paragraph());

Also see this other Stack Overflow answer:
Is there a shorter/simpler version of the for loop to anything x times?


text:
Q: "It will be the first time (that) I have flown to America." Is the "that"-clause a relative clause?
It will be the first time (that) I have flown to America.

The above example sentence is borrowed from this earlier post.
Depending on context, there can be other variations as follows:

It is the first time (that) I have flown to America.
It was the first time (that) I had flown to America.

The parentheses are there to indicate that that is optional.
What exactly is this that-clause? Is it an ordinary relative clause?
If it is, why is it not allowed to use "when" instead of "that"?

It will be the first time when I have flown to America. (?)

Ngram: is the first time that vs. is the first time when
Edit: I'm leaning toward the relative clause.
The only thing that bothers me is that a relative clause generally allows "when" instead of "that" insofar as the antecedent is some kind of "time". Are there some other relative clauses that don't quite allow "when" for a "time" antecedent?

A: Yes, it is a relative clause.

*

*it begins with 'that'

*it contains a subject and object (is a complete sentence without the relative pronoun)

Don't be distracted by the possible variations, the variation with 'that' is usually the most telling intro to a relative clause. 'When' works grammatically and you might think it is the better choice, but it just isn't used that much by native speakers (and sounds  a little weird).

A: It's the first time that I fly to America.
What part of sentence is the that-clause? I wouldn't say it is a relative clause.
"It" is the percursory or empty subject, and the that-clause is the main subject.
Though it is not very stylistic it would be possible to place the that-clause in subject position:
That I fly to America is the first time.
Supplement
Relative clause or not. It seems there are different views. And all the time  I'm thinking about how to show that we have no relative clause.
One characteristic of relative clauses is that you can change them in a second sentence:
1 Once there was a king who had three daughters - Once there was a king and this king/he had three daughters.
2 Once there was a king whose daughter was ill - Once there was a king and this king's daughter/his daughter was ill.
3 Once there was a king whom God had given no children - Once there was a king and God had given this king/him no children.
Now try to change "It is the first time that I fly to America" according to the three examples above to show that it is a relative clause.


text:
Q: return a line of text if match found I am having some trouble working out how to return a line of text if a match is found.
(set 'wireshark "http://anonsvn.wireshark.org/wireshark/trunk/manuf")

(set 'arptable (map (fn (x) (parse x " ")) (exec "arp -a")))

(define (cleanIPaddress x)
  (slice x 1 -1))

(define (cleanMACaddress x)
  (upper-case (join (slice (parse x ":") 0 3) ":")))

(define (addIPandMACaddress x)
  (list (cleanIPaddress (nth 1 x)) (cleanMACaddress (nth 3 x))))

(set 'arplist (map addIPandMACaddress arptable))

(set 'routerMAC (last (assoc (exec "ipconfig getoption en1 router") arplist)))

(find-all routerMAC (get-url wireshark))

returns
("20:AA:4B")
so I know that the code "works"
but I would like to retrieve the full line of text
"20:AA:4B  Cisco-Li               # Cisco-Linksys, LLC"

A: This can be performed simply by using a string-split procedure that allows us to use remove-if (the Common Lisp version of filter) to search through a string split by newlines removing any lines that do not contain the string we are searching for. That would result in a list of every line containing the string. The functions we will define here are already available via various Common Lisp libraries, but for the education purposes, we will define them all ourselves. The code you need works like so:
; First we need a function to split a string by character

(defun string-split (split-string string)
  (loop with l = (length split-string)
        for n = 0 then (+ pos l)
        for pos = (search split-string string :start2 n)
        if pos collect (subseq string n pos)
        else collect (subseq string n)
        while pos))

; Now we will make a function based on string-split to split by newlines

(defun newline-split (string)
  (string-split "
" string))

; Finally, we go through our text searching for lines that match our string.
; Make sure to replace 'needle' with the string you wish to search for.

(remove-if #'(lambda (x)
               (equal 'nil (search (string-upcase "needle")
                                   (string-upcase x))))
           (newline-split haystack))

You should be able to apply this strategy to the code you posted with a few small modifications. This code was tested on SBCL 1.0.55.0-abb03f9, an implementation of ANSI Common Lisp, on Mac OS X 10.7.5.

A: In the end I used:
(find-all (string routerMAC ".*") (get-url wireshark))


text:
Q: Exact Sequences of Modules and Rank Suppose that:
$0 \rightarrow M_{1} \rightarrow M \rightarrow M_{2} \rightarrow 0$
Is an exact sequence of $R$-modules (for $R$ commutative integral domain). Show that $\mathrm{rk}(M) = \mathrm{rk}(M_{1})+\mathrm{rk}(M_{2})$

I have shown the inequality $\mathrm{rk}(M) \geq \mathrm{rk}(M_{1})+\mathrm{rk}(M_{2})$, however for the opposite direction I'm lost. I tried to take $N$ as a linear independent subset and tried to decompose it into $N_{1}$ (the elements in $\mathrm{Ker}(g)$) and $N_{2}$ (the elements not in $\mathrm{Ker}(g)$), but I haven't got far, since $N_{1}$ gives us a linearly independent set in $M_{1}$, however $N_{2}$ can give us a linearly dependent set in $M_{2}$.
We define $\mathrm{rk}(M)$ in this case as the supremum over all cardinalities of the linearly independent subsets of $M$ (where the only finite linear combination equaling $0$ implies trivial coefficients for $r \in R$).
Would this be the proper way to show the result? I think I'm missing something important.

A: I am aware of the fact, that passing to the quotient field by localization or tensoring gives us an easy proof, but the OP asked for something more elementary.
First of all some notations: Denote the map $M \to M_2$ by $f$ and identify $M_1$ as the kernel of $f$, i.e. view $M_1$ as a subset of $M$.
Here is an elementary proof for the inequality
$$\operatorname{rk} M \leq \operatorname{rk} M_1 + \operatorname{rk} M_2.$$
Take $R$-linear independent subset $N \subset M$. Let $X \subset N$ be maximal with respect to the property that $f(X)$ is linear independent in $M_2$.
Now let $m \in N \setminus X$. The set $f(\{m\} \cup X)$ is linear dependent, hence we have some $r_m, \lambda_{m,x} \in R$ such that
$$0=r_mf(m) + \sum_{x \in X} \lambda_{m,x}f(x) = f\left(r_mm+\sum_{x \in X} \lambda_{m,x}x \right),$$
hence $r_mm+\sum_{x \in X} \lambda_{m,x}x \in M_1$.
Note that we have $r_m \neq 0$, since $f(X)$ is linear independent.
Let us proof that the elements $(r_mm+\sum_{x \in X} \lambda_{m,x}x)_{m \in N \setminus X}$ are linear indepedendent:
Let $\mu_m \in R$ such that
$$\sum_{m \in N \setminus X } \mu_m(r_mm+\sum_{x \in X} \lambda_{m,x}x) = 0$$
We rearrange this sum and get:
$$0=\sum_{m \in N \setminus X} \mu_mr_mm + \sum_{x \in X} \sum_{m \in N \setminus X} \mu_m\lambda_{m,x}x$$
The linear independence of $N$ yields (in particular) $\mu_mr_m=0$, hence $\mu_m=0$, since $r_m \neq 0$ and $R$ is an integral domain. This shows that the elements are indeed linear independent.
All in all we have shown:
We can split $N$ into a disjoint union $N = (N \setminus X) \cup X$, such that the elements of $N \setminus X$ are linear indepedenent in $M_1$ and the elements of $X$ are linear independent after passing to $M_2$. Thus we are done.

To the other inequality
$$\operatorname{rk} M \geq \operatorname{rk} M_1 + \operatorname{rk} M_2.$$
You have already shown this, so I only give a sketch:
Take a linear indepedent set $N_1 \subset M_1$ and another $N_2 \subset M_2$. View $N_1$ as set in $M$ in take arbitrary inverse images of the elements in $N_2$ to form a set $f^*(N_2)$ (which is in bijection with $N_2$). Then $N_1 \cup f^*(N_2)$ is a linear independent family in $M$, which proves the inequality. Note that this works over any commutative ring with unity, we can allow zero-divisors for this. (But we need the integral domain property for the other inequality as seen above)


text:
Q: Should I switch to MTL4 from Eigen if I also need to make use of ODEs? I'm looking for C++ matrix libraries to work with on a Linux (Fedora) system. The intention is to implement continuous attractor neural networks and such for computational neuroscience. I've already begun using Eigen. However, I realized I need differential equation solvers too for my task and ran into Odeint (which recently seems to have been accepted into boost). Odeint works with MTL4 as this page details. I'm now wondering if I should rewrite my code using MTL4 instead of Eigen to be able to make use of odeint properly.
I've looked on both google and stackoverflow itself but failed to find a comparison

A: I am pretty sure that Eigen will also work with odeint. So it is up to you if you want to change to MTL.
The documentation of odeint http://headmyshoulder.github.com/odeint-v2/doc/boost_numeric_odeint/odeint_in_detail/state_types__algebras_and_operations.html shows how to adapt an arbitrary type to odeint. I think Eigen supports expression templates (so you can write vector or matrix expression like M1=a*M2+b*M3;) such that you can use odeint with the vector_space_algebra and the default_operations. All you have to do is to adapt the resizing mechanism of odeint. Have a look at the MTL bindings in odeint to see how this works. It is straightforward.


text:
Q: Java System statements outside code block I am in an understanding any statement in java should be in code block.
  But I see in below code that System.getenv(); is not place in code block. But if I put a System.out.println() below it compiler complains. Is System.getenv() here treated as declaration rather than a statement?
package gov.ssa.epa;

public class AdvJ {

    private static final Map<String, String> INVALID_FILTER_KEY = System.getenv();

    System.out.println("hello");

    public static void main(String[] args)  {

    }

A: System.getenv() is not a statement, it is an initialization expression used as part of a field declaration. Field declarations are allowed in the context outside of any method - in fact, that's the only place where fields declarations can go. Initialization expressions are attached to the declarations, so, naturally, they are allowed as well.
System.out.println, on the other hand, is not a declaration, so it is not allowed outside of a function or an initialization block.

A: This is because private static final Map INVALID_FILTER_KEY = System.getenv() is a private class instance variable. These instance variables can be used anywhere in the class and are thus declared outside of any method. A variable declared inside a method can only be used in that method. The reason it is having problems when you call System.out.println is because this is actual executable code and for actual code to run, it needs to be inside a method. Consider checking out this tutorial on how it works in java classes https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html


text:
Q: Is there any way to show records that are preventing a delete due to referencial integrity? i have a generic problem all over my application and want to see if there is a common generic way of solving it.
The main issue is how to let users know which records are linked when you try to delete a record from a joined table.
for example, let's say i have two database tables.

*

*Customer

*Branch

where Customer has a branchId field.
if i go delete a record from the branch table, it will fail if there are customers that have that branchId in its foreign key.
if i try to delete this through code, i get an error saying that it can't delete because of a referencial integrity constraint but it doesn't let me know what the actual linked tables is or which particular records are causing the link.
Is there any generic C# code that handles this situation that would either:

*

*Give a better error message back and show you the records that are links

*Even better, lets you change the linked records at that time to a default reference or a null reference (in cases where the foreign key is nullable)

A: You might consider creating a trigger on the Branch table that sets any Customer records referencing the Branch record that is going to be deleted to BranchId = null.
This should allow you to delete Branches and remove any associations from existing customers.
Here is an article that goes over something similar.
Be warned that you will probably have some confused customers if you start changing their data without them knowing it...


text:
Q: Extract value from repeated xml tags in unix I have sample xml below, I would like to extract values from the tags for example value=3. Since there are repeated tags I am finding challenge to do this in unix.
<Request>
<Destination>
    <Parameters>
        <Parameter>
            <key>a</key>
            <value>1</value>
        </Parameter>
        <Parameter>
            <key>b</key>
            <value>2</value>
        </Parameter>
        <Parameter>
            <key>c</key>
            <value>3</value>
        </Parameter>
    </Parameters>
    <Proxy>
        <Destination>
            <Parameters>
                <Parameter>
                    <key>a</key>
                    <value>1</value>
                </Parameter>
                <Parameter>
                    <key>b</key>
                    <value>2</value>
                </Parameter>
                <Parameter>
                    <key>c</key>
                    <value>3</value>
                </Parameter>
            </Parameters>
        </Destination>
    </Proxy>
</Destination>

A: Generally it is more compact to use  XQuery/XPath 3 (e.g. in my implementation) than XSLT.  Depending what you mean by "extract values", you can do  one of these:
xidel req.xml  --extract '//value'

to get all values
1
2
3
1
2
3

or with a prefix:
xidel req.xml  -e '//value/("value="||.)'

to get
value=1
value=2
value=3
value=1
value=2
value=3

To get all keys with a certain value:
xidel req.xml  -e '//*[value="3"]/key'

c
c

Or all values with a certain key:
xidel req.xml  -e '//*[key="b"]/value'

2
2

A: You can try using a command line XSLT processor like 'xsltproc' or 'xalan' and parse your .xml file using a .xsl stylesheet. Here's a stylesheet which refers to your sample xml data.
I am assuming there is an end tag corresponding to 'Request' at the end of your file.
<xsl:stylesheet xmlns:xsl = "http://www.w3.org/1999/XSL/Transform" version = "1.0">
  <xsl:output method = "text"/>
  <xsl:template match = "Request">
    <xsl:for-each select = "Destination/Parameters/Parameter">
        <xsl:text>value=<xsl:value-of select = "@value"/>
        </xsl:text>
    </xsl:for-each>
    <xsl:template match = "Proxy">
        <xsl:for-each select = "Destination/Parameters/Parameter">
            <xsl:text>value=<xsl:value-of select = "@value"/>
            </xsl:text>
        </xsl:for-each>
    </xsl:template>
  </xsl:template>
</xsl:stylesheet>

A: In perl:
#!/usr/bin/env perl

use strict;
use warnings;
use XML::Twig;

my $twig = XML::Twig -> new -> parsefile ( 'your_xml_file' );

print $_ -> text,"\n" for $twig -> findnodes('//value');

Which reduces to a one liner:
perl -MXML::Twig -e 'print $_ -> text,"\n" for XML::Twig -> parse ( do { local $/;<> }  )-> findnodes('//value')' your_file.xml

If you want to get a bit more complicated with it, you can use xpath expressions to find particular things:
#!/usr/bin/env perl

use strict;
use warnings;
use XML::Twig;

my $twig = XML::Twig -> new -> parsefile ( 'your_file.xml' );

foreach my $node ( $twig -> findnodes('//value[string()="3"]/../') ) {
   print $node -> first_child_text('key'),"\n";
}


text:
Q: jQuery DataTable Selecting Row in Paged Table I have a datatable which displays data from an object array. I need to select a row in the table based on some user input on another element on the page.
I have been able to get this to work with the DataTable in non-paged mode with the following function:
function (scrollTo) {
  var container = $('.dataTables_scrollBody');
  container.scrollTop(
    scrollTo.offset().top - container.offset().top + container.scrollTop()
  );
}

Now I need to put the DataTable in paged mode and select a row and the above method does not work.
I get the following error: "Unable to get property 'top' of undefined or null reference"
Any pointers will be appreciated.


text:
Q: Dynamic content loading on clicking menu items using Jquery? html code:

    <meta charset="utf-8">

    <title>Article Thumbnails - Bootsnipp.com</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">

Area Chart

Line Chart

Scatter chart

In the above code i have menu items on left side as you can see and whenever i clicked on any menu item.i want to load its particular div content on right side using bootstrap jQuery.i tried but its not working.any help would be appreciated?


text:
Q: how can I make snapchat ads charge you when user click a specific button I need to make a snapchat ads with conversion that charge you when user click a specific button
like cost if user click on call button or whatsapp one ?
I have tried Page_view option .. but no good resutl


text:
Q: Angular interceptor not sending request Header So I have this interceptor:
@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log(`interceptor called from! ${req.url}`);
        const headers = new HttpHeaders({
            'x-app': getPackage().name,
            'x-app-version': getPackage().version,
        });

        const cloneReq = req.clone({ headers });

        req.clone({ headers: req.headers });

        if (req.method !== 'GET' && !req.headers.has('Content-Type')) {
            // Clone the request to add the new header
            const clonedRequest: HttpRequest<any> =
            req.clone({ headers: req.headers.append('Content-Type', 'application/json') });

            // Pass the cloned request instead of the original request to the next handle
            return next.handle(clonedRequest);
        }
        return next.handle(cloneReq);
    }
}

But the x-app and x-app-version headers gets called only when it is a GET request.
I tried adjusting the code in the if block to this:
if (req.method !== 'GET' && !req.headers.has('Content-Type')) {
            // Clone the request to add the new header
            // const clonedRequest: HttpRequest<any> =
            const clonedRequest = req.clone({
                headers: new HttpHeaders({
                    'Content-Type': 'application/json',
                    'x-app': getPackage().name,
                    'x-app-version': getPackage().version,
                }),
            });

            // Pass the cloned request instead of the original request to the next handle
            return next.handle(clonedRequest);
        }

But my POST requests are throwing 403 errors. Please how do I fix this?


text:
Q: Where are ServiceWorker data stored? I'm playing with ServiceWorker api for quite a while, but cannot figure out, where are the cached files stored on my hard drive and if they're accessible from outside of browser context. Any tips highly appreciated!
Cheers,
Wojtek

A: For Firefox, in the storage subdirectory of your Firefox profile.
E.g. ~/.mozilla/firefox/z4o9asac.default/storage/default/http+++localhost+3003/cache

A: The only thing I found is a directory
~/.config/google-chrome/Profile 1/Service Worker (on Ubuntu), but it seems to be just SW implementation there.


text:
Q: If $A$ is a domain but not a field, then $(x)$ is not a maximal ideal of $A[x]$? The question arised when considering the equivalence: $A$ is a field if and only if $A[x]$ is a PID. Now, I know the only if part. The if part should go like this:

For any $a\in A\setminus\{0\}$, let $(a,x)=(p(x))$. Because $a\in (p(x))$ we have $p(x)=b\in A $, besides $x\in (b)$ implies $b\in A^*$ and thus $(a,x)=(b)=A[x]$. In particular $1\in (a,x) $, hence $a\in A^*$. Therefore $A $ is a field.

Is it correct?
But here's the main point of my question. My book mentions a contrapositive approach: if $A$ is a domain but not a field then $A[x]$ is a domain but not a PID, because $x$ is irreducible but $(x)$ is not maximal. How to show this?

A: The element $x$ is obviously irreducible in any ring $A[x]$, where $A$ is a domain, because proper factors would have degree $0$.
The ideal $(x)$ has the property that
$$
A[x]/(x)\cong A
$$
so $(x)$ is maximal if and only if $A$ is a field.
In a PID, an irreducible element generates a maximal ideal.


text:
Q: Move column values to values with True/False I have a dataset similar to this one:
 data = {'lat': [0.15, 0.15, 0.15, 0.15, 0.25, 0.25, 0.48, 0.48, 0.48, 0.48],
        'lon': [0.87, 0.87, 0.87, 0.87, 0.12, 0.12, 0.59, 0.59, 0.59, 0.59],
        'animal': ['dog', 'cat', 'rat', 'rat', 'cat', 'rat', 'cat', 'dog', 'dog', 'rat'],
        'category': ['A', 'C', 'B', 'C', 'B', 'B', 'C', 'A', 'C', 'C']}
mdf = pd.DataFrame(data)

mdf
Out[460]:
    lat   lon animal category
0  0.15  0.87    dog        A
1  0.15  0.87    cat        C
2  0.15  0.87    rat        B
3  0.15  0.87    rat        C
4  0.25  0.12    cat        B
5  0.25  0.12    rat        B
6  0.48  0.59    cat        C
7  0.48  0.59    dog        A
8  0.48  0.59    dog        C
9  0.48  0.59    rat        C

I want to use 'animal', 'lat' and 'lon' as some kind of indexes to obtain something like this:
      lat   lon animal     A      B      C
0    0.15  0.87    dog True   False  False
1    0.15  0.87    cat False  False  True
2    0.15  0.87    rat False  True   True
4    0.25  0.12    cat False  True   False
5    0.25  0.12    rat False  True   False
6    0.48  0.59    cat False  False  True
7    0.48  0.59    dog True   False  True
9    0.48  0.59    rat False  False  True

I don't really care wether it is True/False, 1/0, etc. as long as I can see which categories each combination of 'lat', 'long' and 'animal' has.
I've been trying without success several alternatives: pivot, pivot_table, groupby, stack/unstack... but none seems to answer my needs.
The only option I have left is to iterate through the different 'lat', 'lon', 'animal' alternatives and check wether there is an occurence for each of the 'category'.
Maybe this could be done somehow by defining 'lat', 'lon', 'animal' as indexes and "unmelting" somehow
Any suggestions?
Thanks.

EDIT: I am unable to have new lines in comments, and I don't know how to contact the person that closed the post, so let me bring some additional explanation here. Apologies for the annoyance.
Quang, thanks for your reference to a different thread. However, I am not sure it helps me.
I could do this:
pd.get_dummies(mdf['category'], prefix='', prefix_sep='')

But I get my initial 10 lines instead of the table I was aiming at.
To obtain something useful with get_dummies, I would have to do this:
mdf = mdf.join(pd.get_dummies(mdf['category'], prefix='', prefix_sep=''))
mdf[['A', 'B', 'C']] = mdf.groupby(['lat', 'lon', 'animal'])[['A', 'B', 'C']].transform('sum')
mdf.drop_duplicates(subset=['lat', 'lon', 'animal'], inplace=True)
d = {1: True,
     0: False}
mdf[['A', 'B', 'C']] = mdf[['A', 'B', 'C']].replace(d)
mdf.drop('category',
        axis=1,
        inplace=True)

But this seems overcomplicated and I feel there must have a better way...
I also thought about this:
mdf['value'] = [True] * 10
mdf = mdf.set_index(['lat', 'lon', 'animal', 'category'])
mdf = mdf.unstack(fill_value=False)
mdf = mdf.reset_index()
mdf.columns = ['lat', 'lon', 'animal', 'A', 'B', 'C']

But again, it seems so un-pythonic to trick the system by playing with indexes...
There must surely be a better way!
Thanks.

A: I the original index values do not matter, you could use get_dummies to concat the A, B and C columns to the original dataframe, then group by lat lon and animal and sum the boolean columns:
categs = np.sort(mdf['category'].unique())

resul = pd.concat([mdf, pd.get_dummies(mdf['category']).astype(bool)], axis=1
                  ).groupby(['lat', 'lon', 'animal'])[categs].sum().reset_index()

it gives:
    lat   lon animal      A      B      C
0  0.15  0.87    cat  False  False   True
1  0.15  0.87    dog   True  False  False
2  0.15  0.87    rat  False   True   True
3  0.25  0.12    cat  False   True  False
4  0.25  0.12    rat  False   True  False
5  0.48  0.59    cat  False  False   True
6  0.48  0.59    dog   True  False   True
7  0.48  0.59    rat  False  False   True


text:
Q: How to draw arrows on a line-chart with Highcharts? I'm trying to add an arrow to the end of my Highcharts line-chart. I've already looked through similar questions but the solutions don't seem to work:
The result i'm looking for (added in colors),

A: You should wrap the drawGraph method and add the code for arrow. It can be realised by path method.
(function(H) {
        H.wrap(H.Series.prototype, 'drawGraph', function(proceed) {

          // Now apply the original function with the original arguments,
          // which are sliced off this function's arguments
          proceed.apply(this, Array.prototype.slice.call(arguments, 1));

          var arrowLength = 15,
            arrowWidth = 9,
            series = this,
            data = series.data,
            len = data.length,
            segments = data,
            lastSeg = segments[segments.length - 1],
            path = [];

          var lastPoint = null;
          var nextLastPoint = null;

          if (lastSeg.y == 0) {
            lastPoint = segments[segments.length - 2];
            nextLastPoint = segments[segments.length - 1];
          } else {
            lastPoint = segments[segments.length - 1];
            nextLastPoint = segments[segments.length - 2];
          }

          var angle = Math.atan((lastPoint.plotX - nextLastPoint.plotX) /
            (lastPoint.plotY - nextLastPoint.plotY));

          if (angle < 0) angle = Math.PI + angle;

          path.push('M', lastPoint.plotX, lastPoint.plotY);

          if (lastPoint.plotX > nextLastPoint.plotX) {
            path.push(
              'L',
              lastPoint.plotX + arrowWidth * Math.cos(angle),
              lastPoint.plotY - arrowWidth * Math.sin(angle)
            );
            path.push(
              lastPoint.plotX + arrowLength * Math.sin(angle),
              lastPoint.plotY + arrowLength * Math.cos(angle)
            );
            path.push(
              lastPoint.plotX - arrowWidth * Math.cos(angle),
              lastPoint.plotY + arrowWidth * Math.sin(angle),
              'Z'
            );
          } else {
            path.push(
              'L',
              lastPoint.plotX - arrowWidth * Math.cos(angle),
              lastPoint.plotY + arrowWidth * Math.sin(angle)
            );
            path.push(
              lastPoint.plotX - arrowLength * Math.sin(angle),
              lastPoint.plotY - arrowLength * Math.cos(angle)
            );
            path.push(
              lastPoint.plotX + arrowWidth * Math.cos(angle),
              lastPoint.plotY - arrowWidth * Math.sin(angle),
              'Z'
            );
          }

          series.chart.renderer.path(path)
            .attr({
              fill: series.color
            })
            .add(series.group);

        });
      }(Highcharts));

Example:

*

*http://jsfiddle.net/vyfsf1ft/

A: (UPDATE)
The previous solution is not quite responsive because it redraws the arrow on the chart every single time when the browser is resized.

*

*Old Example: http://jsfiddle.net/vyfsf1ft/
However I found out how to make the chart with the arrow fully responsive:
(function(H) {

    var arrowCheck = false,
        pathTag;

    H.wrap(H.Series.prototype, 'drawGraph', function(proceed) {

    // Now apply the original function with the original arguments,
    // which are sliced off this function's arguments

    proceed.apply(this, Array.prototype.slice.call(arguments, 1));

    var arrowLength = 15,
        arrowWidth = 9,
        series = this,
        data = series.data,
        len = data.length,
        segments = data,
        lastSeg = segments[segments.length - 1],
        path = [],
        lastPoint = null,
        nextLastPoint = null;

    if (lastSeg.y == 0) {
       lastPoint = segments[segments.length - 2];
       nextLastPoint = segments[segments.length - 1];
    } else {
       lastPoint = segments[segments.length - 1];
       nextLastPoint = segments[segments.length - 2];
    }

    var angle = Math.atan((lastPoint.plotX - nextLastPoint.plotX) /
        (lastPoint.plotY - nextLastPoint.plotY));

    if (angle < 0) angle = Math.PI + angle;

    path.push('M', lastPoint.plotX, lastPoint.plotY);

    if (lastPoint.plotX > nextLastPoint.plotX) {

       if (arrowCheck === true) {

         pathTag = document.getElementById("arrow");
         if (pathTag != null) {
           pathTag.remove(pathTag);
       }
     }

     path.push(
        'L',
        lastPoint.plotX + arrowWidth * Math.cos(angle),
        lastPoint.plotY - arrowWidth * Math.sin(angle)
     );
     path.push(
        lastPoint.plotX + arrowLength * Math.sin(angle),
        lastPoint.plotY + arrowLength * Math.cos(angle)
     );
     path.push(
        lastPoint.plotX - arrowWidth * Math.cos(angle),
        lastPoint.plotY + arrowWidth * Math.sin(angle),
        'Z'
     );
    } else {

       if (arrowCheck === true) {

          pathTag = document.getElementById("arrow");
          if (pathTag != null) {
             pathTag.remove(pathTag);
          }
       }

       path.push(
         'L',
         lastPoint.plotX - arrowWidth * Math.cos(angle),
         lastPoint.plotY + arrowWidth * Math.sin(angle)
       );
       path.push(
         lastPoint.plotX - arrowLength * Math.sin(angle),
         lastPoint.plotY - arrowLength * Math.cos(angle)
       );
       path.push(
         lastPoint.plotX + arrowWidth * Math.cos(angle),
         lastPoint.plotY - arrowWidth * Math.sin(angle),
         'Z'
       );

    }

    series.chart.renderer.path(path)
    .attr({
       fill: series.color,
       id: 'arrow'
    })
    .add(series.group);

    arrowCheck = true;

   });
}(Highcharts));

*

*Working example: http://jsfiddle.net/vyfsf1ft/3/
Hope this helps. Cheers!

A: Great help for me!
One note, the code above only works if there is only one series on the graph.  I made a few changes that lets it work with more than one series.  The issue was that since each arrow had the same ID, it would wipe out the prior arrows for other series, thinking they were old arrows that needed to be redrawn.  All I did was change the id to be a combo of 'arrow' and the series name, so it only wipes out the prior arrows for the specific series.
(function(H) {

    var arrowCheck = false,
        pathTag;

    H.wrap(H.Series.prototype, 'drawGraph', function(proceed) {

      // Now apply the original function with the original arguments,
      // which are sliced off this function's arguments
      proceed.apply(this, Array.prototype.slice.call(arguments, 1));

      // used a bit of regex to clean up the series name enough to be used as an id
      var arrowName = "arrow"+this.name.replace(/\W/g,"_").toLowerCase();
      // console.log("----------->arrowName:"+arrowName)

      var arrowLength = 15,
        arrowWidth = 7,
        series = this,
        data = series.data,
        len = data.length,
        segments = data,
        lastSeg = segments[segments.length - 1],
        path = [],
        lastPoint = null,
        nextLastPoint = null;

      if (lastSeg.y == 0) {
        lastPoint = segments[segments.length - 2];
        nextLastPoint = segments[segments.length - 1];
      } else {
        lastPoint = segments[segments.length - 1];
        nextLastPoint = segments[segments.length - 2];
      }

      var angle = Math.atan((lastPoint.plotX - nextLastPoint.plotX) /
        (lastPoint.plotY - nextLastPoint.plotY));

      if (angle < 0) angle = Math.PI + angle;

      path.push('M', lastPoint.plotX, lastPoint.plotY);

      if (lastPoint.plotX > nextLastPoint.plotX) {

        if (arrowCheck === true) {
          //replaced 'arrow' with arrowName
          pathTag = document.getElementById(arrowName);
          if (pathTag != null) {
            pathTag.remove(pathTag);
          }
        }

        path.push(
          'L',
          lastPoint.plotX + arrowWidth * Math.cos(angle),
          lastPoint.plotY - arrowWidth * Math.sin(angle)
        );
        path.push(
          lastPoint.plotX + arrowLength * Math.sin(angle),
          lastPoint.plotY + arrowLength * Math.cos(angle)
        );
        path.push(
          lastPoint.plotX - arrowWidth * Math.cos(angle),
          lastPoint.plotY + arrowWidth * Math.sin(angle),
          'Z'
        );
      } else {

        if (arrowCheck === true) {
          //replaced 'arrow' with arrowName
          pathTag = document.getElementById(arrowName);
          if (pathTag != null) {
            pathTag.remove(pathTag);
          }
        }

        path.push(
          'L',
          lastPoint.plotX - arrowWidth * Math.cos(angle),
          lastPoint.plotY + arrowWidth * Math.sin(angle)
        );
        path.push(
          lastPoint.plotX - arrowLength * Math.sin(angle),
          lastPoint.plotY - arrowLength * Math.cos(angle)
        );
        path.push(
          lastPoint.plotX + arrowWidth * Math.cos(angle),
          lastPoint.plotY - arrowWidth * Math.sin(angle),
          'Z'
        );
      }

      series.chart.renderer.path(path)
        .attr({
          fill: series.color,
          id: arrowName //changed from 'arrow' to arrowName to enable more than one series with an arrow
        })
        .add(series.group);

       arrowCheck = true;

    });
  }(Highcharts));

A: Linted /cleaned up version of jmfeland's answer with two series
http://jsfiddle.net/vyfsf1ft/18/
$(function() {

  (function(H) {
    var arrowCheck = false
    var pathTag

    H.wrap(H.Series.prototype, 'drawGraph', function(proceed) {
      // Apply the original function with the original arguments,
      // which are sliced off this function's arguments
      var series = this
      proceed.apply(series, Array.prototype.slice.call(arguments, 1))

      var arrowName = 'arrow' + series.name.replace(/\W/g, '_').toLowerCase()
      var arrowLength = 15
      var arrowWidth = 7
      var data = series.data
      var len = data.length
      var lastSeg = data[len - 1]
      var path = []
      var lastPoint = null
      var nextLastPoint = null

      if (lastSeg.y == 0) {
        lastPoint = data[len - 2]
        nextLastPoint = data[len - 1]
      } else {
        lastPoint = data[len - 1]
        nextLastPoint = data[len - 2]
      }

      var angle = Math.atan((lastPoint.plotX - nextLastPoint.plotX) /
        (lastPoint.plotY - nextLastPoint.plotY))

      if (angle < 0) angle = Math.PI + angle

      path.push('M', lastPoint.plotX, lastPoint.plotY)

      if (lastPoint.plotX > nextLastPoint.plotX) {
        if (arrowCheck === true) {
          pathTag = document.getElementById(arrowName)
          if (pathTag != null) {
            pathTag.remove(pathTag)
          }
        }

        path.push(
          'L',
          lastPoint.plotX + arrowWidth * Math.cos(angle),
          lastPoint.plotY - arrowWidth * Math.sin(angle)
        )
        path.push(
          lastPoint.plotX + arrowLength * Math.sin(angle),
          lastPoint.plotY + arrowLength * Math.cos(angle)
        )
        path.push(
          lastPoint.plotX - arrowWidth * Math.cos(angle),
          lastPoint.plotY + arrowWidth * Math.sin(angle),
          'Z'
        )
      } else {
        if (arrowCheck === true) {
          pathTag = document.getElementById(arrowName)
          if (pathTag != null) {
            pathTag.remove(pathTag)
          }
        }

        path.push(
          'L',
          lastPoint.plotX - arrowWidth * Math.cos(angle),
          lastPoint.plotY + arrowWidth * Math.sin(angle)
        )
        path.push(
          lastPoint.plotX - arrowLength * Math.sin(angle),
          lastPoint.plotY - arrowLength * Math.cos(angle)
        )
        path.push(
          lastPoint.plotX + arrowWidth * Math.cos(angle),
          lastPoint.plotY - arrowWidth * Math.sin(angle),
          'Z'
        )
      }

      series.chart.renderer.path(path)
        .attr({
          fill: series.color,
          id: arrowName,
        })
        .add(series.group)

      arrowCheck = true
    })
  }(Highcharts))

  var chart = new Highcharts.Chart({
    chart: {
      renderTo: 'container',
      defaultSeriesType: 'scatter'
    },
    xAxis: {
      min: 0,
      max: 10
    },
    plotOptions: {
      series: {
        animation: {
          duration: 2000
        },
        lineWidth: 2,
        marker: {
          enabled: false
        }
      },
      states: {
        hover: {
          enabled: true,
          lineWidth: 2
        },
      }
    },
    series: [{
      name: 'main',
      id: 'main',
      data: [
        [0, 0],
        [3, 4]
      ]
    }, {
      name: 'secondary',
      id: 'secondary',
      data: [
        [1, 0],
        [5, 8]
      ]
    }]
  })
})

A: (UPDATE) plot graph XY
if (lastPoint.plotX > nextLastPoint.plotX || (lastPoint.plotX==nextLastPoint.plotX && lastPoint.plotY > nextLastPoint.plotY))

Grap Arrow Line XY


text:
Q: JBoss 7, how to add library module to eclipse project build path I wanted to move from jboss AS 6 to 7 with hibernate 4 support and now all libraries are in subfolders with module.xml files.
And I have no idea how to add those to my eclipse project build path.
Where do I define my module dependencies?

A: The easiest way is to do Build Path > Add External Archives and select the jars you want.
Slightly better might be to define a JBOSS_HOME classpath variable, and add the jars as variable entries. That would make things easier if you ever move your JBoss installation.
If you wanted more automation, it would be possible to write a script, for whatever build tool you use, that parses your application's manifest to find which modules it depends on, and add those to your classpath automatically. If you're good at scripting, that should be quite easy.


text:
Q: Gatsby Unable to process image from markdown files I am revamping a blog to Gatsby which is lightning fast, everything seems perfect but I am facing different sort of issue, as the images I have via Netlify CMS aren't appearing properly in the blog, the images are appearing blur. I don't know what is going wrong here.
Here is the example of the problem statement
DEMO
here is the excerpt of my gatsby-config.js.
plugins: [
        `gatsby-plugin-sitemap`,
        `gatsby-plugin-netlify-cms`,
        {
          resolve: 'gatsby-source-filesystem',
          options: {
            path: `${__dirname}/static/home`,
            name: 'home',
          },
        },
        {
          resolve: 'gatsby-source-filesystem',
          options: {
            path: `${__dirname}/static/blogs`,
            name: 'blogs',
          },
        },
        {
          resolve: 'gatsby-source-filesystem',
          options: {
            path: `${__dirname}/static/author`,
            name: 'author',
          },
        },
        {
          resolve: 'gatsby-source-filesystem',
          options: {
            path: `${__dirname}/static/svg`,
            name: 'svg',
          },
        },
        {
            resolve: 'gatsby-source-filesystem',
            options: {
                path: `${__dirname}/content`,
                name: 'pages',
            },
        },
        {
          resolve: 'gatsby-source-filesystem',
          options: {
            path: `${__dirname}/content`,
            name: 'blog',
          },
        },
        {
            resolve: 'gatsby-source-filesystem',
            options: {
                name: 'assets',
                path: `${__dirname}/static`,
            },
        },

package.json
{
  "name": "Bhavikji",
  "private": true,
  "description": "Bhavikji website",
  "version": "2.0.0",
  "author": "Oscar",
  "dependencies": {
    "@mdx-js/mdx": "^1.5.3",
    "@mdx-js/react": "^1.5.3",
    "bootstrap": "^4.4.1",
    "disqus-react": "^1.0.7",
    "gatsby": "^2.18.12",
    "gatsby-image": "^2.2.34",
    "gatsby-paginate": "^1.1.1",
    "gatsby-plugin-catch-links": "^2.1.21",
    "gatsby-plugin-google-analytics": "^2.1.34",
    "gatsby-plugin-manifest": "^2.2.31",
    "gatsby-plugin-netlify": "^2.1.30",
    "gatsby-plugin-netlify-cms": "^4.1.33",
    "gatsby-plugin-offline": "^3.0.30",
    "gatsby-plugin-optimize-svgs": "^1.0.3",
    "gatsby-plugin-prefetch-google-fonts": "^1.4.3",
    "gatsby-plugin-react-helmet": "^3.1.16",
    "gatsby-plugin-react-svg": "^3.0.0",
    "gatsby-plugin-robots-txt": "^1.5.0",
    "gatsby-plugin-sass": "^2.1.26",
    "gatsby-plugin-sharp": "^2.3.5",
    "gatsby-plugin-sitemap": "^2.2.26",
    "gatsby-remark-autolink-headers": "^2.1.22",
    "gatsby-remark-copy-linked-files": "^2.1.35",
    "gatsby-remark-images": "^3.1.39",
    "gatsby-remark-lazy-load": "^1.0.2",
    "gatsby-remark-normalize-paths": "^1.0.0",
    "gatsby-remark-prismjs": "^3.3.29",
    "gatsby-remark-relative-images": "^0.2.3",
    "gatsby-remark-responsive-iframe": "^2.2.31",
    "gatsby-remark-smartypants": "^2.1.19",
    "gatsby-source-filesystem": "^2.1.40",
    "gatsby-transformer-remark": "^2.6.45",
    "gatsby-transformer-sharp": "^2.3.7",
    "intersection-observer": "^0.7.0",
    "lodash": "^4.17.15",
    "moment": "^2.24.0",
    "netlify-cms-app": "^2.10.1",
    "node-sass": "^4.13.0",
    "prismjs": "^1.18.0",
    "prop-types": "^15.7.2",
    "react": "^16.12.0",
    "react-clamp-lines": "^3.0.2",
    "react-dom": "^16.12.0",
    "react-helmet": "^5.2.1",
    "save": "^2.4.0",
    "sharethis-reactjs": "^1.5.0",
    "styled-components": "^5.0.0"
  },
  "devDependencies": {
    "@babel/core": "7.7.7",
    "@babel/plugin-proposal-class-properties": "7.7.4",
    "@babel/plugin-proposal-optional-chaining": "7.7.5",
    "@babel/plugin-transform-flow-strip-types": "^7.7.4",
    "@babel/preset-env": "7.7.7",
    "@babel/preset-react": "7.7.4",
    "autoprefixer": "9.7.3",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "10.0.3",
    "babel-jest": "24.9.0",
    "babel-preset-gatsby": "0.2.26",
    "browserslist": "4.8.2",
    "concurrently": "5.0.2",
    "eslint": "6.8.0",
    "eslint-config-airbnb-base": "14.0.0",
    "eslint-plugin-import": "2.19.1",
    "eslint-plugin-jest": "23.2.0",
    "eslint-plugin-jsx-a11y": "6.2.3",
    "eslint-plugin-react": "7.17.0",
    "eslint-watch": "6.0.1",
    "prettier": "^1.19.1",
    "rimraf": "3.0.0",
    "stylelint": "12.0.1",
    "stylelint-config-recommended-scss": "4.1.0",
    "stylelint-scss": "3.13.0"
  },
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write \"**/*.{js,jsx,json,md}\"",
    "start": "npm run develop",
    "serve": "gatsby serve",
    "clean": "gatsby clean",
    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1",
    "lint:js": "eslint --cache --ext .js,.jsx .",
    "lint:scss": "stylelint \"src/**/*.scss\"",
    "lint": "concurrently \"yarn run lint:js\" \"npm run lint:scss\" \"yarn flow\""
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/gatsbyjs/gatsby-starter-default"
  },
  "bugs": {
    "url": "https://github.com/gatsbyjs/gatsby/issues"
  }
}

config.yml
media_folder: static/blogs
public_folder: blogs

collections:
- name: blog
  label: Blog
  folder: "content/blog"
  create: true

Here is the repository link for the DEMO and reproduction of the issue
REPO LINK
Thank you in advance.

A: I am more interested in how do you call those images in your components rather than in the package.json (it doesn't seem a dependencies issue) because inspecting the code, it seems that you've added the /static path which is not required. As it is shown in the following screenshot:

Regarding the updates coming from the comments below, we've figured out that the issue is related directly to this GitHub issue where apparently images retrieved by a markdown are blurring. What solves the issue is to pass a withWebp parameter in Gatsby's configuration, so in gatsby-config.js:
  {
    resolve: 'gatsby-remark-images',
    options: {
      maxWidth: 1920,
      withWebp: true,
    },
  },

Thanks to @Mr. Pyramid for the patience.


text:
Q: Forecasting with plm [panel regression] I am having some troubles with forecasting panel data using the fixed model of the plm pachage. I know that it does not have a built-in forecasting function, so I want to compute the out-of-sample forecasts by hand. Is my logic correct:
fixed <- plm(y ~ x1 + x2, data=panel_df, index=c("country", "year"), model="within")

forecast <- fixed$coefficients[1] * x1 +
            fixed$coefficients[2] * x2 +
            as.numeric(fixef(fixed))

Of course, as this is out-of-sample forecasting, I am using lagged variables (already defined in the data.frame panel_df), and for the forecasting I use the last observations, which should give forecasts for the one-ahead (unknown) period.
I would be grateful for confirming whether such approach is correct!


text:
Q: Android driver-to-device map In android, is there a file or a database which decides which driver (module) will be loaded for a certain USB device?
Some background:
I have a 3g modem which is "supported" by the manufacturer and gets a /dev/ttyUSBx file. I have a phone which can be used as a 3g modem (it works in Linux, just have to force usbserial driver).
My problem is that Android loads cdc_acm driver and creates a /dev/ttyACMx file. In this case the mobile net capability does not show up in Android menus.
My goal is to find the mechanism which handles the 3g modem but ignores the phone. The standard method: insmod usbserial vendor=0xVVVV product=0xPPPP does not work (usbserial module not found). - But clearly there is a mechanism that handles the modem (so it handles usbserial protocol well), but choses to ignore the phone.
Note: modeswitching has nothing to do with it.
Note2: I know this is not strictly a coding question but it is certainly not "user level" stuff either, so I think this site has the best audience to answer it.


text:
Q: Using realloc for dynamic array size vs. initial size in C I am new to C language (coming from java) and wondering what is a better approach in my situation.  I am programming a game and in the function where i generate the moves, i want to return some pointer to an array of structs (a Move is represented by a struct).
Because i don't know in advance what will be the array size, i thought about starting with an empty array an than resize it every time i want to add a move (by realloc(size+1)).   but i wonder if it is more optimal to just set an initial size and if i need to,just double the size.      what is the better approach performance wize?
Thank you!

A: Calling realloc many times would be inefficient. So adding one memory size is a bad idea. Double the size and when you are done and get the exact size you wanted for storing the data you can realloc down to that size. That should take care of wasted memory. But realloc down only at the end when you think you don't need to to increase anymore.
Depending on the particular situation and your implementation if you think doubling is bit too much when the total memory allocated becomes big you can add checks to incrementally add memory. Something like
if (memory_allocated < 100)
   //realloc to double size
else
  //realloc 10 more

The numbers above are arbitrary and you can choose better ones. But use this if doubling the memory is a huge concern. Otherwise doubling and reallocing down to exact is a good enough solution.

A: Apart from doubling the array size using realloc to improve the allocation performance, I'd ask if you really need O(1) access time to each of the Move items. If not you could also use a list instead, like:
typedef struct Move Move;
struct Move {
    /* your stuff here */
    Move *next;
};

With this in mind, you could add a new Move item to the lists head or tail each time you create a new one. But here you'd end up with O(n) access time for random access to the Move items.

A: You could double.  But if you are concerned about the time and wasted space,  you need to know the distribution of the number of moves.  That is, what percent of the time are there 1 moves, 2 moves, etc.  Then a method might be clearer.  Such as double when number of moves is <= 100, but add 20 for greater than 100.
Initially, write code into your game that tracks these stats and adjust your method accordingly.

A: suppose you have an array of n elements,and now it is full. everytime you call realloc(), every elements will be moved to a new space.
realloc(size+1):
the sum of moves is 1+2+...+n = O(n^2)
(even if it begins as k+k+1...+n, it turns out to be O(n^2), where k is the original space you malloc)
realloc(size*2) even if the original space is just one:
the sum of moves is n*(1/2+1/4+...+1/(2^logn)),(2^logn = n)
and the sum's upper bound is 2n, that's to say, O(n).
it's clear that, when the number of total element is quite few, they are almost same.But if the n is large, the double one is more efficient.
by the way, the one which double the size when array is full,is a popular implement of many dynamic array.

A: Increasing by constant amount will lead to each insertion to cost O(n), therefore inserting n elements will have time complexity of O(n²).
The amortized cost of inserting a single element when you increase the allocation by a constant factor is O(1), which means O(n) for insertion of n elements. You don't need to double every time, allocating just 25 % or 20 % or just 15 percent more at most will overallocate that 15 %, and you will still get the O(1) amortized cost per insertion. With 15 % say, the O(1) will have a higher constant factor, but on average will now overallocate much less than with 100 % increment every time the buffer is full.

A: No contest. Choose an arbitrary size and double it each time you need to allocate more memory. The function calls to realloc() for every single struct you need to add would cause your program to be slow.
realloc() is also expensive. Every time you call it, you're going to use a new block of memory on the heap. realloc() does free the originally allocated block when the new memory is successfully allocated; however, this leads to heap fragmentation and you run the risk of running out of contiguous memory to allocate even though there's plenty of free memory.
Finally, every time you call realloc(), you run the risk of the memory allocation failing. Why not minimize the risk by calling it as few times as possible?