text:
Q: Addition of elements of Two Arrays You have Two arrays
int[] a = {......} // Total elements 1 million
int[] b = {......} // Total elements 1 million , Length is same for both arrays.

Q1. I have to create an array
int[] c

whose elements are sum of corresponding indexes of a[] and b []
Ex.
 c[0] = a[0] + b[0];
 c[1] = a[1] + b[1];
 c[2] = a[2] + b[2];

Solution : -> I can take advantage of Multithreading. Divide the whole array in 10 or more parts and assign each segment to a thread to perform the calculation.
Note-> Interviewer suggested to use Multithreading
Q2.
Now its little bit changed.Elements of array C will have values like this :->
c[0] = a[0] + b[0];
c[1] = a[1] + b[1] + c[0]; // At this line c[0] is Sum of a[0] + b[0]; The Above Line
c[2] = a[2] + b[2] + c[1]; // At this line c[0] is Sum of a[1] + b[1]+ a[0] + b[0]; The Above Line

MySolution-> Solve Part 1 (Q1) and create a temporary array and after that we have to perform addition like this.
C[1] = temp[1]+temp[0]
C[2] = temp[2]+temp[1]

Note :-> We really don't need temp[], we can do this only using  Array c Also. Just to explain this on SO in easy way.
Problem-> I dont think that in question 2 we can use multithreding. Is there a better way to solve Q2 ? Can we take advantage of multithreading in this.

A: In my opinion for question two you have two techniques:
First should be done in two steps.
step-1 using threads you can add
 c[0] = a[0] + b[0];
 c[1] = a[1] + b[1];
 c[2] = a[2] + b[2];

as you suggested.
But step-2 should be done sequentially. because c[ i + 1] value depends on updated value of c [i]
Second technique is bit complex but can be fast.
What you are asked to do in second question is do something like:
 c[0] = a[0] + b[0];
 c[1] = a[1] + b[1] + a[0] + b[0];
 c[2] = a[2] + b[2] + a[1] + b[1] + a[0] + b[0];

This can be parallel.
c[i] =  thread1( sum(a[0]...a[i] )) + thread2( sum(b[0]...b[i] ))
         for i >= 0

Good is in this technique, you can calculate c[i] parallely for all i (its two like level threaded model).
You can further improve thread1/thread2 functions as multithread with child threads to perform sum – but remember sometime multi-threaded code runs slow then single-threaded code because of thread context-switching time (So you should give sufficient amount of task to each thread).
A point that is unlike about second technique is "most of what the threads for c[i] do is the same as what the threads for c[i-1] do as well".
Thanks to @jogojapan to let me know about this drawback point.
For better technique read updated answer by Mr.Jogojapan.

A: You can do part 1 multi-threaded as you say giving -
temp[0] = a[0] + b[0];
temp[1] = a[1] + b[1];
temp[2] = a[2] + b[2];
etc....

Then the calculation for part 2 becomes -
c[0] = temp[0];
c[1] = temp[1] + temp[0];
c[2] = temp[2] + temp[1] + temp[0];
c[3] = temp[3] + temp[2] + temp[1] + temp[0];
etc...

Although this looks sequential and impossible to parallelize, it is in fact quite a common operation called a 'prefix sum' or 'scan'. For more details, including how to parallelize, see Wikipedia or Blelloch.
In the 8 elements case this becomes the following where each recursive phase can be parallelized as each calculation has no dependency on other calculations in the same phase.
// 1st phase
u[0] = temp[0] + temp[1];
u[1] = temp[2] + temp[3];
u[2] = temp[4] + temp[5];
u[3] = temp[6] + temp[7];

// 2nd phase
v[0] = u[0] + u[1];
v[1] = u[2] + u[3];

// 3rd phase
w[0] = v[0] + v[1];

// final phase
c[0] = temp[0];
c[1] = u[0];
c[2] = u[0] + temp[2];
c[3] = v[0];
c[4] = v[0] + temp[4];
c[5] = v[0] + u[2];
c[6] = v[0] + u[2] + temp[6];
c[7] = w[0];

A: Actually you could use multithreading in this task. Your algorithm will consist in two parts:

*

*apply Q1 algorithm - this part will use advantage of multithreading.

*just in one-thred loop apply formyla: c[n] = c[n] + c[n-1], n=1...999999.

A: You can use multithreading here in the way from 1st question. I mean you can calculate
sumA0B0 = a[0] + b[0];

in separate threads and even wait for the calculation (sync ie on a[i]). Then in separate thread you can calculate  c[i] = sumAiBi + c[i-1];

A: One way of using multi-threading for Q2 is to do it in two passes (each using T threads internally, where T can be chosen freely):

*

*Compute c[i] = a[i] + b[i] + c[i-1] for all cells in the usual multi-threaded fashion, i.e. after dividing the input into ranges [0,r1), [r1,r2), ... [rk,n) and applying one thread to each range. Yes, this will be incorrect for all ranges except the first one, and step 2 will correct it.

*Compute corrections, again in a multi-threaded fashion. For this, we look up the right-most value of each range, i.e. corr1:=c[r1-1], corr2:=corr1+c[r2-1], corr3:=corr2+c[r3-1] etc., which gives us the correcting value for each thread, and then calculate, again using multi-threading with the same ranges as before, c[i] += corrk where corrk is the thread-specific correcting value for the k-th thread. (For the zeroth thread, we can use corr0:=0, so that thread doesn't need to do anything.)
This improves the theoretical running time by a factor T where T is the number of threads (which can be chosen freely), so it's an optimal solution as far as multithreading is concerned.

To illustrate how this works, here is an example where we assume arrays of length n==30. We further assume that we use 3 threads: One to compute the range c[0..9], one for c[10..19] and one for c[20..29].
Clearly, the goal is that in cell c[i], for any 0<i<n, we get
c[i] == a[0]+...+a[i]+b[0]+...+b[i]

(i.e., the sum of all a[0..i] and all b[0..i]) after the algorithm has finished. Let's have a look at how the algorithm gets there, for an example cell i==23. This cell is handled by the third thread, i.e. the thread responsible for the range c[20..29].
Step 1: The thread sets
c[20] = a[20]+b[20]
c[21] = c[20]+a[21]+b[21] == a[20]+a[21]+b[20]+b[21]
c[22] = c[21]+a[22]+b[22] == a[20]+a[21]+a[22]+b[20]+b[21]+b[22]
c[23] = c[22]+a[23]+b[23] == a[20]+a[21]+a[22]+a[23]+b[20]+b[21]+b[22]+b[23]
...

So, after step 1 has finished, we have the some of a[20..23] and b[20..23] in cell c[23]. What is missing, is the sum of a[0..19] and b[0..19].
Similarly, the first and second threads have set the values in c[0..9] and c[10..19] such that
c[0] = a[0]+b[0]
c[1] = c[0]+a[1]+b[1] == a[0]+a[1]+b[0]+b[1]
...
c[9] = a[0]+...+a[9]+b[0]+...+b[9]

and
c[10] = a[10]+b[10]
...
c[19] = a[10]+...+a[19]+b[10]+...+b[19]

Step 2: The correcting value for the third thread, corr2 is the sum of corr1 and the right-most value computed by the second thread, while corr1 is the right-most value computed by first thread. Hence
corr2 == c[9]+c[19] == (a[0]+...+a[9]+b[0]+...+b[9]) + (a[10]+...+a[19]+b[10]+...+b[19])

And this is indeed the sum missing from the value of c[23] after step 1. In step 2, we add this value to all elements c[20..29], hence, after step 2 has finished, c[23] is correct  (and so are all other cells).

The reason why this works is that the calculation of the cell values is a left-to-right, strictly incremental operation, and the order of operations for the calcuation of a single cell doesn't matter (because + is associative and commutative). Hence the end-result ("right-most value") of any given thread after step 1 can be used to correct the results of threads responsible for the ranges to its right in step 2.


text:
Q: Proving a bipartite graph is not planar I have drawn the bipartite graph K3,3. And I need to prove this graph isn't planar. I used contradiction, assuming it was planar, using Eulers formula to prove it wasn't planar.
I concluded my graph should have 5 faces according to Eulers formula, I then labeled faces on my graph to conlcude there are >5 faces in this graph, and it is clearly not planar.
Is this sufficient enough to prove my graph is not planar?

A: This is the key observation: if a planar bipartite graph has at least one cycle, every face has at least four edges. Counting each edge by its incident faces shows that $4f \le 2m$. This inequality combined with Euler's formula gives $4 = 2n - 2m + 2f \le 2n - m$. However, $K_{3,3}$ has $n=6$ and $m=9$, and so it is not planar.

A: You should first find the amount of vertices, edges, and faces in your graph. Then use euler's formula and if you do not get 2, the graph is not planar.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does this code pass a value to var? There following code is from https://github.com/NanoHttpd/nanohttpd/blob/master/webserver/src/main/java/fi/iki/elonen/SimpleWebServer.java.
Does the code static {mimeTypes(); ...} pass value to the var LICENCE?  Is this valid java syntax? When will the var LICENCE  be passed value? Runtime or Compile-time ?
/**
 * The distribution licence
 */
private static final String LICENCE;
static {
    mimeTypes();
    String text;
    try {
        InputStream stream = SimpleWebServer.class.getResourceAsStream("/LICENSE.txt");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int count;
        while ((count = stream.read(buffer)) >= 0) {
            bytes.write(buffer, 0, count);
        }
        text = bytes.toString("UTF-8");
    } catch (Exception e) {
        text = "unknown";
    }
    LICENCE = text;
}

A: The static { is a static initializer block. This code is run once when the class is loaded.
LICENSE is set to the value of text, which is obtained from the bytes.toString().
It will be set at Runtime.

A: Of cause it will pass value to the var LICENCE. This block will be executed just one time once that class is loaded.
But, DO NOT coding like this. Reading/Writing must not be invoked in Main Thread to not get ANR.


text:
Q: GRUB rescue returns no such partition after deleting Ubuntu partition I have dual booted Windows 10 and ubuntu. I accidently deleted the ubuntu partition from Disk Management from my Windows. After restarting my laptop, I get the following error:
error: no such partition.
Entering rescue mode...
grub rescue>

ls returns:
(hd0) (hd0,msdos1)

When I entered ls (hd0,msdos1)
I get error: (hd0,msdos1): Filesystem is unknown
set command returns:
cmdpath = (hd0)
prefix = (hd0,msdos5)/boot/grub
root = hd0,msdos5

When ls command returns only (hd0,msdos1) , why set is showing as (hd0,msdos5)/boot/grub
Here is what is showing on my screen


text:
Q: It is possible train a neural network for soccer players prediction? I have a large number of players stats, such as goals, assist, meters run, passes, etc.. of 3 seasons. I would like to know if I can feed the Neural Network with the data and it will return the best player of the season. My objective is that with the data the N.N gives me the best player of the season.
I already built an N.N that makes soccer predictions, however, when training I was giving the match result. In this case, it is different, because I'm not giving the information of who was the best player.
If it is possible, what structure should I use and how should I prepare the data?


text:
Q: Meaning of "I got my" What is the difference between and when to use them?
1. I got my hair stuck in the nail
2. My hair got stuck in the nail
I Know about this
1. I got my hair cut - Means - Having some one else do the hair cut
2. I cut my hair - Means - doing the hair cut by the same person

A: Regarding your two examples:

*

*I got my hair stuck in the nail.

*My hair got stuck in the nail.

The former specifies that you are responsible, by usage of the pronoun "I" as the subject (actor) of the sentence.
The latter leaves open as to who is responsible; it could be you, or another person, or the outcome of circumstances (maybe the wind blew your hair).
Regarding this usage of "got" (past tense of "get"):
Oxford:

3.1 [as auxiliary verb] Used with past participle to form the passive mood.
  'the cat got drowned'

American Heritage:

v. intr. 3. b. Used with the past participle of transitive verbs as a passive voice auxiliary: got stung by a bee.


text:
Q: Performance of "function_score" I'm working on a solution for custom score boosting in Elasticsearch.
I wanted to ask if using function_score is a good idea. Because the index size is great but the result of the query should not be that big.
Does function_score work on a query result or rather as a part of query logic? If former, it might be fast, is it?
PS. Initially query boost operator seemed like a best option, but I can't get it to raise a score much above the normal range for one of the match. I've checked _explain API and it says that queryNorm normalizes my boost and I still get values below normal range (0.1 .. 4).

A: In principle - yes, it will slow down the performance of the search. Of course real penalty will depend on the complexity of your script. It will work during so called 'search' phase, so it means, that it will be applied for all matched docs.
You could try to make your logic faster, if your case is suitable for rescoring functionality, cause it's applied only to the top N (configurable in rescore API) results.
More information about rescoring - https://www.elastic.co/guide/en/elasticsearch/guide/current/_improving_performance.html#rescore-api


text:
Q: One IP address has multiple MAC addresses, how is this possible? While looking for duplicate addresses with the following command, "arp-scan --timeout 1000 192.168.110.0/24", I discovered that the host I'm running this command on has multiple MAC addresses for the same IP address.
192.168.110.200 00:90:e8:64:0f:a7       MOXA TECHNOLOGIES CORP., LTD.
192.168.110.200 00:90:e8:64:0f:a9       MOXA TECHNOLOGIES CORP., LTD. (DUP: 2)
192.168.110.200 00:90:e8:64:0f:a5       MOXA TECHNOLOGIES CORP., LTD. (DUP: 3)
192.168.110.200 00:90:e8:64:0f:ab       MOXA TECHNOLOGIES CORP., LTD. (DUP: 4)
192.168.110.200 00:90:e8:64:0f:9b       MOXA TECHNOLOGIES CORP., LTD. (DUP: 5)
192.168.110.200 00:90:e8:64:0f:af       MOXA TECHNOLOGIES CORP., LTD. (DUP: 6)

Note that 192.168.110.200 is the Linux host from which I am running the command.  Additionally, I have 35 other cloned hosts that are in identical isolated networks and I am not seeing this behaviour.
I am starting to think this is hardware problem.

A: it seems to me that you are dealing with an ARP flux. If your Linux host has many Ethernet interfaces on the same subnet then your host replies to ARP requests for interfaces on the same subnet, from any interface on that same subnet.
Starting from kernel 2.6.4, the default behavior of the Linux kernel can be corrected with the two following commands:
$ sysctl -w net.ipv4.conf.all.arp_announce=1
$ sysctl -w net.ipv4.conf.all.arp_ignore=2


text:
Q: bootstrap modal inside php echo and JQuery .load I have index.php which calls other test.php using jQuery and loads the contents in one div tag.
But if I put modal in echo of test.php it doesn't work.
Modal does not open.
Here is my index.php

    <link type="text/css" rel="stylesheet" href="css/bootstrap.css">
    <link type="text/css" rel="stylesheet" href="css/custom.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">

test.php
<?php
echo '
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="modal12">Otryl</button>

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

Modal Header

text

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

';
?>

I think the problem is in $(document).ready()

A: Try the following
Index.php :

test.php :(you missed the # symbol)
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#modal12">Otryl</button>

A: you need add a closure
$(document).ready(function(){
  loadUnSolved();
});


text:
Q: How to include span tags in an array? I think this question has been asked before but I couldn't find a satisfactory answer. I am building a page using React and I need to make some parts of the text bold. Normally I would do this using span tags but the problem is that the text is coming from an array. I tried including the span tag in the array by concatenation but I am getting a weird result. Anyone knows a workaround?
the code
the result

A: Try wrapping your string in a p tag like:

Bla bla bla ...


text:
Q: System.QueryException: unexpected token: = Error is in expression '{!dosearch}' in component public class search {
public search(){
soql = '';
service = new list<Service__c>();
}
public string soql;
public string city{get;set;}
public list<Service__c> service{get;set;}
public void dosearch(){
 soql = '';
 soql = soql + 'select id,name,Bus_Type__c,From__c from Service__c';
 soql = soql + 'Where From__c = ' + '\''+city+'\'';
 system.debug('choos=================>' +soql);
 service = new list<Service__c>();
 service = database.query(soql);// Error hear
}
}

Visualforce
<apex:inputText value="{!city}"/>
<apex:commandButton value="Search" action="{!dosearch}"/> //Error
<apex:pageBlock title="Display Value">
<apex:pageblockTable Value="{!service}" var="v">
<apex:column value="{!v.name}"/>
<apex:column value="{!v.Bus_Type__c}"/>
</apex:pageblockTable>
</apex:pageBlock>

A: you have problem with string query.
Do not use string for SOQL query, until you have to do it, because dynamic SOQL is vulnerable to SOQL Injections. There are two ways to prevent possible SOQL Injections for dynamic queries:

*

*Use String.escapeSingleQuotes(String) method for your city parameter

public void dosearch(){
        soql = 'select id, name, Bus_Type__c,From__c '
              +'from Service__c '
              +'where From__c = \''+String.escapeSingleQuotes(city)+'\'';
        service = Database.query(soql);
}

*

*Use simple bind variables :city
public void dosearch(){
     service = [
         select id, name, Bus_Type__c,From__c
         from Service__c
         where From__c = :city
     ];
}


text:
Q: Is there a data structure like a C++ std set which also quickly returns the number of elements in a range? In a C++ std::set (often implemented using red-black binary search trees), the elements are automatically sorted, and key lookups and deletions in arbitrary positions take time O(log n) [amortised, i.e. ignoring reallocations when the size gets too big for the current capacity].
In a sorted C++ std::vector, lookups are also fast (actually probably a bit faster than std::set), but insertions are slow (since maintaining sortedness takes time O(n)).
However, sorted C++ std::vectors have another property: they can find the number of elements in a range quickly (in time O(log n)).
i.e., a sorted C++ std::vector can quickly answer: how many elements lie between given x,y?
std::set can quickly find iterators to the start and end of the range, but gives no clue how many elements are within.
So, is there a data structure that allows all the speed of a C++ std::set (fast lookups and deletions), but also allows fast computation of the number of elements in a given range?
(By fast, I mean time O(log n), or maybe a polynomial in log n, or maybe even sqrt(n). Just as long as it's faster than O(n), since O(n) is almost the same as the trivial O(n log n) to search through everything).
(If not possible, even an estimate of the number to within a fixed factor would be useful. For integers a trivial upper bound is y-x+1, but how to get a lower bound? For arbitrary objects with an ordering there's no such estimate).
EDIT: I have just seen the
related question, which essentially asks whether one can compute the number of preceding elements. (Sorry, my fault for not seeing it before). This is clearly trivially equivalent to this question (to get the number in a range, just compute the start/end elements and subtract, etc.)
However, that question also allows the data to be computed once and then be fixed, unlike here, so that question (and the sorted vector answer) isn't actually a duplicate of this one.

A: All data structures have their pros and cons, the reason why the standard library  offers a bunch of containers.
And the rule is that there is often a balance between quickness of modifications and quickness of data extraction. Here you would like to easily access the number of elements in a range. A possibility in a tree based structure would be to cache in each node the number of elements of its  subtree. That would add an average log(N) operations (the height of the tree) on each insertion or deletion, but would highly speedup the computation of the number of elements in a range. Unfortunately, few classes from the C++ standard library are tailored for derivation (and AFAIK std::set is not) so you will have to implement your tree from scratch.

A: The data structure you're looking for is an Order Statistic Tree
It's typically implemented as a binary search tree in which each node additionally stores the size of its subtree.
Unfortunately, I'm pretty sure the STL doesn't provide one.

A: Maybe you are looking for LinkedHashSet alternate for C++ https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html.


text:
Q: Why can't I accept an answer immediately?
Possible Duplicate:
Allow me to accept an answer immediately

I asked a basic question, and got a right answer in 1 minute. Why can't I accept it?
If I don't accept the question that is a problem: lower accept rate. If I would accept it, I have to wait 10 minutes unnecessarily. If I come back later then I may forget to accept it.

Let's create an abstract case:
There is a very basic question:

Questioner: 1+1=?

The answer comes from A immediately:

A: ?=2

The questioner accepts the answer in (1 minute!), because he/she checked it and that was correct. A can continue its work unless clicking on accept answer icon in every 30 sec.
B, who are browsing the questions list, will see, that 1+1 is already answered and accepted, and won't start answering the question. He/she may don't even open the question, because it is solved.
B see this:

Here is the feature request:
C, who is still answering the question first got a message, new answer posted. 1 minute later gets a new notification, the answer was solved, here is the solution: 2. C will not thinking about what can 1+1 be, but will chose another question to answer. And C won't post the right answer as a duplication.
PS:
I know that this is a duplication of this and this.

Let me present the case if the answer is not correct:
the answer comes from A immediately:

A: ?=3

The questioner accepts the answer in (1 minutes!), because he/she checked it wrong but figured out that is correct. A is happy that he found an answer so fast.
B, who are browsing the questions list, will see, that 1+1 is already answered and accepted, and won't start answering the question. He/she may don't even open the question, because it is solved. B don't know that the solution was false. B will still ignore the question though may know the right answer.
C, who is answering the question, will see that the solution is wrong. He will post the answer: 2.
A is working, because he thought that the answer is 3. One month later he will return back to Stack Overflow because this error caused a fatal error. After hours of debugging/or seeing C's answer found that 1 + 1 = 2. He will remember it forever.

A: Because other people deserve a shot at answering the question. They may post a better answer, and those better answers deserve better than being trumped just because you can't wait a few minutes.
Not all questions are "basic". And the site needs to serve their needs too.

B, who are browsing the questions list, will see, that 1+1 is already answered and accepted, and won't start answering the question. He/she may don't even open the question, because it is solved.

This assumes that B only saw the question after it was answered and accepted. SO gets a lot of traffic; many people will see the question between the time it was posted and the time someone answers and the answer was accepted.


text:
Q: Mostrar uma imagem em mvc Olá, gostaria de uma ajuda.
Tenho a seguinte controller para cadastrar uma imagem e alguns campos, sendo que a propriedade da imagem é string:
        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public ActionResult Cadastrar(NoticiaViewModel vm, HttpPostedFileBase file)
        {
            try
            {
                vm.ComboCategoriaId = new CategoriaRepositorio().BuscarTodos().Select(x => new SelectListItem { Text = x.NomeCategoria, Value = Convert.ToString(x.CategoriaId) });
                if (!ModelState.IsValid)
                {
                    return View(vm);
                }
                var mapper = Mapper.Map<NoticiaViewModel, Noticia>(vm);
                _repositorio.Salvar(mapper);
                if (file != null)
                {
                    String[] strName = file.FileName.Split('.');
                    String strExt = strName[strName.Count() - 1];
                    string pathSave = String.Format("{0}{1}.{2}", Server.MapPath("~/Imagem/noticias/"), mapper.NoticiaId, strExt);
                    String pathBase = String.Format("/Imagem/noticias/{0}.{1}", mapper.NoticiaId, strExt);
                    file.SaveAs(pathSave);
                    mapper.Imagem = pathSave;
                    _repositorio.Atualizar(mapper);
                }

                TempData["mensagem"] = "Noticia cadastrada com sucesso";
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View();
            }
        }

Até ai tudo bem, eu gravo o caminho onde minha imagem está.
O problema é pra mostrar ela:
        public ActionResult Visualizar(int id)
        {
            try
            {
                Noticia noticia = _repositorio.BuscarPorId(id);
                if (noticia == null)
                {
                    return HttpNotFound();
                }
                var mapper = Mapper.Map<Noticia, NoticiaViewModel>(noticia);
                return View(mapper);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View();
            }
        }

Eu tô usando isso para trazer do banco os dados de uma determinada notícia:
A View está assim:

                @Model.DataCadastro

Categoria: @Model.Categoria.NomeCategoria

Título: @Model.Titulo

                @MvcHtmlString.Create(Model.Descricao)

Mas a imagem não aparece.
Alguém pode me dar uma ajuda?

A: Olá, no seu código troque o seguinte trecho:
   mapper.Imagem = pathSave;

para:
   mapper.Imagem = pathBase;

O que basicamente vocè está fazendo é salvar o caminho físico de sua imagem, e não a url a ser exibida. Você sempre poderá obter o caminho físico da imagem através do método MapPaht como fez em seu código, então não há problemas em salvar a Url.


text:
Q: Is it possible to combine OpenTok and regular calls on mobile? I'm building video chat application. I'm wondering is it possible to make/receive calls during video conversation using OpenTok.
The main point is to allow hear each other caller and video companion - some kind of conference.
I've read documentation for OpenTok, Android and iOS developers and didn't find anything helpful
I've tried to test this and there is no sound in video conversation while call is active. Looks like they use same sound input and output
I know this is a bad question, but I don't know how to make proper request to google or documentation

A: There is no such connectivity right now, so, you cannot mix an OpenTok session, and a regular mobile phone call. You could be interested in inspecting connectivity with SIP networks:
https://tokbox.com/developer/guides/sip/


text:
Q: Where should a ViewModel sit in the directory structure of an ASP.NET MVC application I am about to create a ViewModel to pass some data to a View. So if the application structure is convention based. Where are the ViewModel definitions to be kept.
I could create a new directory called ViewModels, but what is the RIGHT way.

A: I don't think there's a widely accepted convention for this.
I have 'ViewModels' folder too.

A: I keep my view models in the Models folder because my data models reside in a separate assembly.

A: We've reluctantly settled on a models folder as well even though our views and controllers are in separate assemblies.  We painted ourselves into the corner since we also use some of our WCF client-side DTOs directly in the view but those WCF client-side DTOs are generated in our controllers assembly.  I blogged about our dilemma in some greater detail.

A: I keep all VM in a separate assembly (dll), so you can run tests easily against them - even outside ASP.NET scope...


text:
Q: capsh works but systemd doesn't - Openvpn unprivileged user OS: Debian 11
Package: OpenVPN 2.5.1
Background:

After an update, Openvpn-2.5 clients can no longer use iproute to
modify the interface and configure routes pushed by the OpenVPN server
after root privileges are dropped and the system unit running as an
unprivileged user. Based on discussions in these two threads on the
iproute issue:
https://bugs.archlinux.org/task/68480
https://phabricator.vyos.net/T3805
A workaround was suggested to remove user & group directives from
/etc/openvpn/openvpn.conf and to add Ambient Capabilities,
User=tunnel, Group=tunnel to a separate .service file.

There is already an existing Openvpn service file (openvpn@openvpn.service) in /lib/systemd/system so we created a new directory and included a .service file in it - /lib/systemd/system/openvpn@openvpn.service.d/override.conf
# separate service file containing User and group directives along with Ambient capabilities

[Service]

User=tunnel
Group=tunnel
SecureBits=keep-caps

ExecStartPre=/usr/bin/sudo --non-interactive /usr/sbin/openvpn --rmtun --dev tun0
ExecStartPre=/usr/bin/sudo --non-interactive /usr/sbin/openvpn --mktun --dev tun0 --dev-type tun --user tunnel --group tunnel
ExecStopPost=/usr/bin/sudo --non-interactive /usr/sbin/openvpn --rmtun --dev tun0

AmbientCapabilities=CAP_IPC_LOCK CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SYS_CHROOT CAP_DAC_OVERRIDE CAP_AUDIT_WRITE

Ran the following commands:
sudo systemctl daemon-reload
sudo chown -R tunnel:tunnel /etc/openvpn /run/openvpn
sudo /usr/sbin/openvpn --rmtun --dev tun0
sudo /usr/sbin/openvpn --mktun --dev tun0 --dev-type tun --user tunnel --group tunnel
cd /etc/openvpn/
sudo -u tunnel openvpn /etc/openvpn/openvpn.conf

Error
The expectation was that the unprivileged User=tunnel will have the ambient capabilities to open up tun0 and modify the interface to complete the openvpn connection. However, it encountered an error.
#Error after running sudo -u tunnel openvpn /etc/openvpn/openvpn.conf

2022-06-24 17:32:08 us=174691 TUN/TAP device tun0 opened
2022-06-24 17:32:08 us=174755 do_ifconfig, ipv4=1, ipv6=0
2022-06-24 17:32:08 us=174844 net_iface_mtu_set: mtu 1500 for tun0
2022-06-24 17:32:08 us=175005 sitnl_send: rtnl: generic error (-1): Operation not permitted
2022-06-24 17:32:08 us=175084 Linux can't set mtu (1500) on tun0
2022-06-24 17:32:08 us=175142 Exiting due to fatal error

The solution that works
However, with capsh, I gave Ambient Capability directly to the Openvpn executable with user=tunnel privileges, and nothing in the systemd service:
sudo /sbin/capsh --keep=1 --user='tunnel' --inh='cap_ipc_lock,cap_net_admin,cap_net_bind_service,cap_net_raw,cap_setgid,cap_setuid,cap_sys_chroot,cap_dac_override,cap_audit_write' --addamb='cap_ipc_lock,cap_net_admin,cap_net_bind_service,cap_net_raw,cap_setgid,cap_setuid,cap_sys_chroot,cap_dac_override,cap_audit_write' -- -c 'openvpn /etc/openvpn/openvpn.conf'

The issue:

Why wasn't systemd able to set the Ambient Capabilities for
user=tunnel whereas capsh was able to? How to make this work with
systemd?

A: I suspect sudo -u tunnel clears ambient capabilities. To confirm, you might try inserting these lines before the last one:
/sbin/capsh --print
sudo -u tunnel /sbin/capsh --print
sudo -u tunnel openvpn /etc/openvpn/openvpn.conf


text:
Q: JSON to PHP API not happening I am trying to save data on click of button using Javascript and PHP.
Button click:
            var xhr = new XMLHttpRequest();
            var url = "savedata.php";
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/json");
            /*xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var json = JSON.parse(xhr.responseText);
                    console.log(json.rawText + ", " + json.convertedText);
                }
            };*/
            var data = JSON.stringify({"rawText": rt, "convertedText": ct});
            xhr.send(data);

savedata.php
<?php
header("Content-Type: application/json");

require('db/db.php');
session_start();

    $saverawText = $_POST['rawText'];
    $saveConvertedText = $_POST['convertedText'];

    $ins_query="insert into cmn_data (`rawtext`,`convertedtext`) values ('$saverawText','$saveConvertedText')";
    $result = mysqli_query($con, $ins_query);

?>

In Db: One record is created but it is empty so every time I click save button 1 record is created but empty. What is the wrong the above syntax?
Thanks!

A: PHP does not parse JSON requests to $_POST array itself. You should either parse request body in php:
$request = json_decode(file_get_contents('php://input'), true);
$saverawText = $request['rawText'];
$saveConvertedText = $request['convertedText'];

or pass data to request with FormaData object:
var data = new FormData();
data.append("rawText", rt);
data.append("convertedText", ct);
xhr.send(data);

And as mentioned before, including user input directly into sql could cause sql injections. Use mysqli_real_escape_string to escape user inputs or PDO driver, which is bit more complicated but more reliable approach.

A: You can POST your values like that :
var xhr = new XMLHttpRequest();
var url = "savedata.php";
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
/*xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.rawText + ", " + json.convertedText);
    }
};*/
var data = "rawText=" + rt + "&convertedText=" + ct;
xhr.send(data);


text:
Q: Difficulty morphing a series of images in Java I'm having a little difficulty doing an assignment.  I'll post the class and explain.
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.text.*;

/**
 * A class that represents a picture.  This class inherits from
 * SimplePicture and allows the student to add functionality to
 * the Picture class.
 *
 * Copyright Georgia Institute of Technology 2004-2005
 * @author Barbara Ericson ericson@cc.gatech.edu
 */
public class Picture extends SimplePicture
{
  ///////////////////// constructors //////////////////////////////////

  /**
   * Constructor that takes no arguments
   */
  public Picture ()
  {
    /* not needed but use it to show students the implicit call to super()
     * child constructors always call a parent constructor
     */
    super();
  }

  /**
   * Constructor that takes a file name and creates the picture
   * @param fileName the name of the file to create the picture from
   */
  public Picture(String fileName)
  {
    // let the parent class handle this fileName
    super(fileName);
  }

  /**
   * Constructor that takes the width and height
   * @param width the width of the desired picture
   * @param height the height of the desired picture
   */
  public Picture(int width, int height)
  {
// let the parent class handle this width and height
super(width,height);
  }

  /**
   * Constructor that takes a picture and creates a
   * copy of that picture
   */
  public Picture(Picture copyPicture)
  {
    // let the parent class do the copy
    super(copyPicture);
  }

  ////////////////////// methods ///////////////////////////////////////

  /**
   * Method to return a string with information about this picture.
   * @return a string with information about the picture such as fileName,
   * height and width.
   */
  public String toString()
  {
    String output = "Picture, filename " + getFileName() +
      " height " + getHeight()
      + " width " + getWidth();
    return output;

  }

 /**
  * Modified version of method from page 154 of the textbook for copying pictures
  */
 public void copyPictureTo(Picture sourcePicture, int xStart, int yStart)
 {
   Pixel sourcePixel = null;
   Pixel targetPixel = null;

   //loop through the columns
   try{
   for (int sourceX = 0, targetX = xStart;
        sourceX < sourcePicture.getWidth();
        sourceX++, targetX++)
   {
     //loop through the rows
     for (int sourceY = 0,
          targetY = yStart;
          sourceY < sourcePicture.getHeight();
          sourceY++, targetY++)
     {
       sourcePixel = sourcePicture.getPixel(sourceX,sourceY);
       targetPixel = this.getPixel(targetX,targetY);
       targetPixel.setColor(sourcePixel.getColor());
     }
   }
  }catch(IndexOutOfBoundsException ex){System.out.println("Either xStart or yStart is out of bounds");System.exit(0);}
}
 //morphStage() method is located here.

 public void morphStage(Picture startPicture, Picture endPicture, int numStages, int k)
 {
   Pixel[] pixelArrayStart = startPicture.getPixels();
   Pixel[] pixelArrayEnd = endPicture.getPixels();
   Pixel pixelObjEnd = null;
   Pixel pixelObjStart = null;
   Pixel pixelObjNew = null;

   //Colour values for starting picture.

   int startingRedValue = 0;
   int startingGreenValue = 0;
   int startingBlueValue = 0;

   //Colour values for ending picture.

   int endRedValue = 0;
   int endGreenValue = 0;
   int endBlueValue = 0;

   //Colour values for intermediate pictures.

   int redValue = 0;
   int greenValue = 0;
   int blueValue = 0;

   //Loops through each entry int he first array, getting the RGB values
   for (int i = 0; i < pixelArrayStart.length; i++)
   {
     //Loops through each entry in the second array, getting the RGB values
     {
       for (int j = 0; j < pixelArrayEnd.length; j++)
       {
         pixelObjEnd = pixelArrayEnd[j];
         endRedValue = pixelObjEnd.getRed();
         endGreenValue = pixelObjEnd.getGreen();
         endBlueValue = pixelObjEnd.getBlue();
         pixelObjStart = pixelArrayStart[i];
         startingRedValue = pixelObjStart.getRed();
         startingGreenValue = pixelObjStart.getGreen();
         startingBlueValue = pixelObjStart.getBlue();
         redValue = startingRedValue +((endRedValue - startingRedValue)/(numStages + 1))*k;
         greenValue = startingGreenValue +((endGreenValue - startingGreenValue)/(numStages + 1))*k;
     blueValue = startingBlueValue +((endBlueValue - startingBlueValue)/(numStages + 1))*k;
         pixelObjNew.setRed(redValue);
         pixelObjNew.setGreen(greenValue);
         pixelObjNew.setBlue(blueValue);
       }
     }
   }
 }
}

 // end of class Picture, put all new methods before this

The idea is to create a series of intermediate pictures using the equation, redValue = startingRedValue +((endRedValue - startingRedValue)/(numStages + 1))*k.
I'm not sure if I'm writing the code properly, but the idea was to create an array of pixels for the first picture, get the RGB values, create an array of pixels for the second picture, get the RGB values, and then create the a new pixel, pixelObjNew by setting each RGB value using the equation.
The code compiles fine, but when I try to run it with two pictures, there's an error.  (NB:  TestMorphing is the class I wrote for the test)
java.lang.NullPointerException
    at Picture.morphStage(Picture.java:149)
    at TestMorphing.main(TestMorphing.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at     sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at     edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

This is an introduction to computer science class, btw.
Much appreciated!
EDIT:  Here's the pixel class.
import java.awt.Color;

/**
 * Class that references a pixel in a picture. A pixel has an x and y
 * location in a picture.  A pixel knows how to get and set the red,
 * green, blue, and alpha values in the picture.  A pixel also knows
 * how to get and set the color using a Color object.
 *
 * Copyright Georgia Institute of Technology 2004
 * @author Barb Ericson ericson@cc.gatech.edu
 */
public class Pixel
{

  ////////////////////////// fields ///////////////////////////////////

  /** the digital picture this pixel belongs to */
  private DigitalPicture picture;

  /** the x location of this pixel in the picture (0,0) is top left */
  private int x;

  /** the y location of this pixel in the picture (0,0) is top left */
  private int y;

  ////////////////////// constructors /////////////////////////////////

  /**
   * A constructor that take the x and y location for the pixel and
   * the picture the pixel is coming from
   * @param picture the picture that the pixel is in
   * @param x the x location of the pixel in the picture
   * @param y the y location of the pixel in the picture
   */
  public Pixel(DigitalPicture picture, int x, int y)
  {
    // set the picture
    this.picture = picture;

    // set the x location
    this.x = x;

    // set the y location
    this.y = y;

  }

  ///////////////////////// methods //////////////////////////////

  /**
   * Method to get the x location of this pixel.
   * @return the x location of the pixel in the picture
   */
  public int getX() { return x; }

  /**
   * Method to get the y location of this pixel.
   * @return the y location of the pixel in the picture
   */
  public int getY() { return y; }

  /**
   * Method to get the amount of alpha (transparency) at this pixel.
   * It will be from 0-255.
   * @return the amount of alpha (transparency)
   */
  public int getAlpha() {

    /* get the value at the location from the picture as a 32 bit int
     * with alpha, red, green, blue each taking 8 bits from left to right
     */
    int value = picture.getBasicPixel(x,y);

// get the alpha value (starts at 25 so shift right 24)
// then and it with all 1's for the first 8 bits to keep
// end up with from 0 to 255
int alpha = (value >> 24) & 0xff;

return alpha;
  }

  /**
   * Method to get the amount of red at this pixel.  It will be
   * from 0-255 with 0 being no red and 255 being as much red as
   * you can have.
   * @return the amount of red from 0 for none to 255 for max
   */
  public int getRed() {

    /* get the value at the location from the picture as a 32 bit int
     * with alpha, red, green, blue each taking 8 bits from left to right
     */
    int value = picture.getBasicPixel(x,y);

    // get the red value (starts at 17 so shift right 16)
    // then and it with all 1's for the first 8 bits to keep
    // end up with from 0 to 255
    int red = (value >> 16) & 0xff;

    return red;
  }

  /**
   * Method to get the red value from a pixel represented as an int
   * @param value the color value as an int
   * @return the amount of red
   */
  public static int getRed(int value)
  {
    int red = (value >> 16) & 0xff;
    return red;
  }

  /**
   * Method to get the amount of green at this pixel.  It will be
   * from 0-255 with 0 being no green and 255 being as much green as
   * you can have.
   * @return the amount of green from 0 for none to 255 for max
   */
  public int getGreen() {

    /* get the value at the location from the picture as a 32 bit int
     * with alpha, red, green, blue each taking 8 bits from left to right
     */
    int value = picture.getBasicPixel(x,y);

    // get the green value (starts at 9 so shift right 8)
    int green = (value >>  8) & 0xff;

    return green;
  }

  /**
   * Method to get the green value from a pixel represented as an int
   * @param value the color value as an int
   * @return the amount of green
   */
  public static int getGreen(int value)
  {
    int green = (value >> 8) & 0xff;
    return green;
  }

  /**
   * Method to get the amount of blue at this pixel.  It will be
   * from 0-255 with 0 being no blue and 255 being as much blue as
   * you can have.
   * @return the amount of blue from 0 for none to 255 for max
   */
  public int getBlue() {

    /* get the value at the location from the picture as a 32 bit int
     * with alpha, red, green, blue each taking 8 bits from left to right
     */
    int value = picture.getBasicPixel(x,y);

    // get the blue value (starts at 0 so no shift required)
    int blue = value & 0xff;

    return blue;
  }

  /**
   * Method to get the blue value from a pixel represented as an int
   * @param value the color value as an int
   * @return the amount of blue
   */
  public static int getBlue(int value)
  {
    int blue = value & 0xff;
    return blue;
  }

  /**
   * Method to get a color object that represents the color at this pixel.
   * @return a color object that represents the pixel color
   */
  public Color getColor()
  {
     /* get the value at the location from the picture as a 32 bit int
     * with alpha, red, green, blue each taking 8 bits from left to right
     */
    int value = picture.getBasicPixel(x,y);

    // get the red value (starts at 17 so shift right 16)
    // then and it with all 1's for the first 8 bits to keep
    // end up with from 0 to 255
    int red = (value >> 16) & 0xff;

    // get the green value (starts at 9 so shift right 8)
    int green = (value >>  8) & 0xff;

    // get the blue value (starts at 0 so no shift required)
    int blue = value & 0xff;

    return new Color(red,green,blue);
  }

  /**
   * Method to set the pixel color to the passed in color object.
   * @param newColor the new color to use
   */
  public void setColor(Color newColor)
  {
    // set the red, green, and blue values
    int red = newColor.getRed();
    int green = newColor.getGreen();
    int blue = newColor.getBlue();

    // update the associated picture
    updatePicture(this.getAlpha(),red,green,blue);
  }

  /**
       * Method to update the picture based on the passed color
       * values for this pixel
       * @param alpha the alpha (transparency) at this pixel
       * @param red the red value for the color at this pixel
       * @param green the green value for the color at this pixel
       * @param blue the blue value for the color at this pixel
       */
      public void updatePicture(int alpha, int red, int green, int blue)
      {
        // create a 32 bit int with alpha, red, green blue from left to right
        int value = (alpha << 24) + (red << 16) + (green << 8) + blue;

        // update the picture with the int value
        picture.setBasicPixel(x,y,value);
      }

      /**
       * Method to correct a color value to be within 0 and 255
       * @param the value to use
       * @return a value within 0 and 255
       */
      private static int correctValue(int value)
      {
        if (value < 0)
          value = 0;
        if (value > 255)
          value = 255;
        return value;
      }

      /**
       * Method to set the red to a new red value
       * @param value the new value to use
       */
      public void setRed(int value)
      {
        // set the red value to the corrected value
        int red = correctValue(value);

        // update the pixel value in the picture
        updatePicture(getAlpha(), red, getGreen(), getBlue());
      }

      /**
       * Method to set the green to a new green value
       * @param value the value to use
       */
      public void setGreen(int value)
      {
        // set the green value to the corrected value
        int green = correctValue(value);

        // update the pixel value in the picture
        updatePicture(getAlpha(), getRed(), green, getBlue());
      }

      /**
       * Method to set the blue to a new blue value
       * @param value the new value to use
       */
  public void setBlue(int value)
  {
    // set the blue value to the corrected value
    int blue = correctValue(value);

    // update the pixel value in the picture
    updatePicture(getAlpha(), getRed(), getGreen(), blue);
  }

   /**
   * Method to set the alpha (transparency) to a new alpha value
   * @param value the new value to use
   */
  public void setAlpha(int value)
  {
    // make sure that the alpha is from 0 to 255
    int alpha = correctValue(value);

    // update the associated picture
    updatePicture(alpha, getRed(), getGreen(), getBlue());
  }

  /**
  * Method to get the distance between this pixel's color and the passed color
  * @param testColor the color to compare to
  * @return the distance between this pixel's color and the passed color
  */
 public double colorDistance(Color testColor)
 {
   double redDistance = this.getRed() - testColor.getRed();
   double greenDistance = this.getGreen() - testColor.getGreen();
   double blueDistance = this.getBlue() - testColor.getBlue();
   double distance = Math.sqrt(redDistance * redDistance +
                               greenDistance * greenDistance +
                               blueDistance * blueDistance);
   return distance;
 }

 /**
  * Method to compute the color distances between two color objects
  * @param color1 a color object
  * @param color2 a color object
  * @return the distance between the two colors
  */
 public static double colorDistance(Color color1,Color color2)
 {
   double redDistance = color1.getRed() - color2.getRed();
   double greenDistance = color1.getGreen() - color2.getGreen();
   double blueDistance = color1.getBlue() - color2.getBlue();
   double distance = Math.sqrt(redDistance * redDistance +
                               greenDistance * greenDistance +
                               blueDistance * blueDistance);
   return distance;
 }

 /**
  * Method to get the average of the colors of this pixel
  * @return the average of the red, green, and blue values
  */
 public double getAverage()
 {
   double average = (getRed() + getGreen() + getBlue()) / 3.0;
   return average;
 }

  /**
   * Method to return a string with information about this pixel
   * @return a string with information about this pixel
   */
  public String toString()
  {
    return "Pixel red=" + getRed() + " green=" + getGreen() +
      " blue=" + getBlue();
  }

}

A: Your problem seems to stem from your trying to use the Pixel type variable, pixelObjNew, while it is still null. You appear to be using a 3rd party library, likely part of your Ga Tech class code, and our not being privy to this code will necessary limit our ability help, but having said that, the bottom line is that you should first assign a valid instantiated object to this variable prior to trying to use it. This might be as simple as calling,
pixelObjNew = new Pixel();

Or it might be a whole lot more complex. Check your library's API, your class notes, your sample code, to find out what you should do.
Key points for solving NPE:

*

*Finding and inspecting the line that throws the NPE is critical to solving it.

*A variable that you are trying to use on that line is null, and your trying to dereference it is causing your problem.

*Often it's obvious by looking at the line to see which variable is at fault.

*At other times you'll need a debugger or System.out.println(...)` statements (the so-called "poor man's debugger") to help you.

Edit
On looking at your Pixel class, it appears that 1) using a default constructor won't do,  and that 2) a Pixel by itself appears to be meaningless, that it only makes sense in context with the Picture from which it is a component. This would also suggest to me that your current approach to morphing might be (accent on the might) be off.
My guess, and please understand that this is a huge guess, is that you might want to create several Picture objects, one for each intermediate stage, and one for the end picture. And then you can extract Pixel arrays from each Picture and adjust them (linearly?). Again this is a silly wild arsed guess. Use this advice with caution.
Also, I think that I would not nest for loops to do my morphing if it is to be a linear morph.

A: pixelObjNew is initialized as null and that never changes.  So pixelObjNew.setRed(redValue); is going to throw an NPE.


text:
Q: Using importXML results in "Imported Content is Empty" error on Google Spreadsheets What I'm trying to do:
Dynamically import the bitcoin/BTC price, from https://www.luno.com/en/price/, OR https://www.luno.com/en/price/BTC.
So I've read everything there is to read (on this site anyway) about importXML, and cannot find what I'm doing wrong. My method works on other websites, where I get a list of expected results, however, using importXML is not working. See below code I'm using (I've used other variants, but this is the one suggested using SelectorGadget:
=IMPORTXML("https://www.luno.com/en/price/", "//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'ng-binding', ' ' ))]")

Of course, I get the dreaded " Imported Content is Empty " error.
Any help?

A: You can load this ajax endpoint to get the current USD:
https://www.luno.com/ajax/1/display_ticker
or for all currency pairs:
https://www.luno.com/ajax/1/price_chart?currency=
if your want to parse the json - there is a wonderful - already written importJson script (https://github.com/bradjasper/ImportJSON/blob/master/ImportJSON.gs), you literally just copy paste it into your apps script and then call the url directly as such:
=importJSON("https://www.luno.com/ajax/1/price_chart?currency=")
or
=importJSON("https://www.luno.com/ajax/1/display_ticker?currency=XBT")


text: Q: Journey builder wait activity delay In my journey, there is a wait by attribute. The wait interval is on ReviewDate (GMT Standard Time). But it leaves wait activity sometimes the next day, sometimes 2 days later, sometimes 5 days later. I have examples with all 3 cases. It is quite random. How can it be fixed and sent as per the defined wait activity i.e. on the date of the attribute?


text: Q: Smooth scroll in IOS 8 I am implementing smooth scrolling in my div, and inside the same div I am using the jquery drag. While I am dragging the inner div the outer div on which I am using smooth scroll is going blank. Do any body have idea why is this happening. I will be very thankful if anybody can come up with any sort of solution.


text:
Q: Sqlite with c# and where clause I have the following code working fine, but how do I add a where clause in.
Been trying the following  string:
 sql = "select [ip_address], [name], [model], [mac_address], [operating_system], [current_user]from [devices] where [ip_address] = @192.168.0.56";
using System;
using System.Data.SQLite;
using System.IO;

namespace SQLiteSamples
{
    class Program
    {
        // Holds our connection with the database
        SQLiteConnection m_dbConnection;

        public string Info { get; private set; }

        static void Main(string[] args)
        {
            Program p = new Program();
        }

        public Program()
        {

            connectToDatabase();
            printResult();
        }

        // Creates a read only connection to spiceworks database file.
        void connectToDatabase()
        {
            //m_dbConnection = new SQLiteConnection(@"Data Source=\\spiceworks\db\spiceworks_prod.db;Version=3;Read Only=True");
            m_dbConnection = new SQLiteConnection(@"Data Source=C:\Temp\ZipSampleExtract\db\spiceworks_prod.db;Version=3;Read Only=True");
            m_dbConnection.Open();
        }

        // Writes the output from spiceworks table devices.
        void printResult()
        {

            string sql = "select [ip_address], [name], [model], [mac_address], [operating_system], [current_user]from [devices]";
            SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
            SQLiteDataReader reader = command.ExecuteReader();

            while (reader.Read())

           Console.WriteLine("ip_address: " + reader["ip_address"] + "  " + reader["name"] + "  " + reader["model"] + "  " + reader["mac_address"]+"  " + reader["operating_system"] + "  " + reader["current_user"]);
           Info = Convert.ToString(Console.ReadLine());
           File.WriteAllText("E:\\johnb.txt", Info);

       }

    }
}

A: String literals in SQL are denoted by single quotes:
string sql = "select [ip_address], [name], [model], [mac_address], [operating_system], [current_user] from [devices] where [ip_address] = '192.168.0.56'";

A: You will want to use parameters to protect against SQL injection in your final project.
    string sql = "select [ip_address], [name], [model], [mac_address], [operating_system], [current_user]from [devices] where [ip_address] = @ip_address";
    SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
    command.Parameters.Add(new SqlParameter("@ip_address", ipAddressValue));

    SQLiteDataReader reader = command.ExecuteReader();


text:
Q: Is lookup skew bad if it doesn't bring about row lock contention? On Opportunity there are two lookups fields, the standard Primary Campaign Source, and a custom lookup to object Exhibition__c (which is set to Clear the value of this field if related record is deleted). So in theory, these should not cause any row lock issues, right? The company uses 1 campaign per year and one 1 Exhibition__c record per year with over 100k Opportunities. I am aware this is not best practice, but I am trying to understand the technical issues caused by this.
What will having this lookup skew produce? Is it simply processing time?

A: Aside from potential row lock issues (which could happen if a trigger on Opportunity causes an update to Campaign or Exhibition__c), the biggest practical issue that you'd run into here is that this makes the index on your lookup fields less useful.
Lookup fields are one of the field types that is automatically indexed by Salesforce, but if you have enough child records using a single parent then that index doesn't really help Salesforce in query planning. It harms (or rather, doesn't help) query selectivity, so any query you have which uses that lookup as a filter (as the only index filter) has a chance of running into the "Non-selective query against large object type (more than 200000 rows)" error.
Note that you don't need a single index to be used 200k times for this error to appear, just that the object at the base of your query (e.g. Opportunity) has more than 200k rows, and enough records related to a single parent record.


text:
Q: USB type-c power supply (up to 20V 5A) from DC source I have a custom made 5s power bank (30 x 18650 cells) and I want to make a power supply to charge my laptop using this power bank. It's not a big deal to make a 5V charger because I just have to hard wire a 5V step down regulator and it will work, but what about higher voltages?
Of course, I can use a standard AC power supply and connect it using a car power inverter, but efficiency in this case will be quite low. I tried to find such power supply/controller on aliexpress or ebay, but it looks like only 5V versions are available. What is the best/easiest way to do it?
Thank you!

A: Form the set of keywords "USB", "type-C", "power supply" "up to 20V 5A" and the literal question,

I want to make a power supply to charge my laptop using this power
  bank. It's not a big deal to make a 5V charger ...[snip], but what
  about higher voltages?

it is obvious the that the question is about implementation of Power Delivery protocol over Type-C CC lines and design of power supply (controllable DC-DC converter) with variable output in accord with Power Delivery handshake protocol.
Answer: there are several semiconductor companies who offer a portfolio of ICs and design guidances on how to build a PD over Type-C.
One is Texas Instruments, see their presentation on USB Developer Days 2017.
The other is ST Micro, see their guide.
Cypress Semiconductors offers a portfolio of reference designs as well.
This is from just the first page of Google search. There are several other companies like Maxim, Fairchild, NXP, ON Semi, Renesas/NEC, Rohm, and maybe many more Chinese sources with similar products.

A: I am aware of two such devices.

*

*ChargerLAB POWER-Z DC to USB PD Converter Board JGL-DCPD review at https://kknews.cc/digital/e8mezky.html

*Magicfox PD180. It takes a 12-28V DC via 5.5 * 2.5/2.1mm barrel (or USB C PD 100W) and provides two USB C ports and an USB A port. A review  http://bbs.chongdiantou.com/thread-57387-1-1.html here and the same is https://kknews.cc/zh-tw/digital/rorpmmv.html here as well.
Google Translate helps in translating the Chinese reviews. The first one seems to be available from an Asian reseller in English, shipping worldwide (Google is your friend). The second is on jd.com but there are various Chinese shopping proxies to help.

A: If you are still looking for a solution, I found a DC to PowerDelivery converter which has reviews on Amazon. I have not used this myself I a searching for a Solar Panel DC output to PowerDelivery converter. I may eventually try this myself, but none of the reviews talked about solar panels, just AC power supplies with this device. https://www.amazon.com/BiXPower-Type-Power-Converter-Delivery/dp/B07BC5TWJB/ref=sr_1_3?keywords=USB+Type+C+Power+Converter+bixpower&qid=1581808832&sr=8-3
I thought power delivery devices would be more prevalent now, but only a few solar panels with PD output are available which are very expensive.


text:
Q: Cannot edit fields in custom UITableViewCell (iOS 9) after upgrading to iOS 9 (worked fine in iOS 8), I am having trouble clicking UIBUttons and editing UITextFields inside custom UITableViewCells.
I have an UITableView with custom UITableViewCells. These cells are loaded like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
        controller=[[PresetRowViewController alloc] initWithNibName:@"PresetRowViewController" bundle:nil];
...
    return (UITableViewCell *)controller.view;
}

The cells show fine, but I cannot click in any UIButton or edit any UITextField inside them.
Any ideas?
Thanks

A: Try checking for gesture recognizers (ie. view.gestureRecognizers = nil;) for various views (the button, cell itself). Also make sure button.userInteractionEnabled = YES; and cell.userInteractionEnabled = YES; Finally, make sure there's no invisible views overtop of the button/cell.

A: Try to bring the subviews in the customized table view cell to the front.

A: I had this same issue. Apple changed how UITableViewCells work in iOS 9. It was fixed for me by dragging in a new UITableViewCell into the Xib and moving everything over. See: https://stackoverflow.com/a/32826526/101923


text:
Q: Flutter Scaffold showing BottomAppBar Space even not requested anyone can tell me why this is happend ?

its make spacing from bottom app bar even i not write the code
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:orangiro_pos/utils.dart';

import '../routing_constants.dart';

class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIOverlays([]);
    return WillPopScope(
      onWillPop: () => Future.value(false),
      child: Scaffold(
        body: Container(
                color: Colors.grey[200],
                child: Row(
                  children: <Widget>[
                    Container(
                      width: MediaQuery.of(context).size.width * .6,
                      height: MediaQuery.of(context).size.height,
                      child: Center(
                        child: Container(
                          child: Image.asset("assets/images/logo-ww.png"),
                        ),
                      ),
                    ),
                    Container(
                      width: MediaQuery.of(context).size.width * .4,
                      height: MediaQuery.of(context).size.height,
                      color: Colors.grey[800],
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text("Login", style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold, color: Colors.white)),
                          Divider(),
                          SizedBox(height: 10,),
                          titledInput(hint: "Username"),
                          SizedBox(height: 10,),
                          titledInput(hint: "Password"),
                          SizedBox(height: 10,),
                          Divider(),
                          GestureDetector(
                            onTap: () {
                              Navigator.pop(context);
                            },
                            child: Container(
                              height: 55,
                              width: MediaQuery.of(context).size.width * .9 * .75 - 45,
                              color: Colors.amber,
                              child: Center(child: Text("Login", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),)),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                )
              ),
        ),
      );
  }
}

this is my code, i totally dont know why this is happend. i think its generated by BottomAppBar because it have same height as i used in my dashboard.

A: You can fix it by adding resizeToAvoidBottomInset: false in your Scafflod():
child: Scaffold(
      resizeToAvoidBottomInset: false,
      ...,
)


text:
Q: Does the cloud code plugin for intellij work with Azure I see that GCP is set on default to sign in so wondering if it works with Azure and if so how do i connect to it

A: Cloud Code IntelliJ Kubernetes features do work with any Kubernetes cluster, regardless of vendor, local or remote. Cloud Code uses standard kubectl configuration (kubeconfig file) to communicate with clusters. When you have your Azure cluster set up, make sure you have it configured on your machine for kubectl (so kubectl config get-contexts contains an entry for your Azure cluster and it is properly configured and accessible - please follow Azure Kubernetes configuration documentation for that).
Once Azure cluster is configured on your machine, it will appear in Cloud Code - you can use the Kubernetes Explorer, develop and debug on it just like with GKE or any other Kubernetes cluster of you choosing.


text:
Q: Is $H^{1}(\Omega)$ defined by $\left\{u \in L^{2}(\Omega) | \nabla u \in L^{2}(\Omega)^{d}, u=0 \text { on } \partial \Omega\right\}$ I can't see the difference between these two Sobolev spaces:
$H^{1}(\Omega):=\left\{u \in L^{2}(\Omega) | \nabla u \in L^{2}(\Omega)^{d}, u=0 \text { on } \partial \Omega\right\}$
and $H_{0}^{1}(\Omega)=\left\{v \in H^{1}(\Omega) | v_{| \partial \Omega}=0 \text { on } \partial \Omega\right\}$
Where $\gamma_{0}$ is linear from $H^{1}(\Omega) \cap C(\bar{\Omega})$ to $L^{2}(\partial \Omega) \cap C(\overline{\partial \Omega})$ by $\gamma_{0} v:=v_{| \partial \Omega}$
the definition that I usually use is:
$H^{1}(\Omega)=\left\{u \in L^{2}(\Omega) | D_{i} u \in L^{2}(\Omega), \forall i=1, \ldots, N\right\}$
but in the paper I am reading the authors state that:
$H^{1}(\Omega):=\left\{u \in L^{2}(\Omega) | \nabla u \in L^{2}(\Omega)^{d}, u=0 \text { on } \partial \Omega\right\}$
I am a beginner in Sobolev spaces.. someone can give me a hint?


text:
Q: How do I restrict certain values in column 2 with the same value in column 1 in SQL? consider the following ERD for a MySQL database:

the table roles contains all kinds of (website-specific) roles users that are logged in could have. As you can see from the ERD: members can have multiple roles, and roles can have multiple members assigned to them.
The table members is dynamic, new members with custom roles can be made at any time, but the roles table is not. The current set-up of roles is final.
The records inside the roles table look like this:

 id  rolename
 1   captain
 2   cabin boy
 3   buccaneer
 4   parrot caretaker
 5   cook

Now for the problem: I want members to have certain roles assigned to them, but certain combinations of roles cannot be chosen. For example, a captain can not also be a cabin boy, but he can also be a parrot caretaker. A cook can also be a cabin boy, but not a parrot caretaker.
I have done some research on Google regarding this topic, but I seem to fail in finding the right keywords to actually find usable information to solve this problem. All I seem to find are references and tutorials on how the SQL CHECK works, but not quite THAT in-depth.
Is there a way for me to use MySQL constraints to restrict some combinations from happening? If not, might this problem be solved using triggers or functions? I am generally looking for the most efficient solution to this, it does not necessarily have to be on the database side.

A: This depends on a few things..
Do you want the database to handle this logic or are you happy to have it at the application level?
If you want the database to handle it, you are probably going to want a trigger.. mysql parses a CHECK constraint but doesn't enforce it.
Either way you'll probably want to store the allowed combinations somewhere.
For simple cases I'd go for either a black-list or a white-list of other roles for each role depending on numbers. You can store this easily in another table.
Another option is a pre-requisite table, for example to be an admiral you must also be a captain.


text:
Q: Erro ao inserir dados do banco na JTable Estou com um problema ao carregar os dados em uma JTable, uso BD Derby, a conexão do banco de dados funciona mais ao tentar abrir o JFrame Cad_Usuarios aparece o erro abaixo:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Controle.ConexaoBD.executaSQL(ConexaoBD.java:57)
at Visao.Cad_Usuarios.preencherTabela(Cad_Usuarios.java:235)
at Visao.Cad_Usuarios.<init>(Cad_Usuarios.java:32)
at Visao.cadastro.jMUsuariosActionPerformed(cadastro.java:147)
at Visao.cadastro.access$300(cadastro.java:9)
at Visao.cadastro$4.actionPerformed(cadastro.java:96)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Classe Usuario:
package Modelo;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="ROOT.USUARIO")
public class Usuario implements Serializable{

    @Id
    @Column(name = "LOGIN", nullable = false)
    private String login;

    @Column(name = "SENHA", nullable = false)
    private String senha;

    @Column(name = "NOME", nullable = false)
    private String nome;

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

     public Usuario(){}

}

Form Cad_Usuarios
package Visao;

import Controle.ConexaoBD;
import Modelo.ModeloTabela;
import Modelo.Usuario;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import static org.eclipse.persistence.jpa.jpql.parser.Expression.SQL;

public class Cad_Usuarios extends javax.swing.JFrame {
    EntityManagerFactory factory;
    EntityManager manager;

    ConexaoBD conecta = new ConexaoBD();

    public Cad_Usuarios() {
        initComponents();
        preencherTabela("select * from usuarios order by login");
        try{
            factory = Persistence.createEntityManagerFactory("Ponto_DablioPU");
            manager = factory.createEntityManager();
        }catch(Exception e){
            System.exit(1);
        }
    }

    public void limpar(){
        jTLogin.setText(null);
        jTNome.setText(null);
        jPFSenha.setText(null);
    }
    private void jBSalvarActionPerformed(java.awt.event.ActionEvent evt) {

        Usuario user = new Usuario();

        user.setLogin(jTLogin.getText());

        user.setNome(jTNome.getText());

        user.setSenha(jPFSenha.getText());

        manager.getTransaction().begin();

        manager.persist(user);

        manager.getTransaction().commit();

        JOptionPane.showMessageDialog(null, "Usuário Cadastrado com Sucesso!");

        limpar();

    }

    private void jBSairActionPerformed(java.awt.event.ActionEvent evt) {
        dispose();
    }

    private void jBLimparActionPerformed(java.awt.event.ActionEvent evt) {
        limpar();
    }

    public void preencherTabela(String SQL){
        ArrayList dados = new ArrayList();

        String[] Colunas = new String[]{"Login","Senha","Nome"};

        conecta.executaSQL(SQL);
        try{
            conecta.rs.first();
            do{
                dados.add(new Object[]{conecta.rs.getInt("login"),conecta.rs.getString("senha"),conecta.rs.getString("nome")});
            }while(conecta.rs.next());
        }catch (SQLException ex){
            JOptionPane.showMessageDialog(null,"Erro ao preencher o ArrayList! \n ERRO:");
        }

        ModeloTabela modelo = new ModeloTabela(dados, Colunas);
        jTable1.setModel(modelo);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(150);
        jTable1.getColumnModel().getColumn(0).setResizable(false);

        jTable1.getColumnModel().getColumn(1).setPreferredWidth(150);
        jTable1.getColumnModel().getColumn(1).setResizable(false);

        jTable1.getColumnModel().getColumn(2).setPreferredWidth(80);
        jTable1.getColumnModel().getColumn(2).setResizable(false);

        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.setAutoResizeMode(jTable1.AUTO_RESIZE_OFF);

        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    }

Classe ModeloTabela
package Modelo;

import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;

public class ModeloTabela extends AbstractTableModel{
private ArrayList linhas = null;
private String[] colunas = null;

public ModeloTabela(ArrayList lin,String[] col){
    setLinhas(lin);
    setColunas(col);

}

public ArrayList getLinhas(){
    return linhas;
}

public void setLinhas(ArrayList dados){
    linhas = dados;
}

public String []  getColunas(){
    return colunas;
}

public void setColunas(String[] nomes){
    colunas = nomes;
}

public int getColumnCount(){
    return colunas.length;
}

public int getRowCount(){
    return linhas.size();
}

public String getColumnName(int numCol){
    return colunas[numCol];
}

public Object getValueAt(int numLin, int numCol){
    Object[] linha = (Object[])getLinhas().get(numLin);
    return linha[numCol];
}
}

Classe ConexaoBD
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class ConexaoBD {

public Statement stm;
public ResultSet rs;
private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
private String caminho = "jdbc:derby://localhost:1527/ponto_dablio";
private String usuario = "root";
private String senha = "root";
public Connection connection;

public void conexao(){

    try {
        System.setProperty("jdbc.Drivers", driver);
        connection = DriverManager.getConnection(caminho, usuario, senha);
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null,"CONECTADO COM SUCESSO!!\n Erro:" + ex.getMessage());
    }

}

public void executaSQL(String sql) {

   try {
       stm =     connection.createStatement(rs.TYPE_SCROLL_INSENSITIVE,rs.CONCUR_READ_ONLY);
       rs = stm.executeQuery(sql);
       } catch (SQLException ex) {
         JOptionPane.showMessageDialog(null,"ERRO DE EXECUTASQL!!\n ERRO: " + ex.getMessage());
       }
}

public void desconecta(){
    try{
        connection.close();
    }catch (SQLException ex){
        JOptionPane.showMessageDialog(null,"Erro ao fechar conexão!\n Erro:"         + ex.getMessage());
    }
}

}

fiz a alteração mais continua dando erro diz que a tabela "usuarios" não existe, erro:

`Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Visao.Cad_Usuarios.preencherTabela(Cad_Usuarios.java:238)
at Visao.Cad_Usuarios.<init>(Cad_Usuarios.java:32)
at Visao.cadastro.jMUsuariosActionPerformed(cadastro.java:147)
at Visao.cadastro.access$300(cadastro.java:9)
at Visao.cadastro$4.actionPerformed(cadastro.java:96)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

A: Você não iniciou a conexão no método preencheTabela(). Faltou invocar o método conexao() da classe ConexaoBD:
public void preencherTabela(String SQL){
    ArrayList dados = new ArrayList();

    String[] Colunas = new String[]{"Login","Senha","Nome"};

    conecta.conexao();

    conecta.executaSQL(SQL);
    try{
        conecta.rs.first();
        do{
            dados.add(new Object[]{conecta.rs.getInt("login"),conecta.rs.getString("senha"),conecta.rs.getString("nome")});
        }while(conecta.rs.next());
    }catch (SQLException ex){
        JOptionPane.showMessageDialog(null,"Erro ao preencher o ArrayList! \n ERRO:");
    }

...

Quanto ao segundo erro, observando seu model, a tabela se chama "USUARIO" e na query que popula a tabela você está passando como "usuarios". Conserte o nome da tabela na query:
public Cad_Usuarios() {
    initComponents();
    preencherTabela("select * from usuario order by login");
    try{
        factory = Persistence.createEntityManagerFactory("Ponto_DablioPU");
        manager = factory.createEntityManager();
    }catch(Exception e){
        System.exit(1);
    }
}

Leitura recomendada: Como funciona o try-with-resources?


text:
Q: How to configure Microsoft exchange 2007 with evolution I got following error while collection

The Exchange server is not compatible with Exchange Connector.
The server is running Exchange 5.5. Exchange Connector  supports
  Microsoft Exchange 2000 and 2003 only.

My server is hosted on ms exchange 2007
So is there any way out ?

A: EMAIL: you should consider accessing with IMAP and SMTP protocols, if your server have them enabled. I was an happy Evolution user, but in the last months I had a lot of problems with it, and now I'm switching to Thunderbird, that finally is well integrated with Ubuntu, works well with IMAP and seems also faster.
CONTACTS: in Thunderbird, you can add the Exchange Global Address List as a Remote LDAP Address Book; the port 389 should be opened on Exchange server. In Evolution, I was not able to make this working.
CALENDAR: no way in Evolution. In Thunderbird, you can work with the Exchange calendar with Lightning extension and Exchange 2007/2010 Calendar and Tasks Provider, that uses EWS (Exchange Web Services). I just tried and works very well!
ALTERNATIVE: you can also try DavMail, what access to Exchange Web Services and act as a "proxy" for standard apps (IMAP, SMTP, LDAP, Caldav). But, I tried it some time, and I was not satisfied. Too many problems to solve...


text:
Q: Is Looping inside a Task Recommended? Is Looping inside a task really recommended?
example code:
public void doTask(){
    Task.Factory.StartNew(() => {
        do{
           // do tasks here.... call webservice
        }while(true till cancelled)
    });
}

any answers would be great! :)
because it is a case for my webservice calling right now, and the memory consumption goes out of control.
So may I ask, is looping inside a task really good or not recommended at all?
As Requested by SLC, heres the code:
CancellationTokenSource tokenSrc;
Task myTask;
private void btnStart_Click(object sender, EventArgs e)
{
    isPressed = !isPressed;

    if(isPressed)
    {
        tokenSrc = new CancellationTokenSource();
        myTask = Task.Factory.StartNew(() =>
        {
            do{
                checkMatches(tokenSrc.Token);
            }while(tokenSrc.IsCancellationRequested != true);
        }, tokenSrc.Token);
    }
    else {
        try{
            tokenSrc.Cancel();
            // Log to notepad
        }
        catch(Exception err){
           // Log to notepad
        }
        finally {
           if(myTask.IsCanceled || myTask.IsCompleted || myTask.isFaulted) {
               myTask.Dispose();
           }
        }

    }
}

private void checkMatches(CancellationTokenSource token)
{
    try
    {
        if(!token.IsCancellationRequested)
        {
           //Create Endpoint...
           //Bypass ServCertValidation for test purposes
           ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate {return true;});
           using(WebServiceAsmx.SoapClient client = new....)
           {
               client.CheckResp response = client.chkMatch();
               // if's here for the response then put to logs
           }
        }
    }
    catch(Exception err)
    {
        // err.toLogs
    }
}

A: It's perfectly fine to do this, especially if your task runs constantly, for example picking up a message queue.
while (not shutting down)
   get next email to send
   if exists next email to send
      send
   else
      wait for 10 seconds
wend

Ensure that you have a way to get out if you need to cancel it, like you've done with a flag, and you should be fine.
Regarding webservices:
You should have no problem calling the webservice repeatedly, nor should it cause any memory spikes. However, you should make sure your initialisation code is not inside the loop:
BAD
while (notShuttingDown)
   make a new connection
   initialise
   make a call to the service()
wend

GOOD
make a new connection
initialise
while (notShuttingDown)
    make a call to the service
wend

Depending on your webservice it might be more optimal to create a batch operation, for example if your service is HTTP then hitting it repeatedly involves a lot of overhead. A persistent TCP connection might be better because it could be creating and destroying a lot of objects to make the calls.
For example
slow, lots of overhead:
myRecords = { cat, dog, mouse }

foreach record in myRecords
    webservice check record
endforeach

faster:
myRecords = { cat, dog, mouse }
webservice check [myRecords] // array of records is passed instead of one by one

Debugging: The most likely risk is that somehow the task is not being disposed correctly - can you add this to your method to debug?
myTask = Task.Factory.StartNew(() =>
        {
            Console.Writeline("Task Started");
            do{
                checkMatches(tokenSrc.Token);
                Thread.Sleep(10); // Some pause to stop your code from going as fast as it possibly can and putting your CPU usage to 100% (or 100/number of cores%)
            }while(tokenSrc.IsCancellationRequested != true);
            Console.Writeline("Task Stopped");
        }

You might have to change that so it writes to a file or similar depending on if you have a console.
Then run it and make sure that only 1 task is being created.


text:
Q: Is it possible to uniquely solve $\mathbf{A}\vec{x}=\vec{b}$ for $\mathbf{A}$ (given $\vec{b}$ and $\vec{x}$)? If $\mathbf{A}$ is an $n\times n$ matrix, $\vec{x}$ is an $n$-element vector, and $\vec{b}$ is an $n$ element vector, can the equation
$$\mathbf{A}\vec{x}=\vec{b}$$
be solved for $\mathbf{A}$ if I know $\vec{x}$ and $\vec{b}$? I have doubts because vectors (other than $1\times 1$) aren't invertible.
EDIT: x is not the zero vector and I actually want to obtain $A^{-1}$

A: Definitely not uniquely, consider
$$x = \begin{bmatrix}1\\1 \end{bmatrix}\hspace{10px}\text{ and }\hspace{10px} b = \begin{bmatrix}4\\0\end{bmatrix}$$
Then it holds for both
$$\mathbf{A}_1 = \begin{bmatrix}1&3\\2&-2\end{bmatrix}\hspace{10px}\text{ and }\hspace{10px} \mathbf{A}_2 = \begin{bmatrix}1 & 3\\1&-1\end{bmatrix}$$
That
$$\mathbf{A}_1x=b \hspace{10px}\text{ and }\hspace{10px} \mathbf{A}_2x=b$$
and (infinitely many more), and both matrices are invertible.

A: You may view your problem as follows: Write $A$ row-wise is a long vector, i.e.
$$a = \begin{bmatrix}a_{11}\\ \vdots \\ a_{1n}\\ a_{21}\\ \vdots \\ a_{2n}\\ \vdots \\ a_{m1}\\ \vdots \\a_{mn}\end{bmatrix}.$$
Now define a matrix $X\in\mathbb{R}^{m\times {mn}}$ (assuming $x\in\mathbb{R}^{n}$ and $b\in\mathbb{R}^m$)  in block fashion
$$
X = \begin{bmatrix}
x^T & 0 & \dots & \\
0    & x^T & 0 & \\
     &     & \dots & \\
     &     &  & x^T
\end{bmatrix}.
$$
and your problem is in familiar notation: Solve
$$Xa = b$$
for $a$.


text:
Q: how to I clean some time range in R and make them more meaningful? I am still very new at R. When I try to clean some reports I get a column called"funding period" where there are so  many different formats of time ranges for different projects, such as
project 1, 01/01/2018 - 12/31/2020
project 2, Annual
project 3, Every 2 Years
project 4, CY 2018
project 5, FY 18-20
project 6, FY 2018

I intend to split these ranges and instead assign a start date and end date to each project, like this:
project, start_date, end_date
project 1, 01-01-2018, 12-31-2020
project 2, 01-01-2018,12-31-2018
project 3, 01-01-2017, 12-31-2018
project 4, 01-01-2018,12-31-2018
project 5, 01-01-2018, 12-31-2020
project 5, 01-01-2018, 12-31-2018
but I do not know exactly how. Thanks in advance!


text:
Q: How to accept multiple socket connection at Java server I'm trying to implement a client-server pair in Android using standard Java sockets. So far, I've successfully implemented one to one client-server connection. Now, I'm modifying my server side code to accept multiple client connection. I've taken help from here. I'm creating a serverSocket and wait for client connection in an infinite while loop. Once the client side socked is accepted, I run a new thread to handle that client and then again wait for new connection. Unfortunately, the program keeps crashing for some unknown reason! The logcat simply says- "error opening trace file: No such file or directory". The file path is correct (it was working fine in older implementation). Can anyone suggest what am I doing wrong? Is it related to missing manifest permission? Here is what I've done so far:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent launchFileManager = new Intent(getBaseContext(),
            FileChooserActivity.class);
    startActivityForResult(launchFileManager, REQUEST_CODE); //receives files
    //fileArray has been populated here

    Button btn=(Button)findViewById(R.id.dispFilesid);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            initializeServer();
        }
    });
}

private void initializeServer() {
    boolean listening = true;
    try {
        serversocket = new ServerSocket(4444);
    } catch (IOException e) {
        e.printStackTrace();
        Log.d("Listen failed", "Listening to port 4444 failed");
    }
    while (listening) {
        try {
            socket = serversocket.accept();
            Thread Clienttrd = new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        OutputStream myos=socket.getOutputStream();
                        myos.write(filepathNameArray.size()); //send file count
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    if (!fileArray.isEmpty()) {
                        for (int i = 0; i < filepathNameArray.size(); i++){
                            copyFile(fileArray.get(i), fileArray.get(i).getName().toString());
                            //mtv.setText(fileArray.get(i).getName().toString());
                        }
                    }
                }
            });
            Clienttrd.start();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

The intent for FileChooserActivity returns an ArrayList containing a list of file URIs. These URIs are then wrapped around files and written over DataOutputStream of Socket object.
Please help. Any insight would be appreciated! Thanks in advance!

A: Finally solved the problem. This might help others who land on this page in future. The problem: I was using the same thread for accepting and handling the client connection. So, the server could not become free for listening other incoming connections. I wrote a separate ConnectionHandler class for handling client connection:
btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            Thread trd = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        serversocket = new ServerSocket(4444);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.d("Listen failed",
                                "Listening to port 4444 failed");
                    }

                    while (listening) {
                        try {
                            socket = serversocket.accept();
                            Runnable connectionHandler = new ConnectionHandler(
                                    socket, fileArray, filepathNameArray);
                            new Thread(connectionHandler).start();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            });
            trd.start();
        }
    });

ConnectionHandler (This solved my issue):
    public class ConnectionHandler implements Runnable {

    private Socket socket=null;
    private ArrayList<File> fileArray=null;
    ArrayList<String> filepathNameArray=null;

    public ConnectionHandler(Socket socket, ArrayList<File> fileArray, ArrayList<String> filepathNameArray) {
        super();
        this.socket = socket;
        this.fileArray=fileArray;
        this.filepathNameArray=filepathNameArray;
    }
    @Override
    public void run() {
        try {
            OutputStream myos=socket.getOutputStream();
            myos.write(filepathNameArray.size()); //send file count
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (!fileArray.isEmpty()) {
            for (int i = 0; i < filepathNameArray.size(); i++){
                copyFile(fileArray.get(i), fileArray.get(i).getName().toString());
                //mtv.setText(fileArray.get(i).getName().toString());
            }
        }

    }
    private void copyFile(File file, String name) {
        FileInputStream fis;
        long filesize = file.length();
        try {
            fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            @SuppressWarnings("resource")
            DataInputStream dis = new DataInputStream(bis);
            byte[] mybytearray = new byte[16384];
            OutputStream os;
            if (socket != null) {
                os = socket.getOutputStream();
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeUTF(name); // filename is also sent to client
                dos.writeLong(filesize); // file size is also sent to client
                long z = filesize;
                int n = 0;
                while ((z > 0)
                        && (n = dis.read(mybytearray, 0,
                                (int) Math.min(mybytearray.length, z))) != -1) {
                    dos.write(mybytearray, 0, n);
                    dos.flush();
                    z -= n;
                }
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}