text:
Q: React app SPA on S3 AWS while refreshing the page shows 404 page I have a SPA made with React JS on a S3 Bucket and I'm using Cloud Front to work through HTTPS and with a custom domain. When I refresh the page - if I have another Route that is not the BASE_URL (for example domain.com/something), S3 sends me a 404 error.
I also tried redirecting the error page to BASE_URL but it doesn't work, it redirects me to the Http default domain that S3 provides me and again, it gives me an 404 error page.
I don't know if there exists an alternative way to keep the URL without any change (domain.com/page) and avoid the 404 error the way a web server (apache) handles.

A: If you are using CloudFront to host s3 website, the effective way to get rid of 404 on reload of non-index route like www.google.com/about or similar non / is by the following steps:

*

*Go to your CloudFront distribution

*Go to Error Pages

*Create a new error page with the following params:

    HTTP Error Code: 404
    TTL: 0
    Custom Error Response: Yes
    Response Page Path: /index.html
    HTTP Response Code: 200

enjoy
credits going to this article https://gist.github.com/bradwestfall/b5b0e450015dbc9b4e56e5f398df48ff

A: You have two options. Either use CloudFront error page as a catch-all that redirects to / (you mentioned you tried setting an error page but did not detail what you did. This should work). The downside is that it will respond with the HTML page for all not found paths, even for mistyped CSS paths, for example.
The other solution is to use Lambda@Edge to rewrite the origin request path. This is a more customizable solution and you can define which paths you want to redirect to the root.


text:
Q: C# WebSocket - No response from client during handshake I'm attempting to write a C# WebSocket server for an application that interacts upon browser input.
This is the code:
class Program {
 static void Main(string[] args) {
  var listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 42001);
  listener.Start();
  using(var client = listener.AcceptTcpClient())
  using(var stream = client.GetStream())
  using(var reader = new StreamReader(stream))
  using(var writer = new StreamWriter(stream)) {
   while (!reader.EndOfStream) {
    String line = reader.ReadLine();

    if (new Regex("^GET").IsMatch(line)) {
     line = reader.ReadLine();
     if (new Regex("^Sec-WebSocket-Key: ").IsMatch(line)) {
      String key = new Regex("(^Sec-WebSocket-Key\\: |\\r\\n)").Replace(line, "");

      key = Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")));

      writer.WriteLine("HTTP/1.1 101 Switching Protocols");
      writer.WriteLine("Upgrade: websocket");
      writer.WriteLine("Connection: Upgrade");
      writer.WriteLine("Sec-WebSocket-Accept: " + key);
      writer.WriteLine("Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits");
      writer.WriteLine("WebSocket-Origin: http://127.0.0.1");
      writer.WriteLine("WebSocket-Location: ws://localhost:42001/websocket");
      writer.WriteLine("");
     }
    }
   }
  }
  listener.Stop();
 }
}

... and:
        var ws = new WebSocket('ws://localhost:42001/websocket');

        ws.onopen = function() {
            console.log('connected');
        };

        ws.onmessage = function(e) {
            console.log(e.data);
        };

        ws.onerror = function(e) {
            console.log(e);
        };

        ws.onclose = function() {
            console.log("closed");
        };

On execution, the TPCListener successfully accepts the TCPClient and reads the incoming HTTP request. It parses the Key, generates the correct Accept token, but the JS - window native - WebSocket seems to have gone flat out bonkers: it does not answer no matter what it receives.
I would expect it throwing an error upon sending a HTTP/1.1 400 Bad Request, but nothing at all happens. It just goes mute.
Checking out Chrome Dev Tools' Networking tab, I do only see the websocket outgoing GET request, but no incoming packets - is that supposed to happen?
If I forcefully close the application, WebSocket throws this exception:
WebSocket connection to 'ws://localhost:42001/websocket' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET.
What am I missing here? Thank you all in advance.
Also, I'm not using Net.WebSockets because it is available since .NET 4.5, and my application targets systems from Windows 7 to the current build of Windows 10.

A: well... how far does your C# code get? My first bet would be on buffering - you don't flush the writer or stream, so I would expect them to be holding onto data while stuck in the top of the while loop, but frankly it shouldn't be a while loop in the first place - you only get one handshake per socket, not many. You could try adding flushes after the blank line, and you should make sure the Socket itself has buffering disabled (NoDelay = true;) - but: fundamentally this isn't a good way to write a web-socket server. Apart from anything else, the data will cease to be text if the handshake succeeds, so having a TextReader is a very bad thing. Frankly, you should be dealing with raw Socket / byte[] data here, IMO (having implemented this very thing several times).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can the Induction axiom in the Peano arithmetic be replaced by the irrationality of $\sqrt{2}$? This is inspired by the Alexander Shen's post here: https://www.facebook.com/groups/mathpuz/permalink/1058782384297603/ (the post is in Russian, but it is easy Russian, and google translate should work fine).
All proofs of irrationality of $\sqrt{n}$ where $n$ is not a perfect square that I know are using (explicitly of implicitly) the induction axiom of the Peano arithmetic.
Question: Can the induction axiom be replaced by the axiom that $\sqrt{2}$ is irrational?

A: One can prove that $\sqrt{2}$ is irrational and indeed that any particular $\sqrt{n}$ is irrational (if $n$ is not a perfect squares) assuming only the principle of induction for $\Delta_0$ formulas, which is much weaker than the full strength of PA. In this sense, the answer is negative.
The classical proof of the irrationality of $\sqrt{2}$ relies on the fact that every rational number has a representation in lowest terms, and this can be proved with a very weak induction principle, using no unbounded quantifiers. Namely, every $p/q$ has a lowest-term representation, since if this is true for all pairs of numbers whose numerator is smaller than $p$, then it is true for $p/q$, since otherwise we would immediately reduce to a case with a smaller numerator. Thus, we never need to embark on unbounded searches to find the lowest-terms representation of a rational number.
And once one has the lowest-term representations, one can easily prove the classical result that $\sqrt{2}$ is irrational, since otherwise one gets $2q^2=p^2$ and so on, as we all know, ultimately showing that both $p$ and $q$ are even, a contradiction.
For the case of $\sqrt{n}$, for fixed $n$, then one can also prove this using just the existence of lowest-terms representations. Basically, $\sqrt{n}$ is irrational, unless $n$ is a perfect square, since otherwise $nq^2=p^2$ and the prime exponent parities don't work out, as you know.
To prove the universal statement about all such $n$, however, that is, the statement "for all numbers $n$, the square root $\sqrt{n}$ is irrational unless $n$ is a perfect square," it seems that one uses the fundamental theorem of arithmetic, asserting that every number has unique prime factorization, which can be proved using $\Sigma_1$ induction. Namely, if every number smaller than $n$ has a unique factorization into primes, then $n$ also has this, since otherwise one can factor $n$ and reduce to the smaller case. (Here, we have to search a little bit, but not much, to find the code of the factorization.) But once you have the factorization into primes, then again the classical argument shows as above that $\sqrt{n}$ is irrational unless $n$ is a perfect square.
I'm not sure if one can prove the fundamental theorem using only $\Delta_0$-induction. And because we moved up to $\Sigma_1$ induction to get the fundamental theorem, it is conceivable to me that one might be able to have a bizarre model of $\Delta_0$-induction in which the universal claim about all $\sqrt{n}$ was not true, even if it was true in every standard-finite instance, and this would be an interesting answer to your question. I would want the proof theorists to weigh in on this.
Since PA proves the consistency of $\Sigma_0$ induction, and indeed of $\Sigma_n$-induction for any fixed $n$, it follows by the incompleteness theorem (as mentioned in the comment of Dan Piponi) that we cannot axiomatize PA by adding the assertion "$\sqrt{2}$ is irrational" or "$\sqrt{n}$ is irrational for all non-perfect squares $n$" to any finite list of axioms.
The essence of PA is the induction axiom for increasingly difficult arithmetic properties. No bounded amount of complexity for induction, limited to $\Sigma_n$ induction for fixed $n$, is sufficient to capture the full power of PA.


text:
Q: Error in mysql when saving data I was about to save the data in my table but I got this error:

Error: You have an error in your SQL syntax;  check the manual that
  corresponds to your MySQL server version for the  right syntax to use
  near 'div, dep, group, loc, plan, desc, fee, pname, unit, amount,
  amort)  VALUES ('55' at line 1

Here is my code:
$sql=
"INSERT INTO account
       (accnum, mobile, status, assignee,
          user, position, entitlement,
          org, div, dep, group,
          loc, plan, desc, fee,
          pname, unit,
          amount, amort)
VALUES
       ('$_POST[accNum]','$_POST[mobNum]','$_POST[stat]','$_POST[assignee]',
        '$_SESSION[userType]','$_SESSION[position]','$_SESSION[entitlement]',
        '$_SESSION[orga]','$_SESSION[divi]','$_SESSION[dept]','$_SESSION[group]',
        '$_SESSION[farm]','$_SESSION[planType]','$_SESSION[promo]',
        '$_SESSION[monthFee]','$_SESSION[phoneType]','$_SESSION[unit]',
        '$_SESSION[amount]','$_SESSION[amort]')";

A: Because div, group, desc are MySQL keyword.

A: Use backticks
$sql="INSERT INTO account(`accnum`, `mobile`, `status`, `assignee`, `user`, `position`, `ntitlement`, `org`, `div`, `dep`, `group`, `loc`, `plan`, `desc`, `fee`, `pname`, `unit`, `amount`, `amort`)
VALUES
('$_POST[accNum]','$_POST[mobNum]','$_POST[stat]','$_POST[assignee]','$_SESSION[userType]','$_SESSION[position]','$_SESSION[entitlement]','$_SESSION[orga]','$_SESSION[divi]','$_SESSION[dept]','$_SESSION[group]','$_SESSION[farm]','$_SESSION[planType]','$_SESSION[promo]','$_SESSION[monthFee]','$_SESSION[phoneType]','$_SESSION[unit]','$_SESSION[amount]','$_SESSION[amort]')";


text:
Q: Django, multiple ModelAdmin for one Model I have Django 1.7.9 and python 2.7. I need multiple ModelAdmin
for one Model. One of them is standart and others with some
constant values. For example, I have model Item with foreign key
Categiries. I need model admin to create Item with constant
value for every category. How can I do it? Is it possible?)

A: Create a proxy model - that will allow you to register it in admin as a different model, but it will be still the same:
class MyModel(models.Model):
    pass

class MyModelAgain(MyModel):
    class Meta:
        proxy = True

admin.py:
admin.site.register(MyModel)
admin.site.register(MyModelAgain)

A: Proxy model approach can make you some troubles with permissions (proxy model has their own permissions).
You can serve second ModelAdmin manually by URL like /admin/<app>/<model>/<id>/alternate_view/:
class YourModelAdmin(ModelAdmin):
    def get_urls(self):
        alternate_admin = SecondModelAdmin(self.model, self.admin_site)

        from django.conf.urls import patterns, url
        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)

            return update_wrapper(wrapper, view)

        urlpatterns = super(YourModelAdmin, self).get_urls()
        urls = patterns('',url(r'^(.+)/alternate_view/$', wrap(alternate_admin.change_view), name='svod_analisys'))
        return urls + urlpatterns


text:
Q: SVN Server pre-commit works but start-commit hook not working I have an existing pre-commit hook working fine however when I use start-commit hook I get "Commit blocked by start-commit hook (exit code 255) with no output.)
The start-commit looks like this...

#!/bin/sh
REPOS="$1"
USER="$2"
grep $USER /var/svn/repos/testrepo/hooks/owasp_users.txt
GREP_STATUS=$?
if [ $GREP_STATUS -ne 0 ]
then
    echo  $GREP_STATUS 1>&2
    echo  $REPOS-PATH 1>&2
    echo  $USER 1>&2
    exit 1
fi
exit 0

The working pre-commit looks like this...

#!/bin/sh

REPOS="$1"
TXN="$2"

SVNLOOK=/usr/bin/svnlook
$SVNLOOK log -t "$TXN" "$REPOS" | grep "[a-zA-Z0-9]" > /dev/null

GREP_STATUS=$?
if [ $GREP_STATUS -ne 0 ]
then
    echo "Your commit has been blocked because you didn't add a log message." 1>&2
    echo "Please write a log message describing the purpose of your changes and" 1>&2
    echo "then try committing again. -- Thank you" 1>&2
    exit 1
fi
exit 0

The file has execute permissions and no matter the code in start-commit I get the 255 error.
I can get past with just the first line #!/bin/sh but add even a simple line return and the 255 error returns.

A: I missed converting DOS line endings while editing the hooks, a quick dos2unix fixed the issue. It acts very weird due to the different ways bash and hooks works with CRLF added to the fact that you can't see stdout this wasted hours of my day.


text:
Q: SSRS : the operation has timed out I try to execute report viewer but does not work. So this is an error log message from ssrs log file.
ERROR:
Reporting Services error Microsoft.ReportingServices.Diagnostics.Utilities.ClosingRegisteredStreamException:
An error occurred closing a registered stream. --->
Microsoft.ReportingServices.Diagnostics.Utilities.ReportServerHttpRuntimeClientDisconnectionException:
A client has disconnected from the Report Server Web service application domain
ReportServer_MSSQLSERVER_0-4-131683910836410373.
No corrective action is required. An error code has been submitted to ASP.NET to release the connection.
The error code is 800708CA. ---> System.Runtime.InteropServices.COMException: This network connection does not exist. (Exception from HRESULT: 0x800708CA)

A: In the web config  set the http run time as
        <httpRuntime maxRequestLength="2147483647" executionTimeout = "10800"/>


text:
Q: JQueryMobile dialog shows twice because of a postback I have an asp.net page with a timer embedded in an UpdatePanel (UpdateMode="Conditional", ChildrenAsTriggers="false"). The timer is responsible for updating some components of that page every few seconds.
There are also some HyperLink controls on the page and they open a JQueryMobile dialog when clicked (data-rel="dialog"). The problem is that the timer i mentioned causes postback every few seconds. So when a dialog is opened and then closed, the first such postback after then causes the dialog to open once again.
Using the rel="external" as another attribute of the HyperLinks I mentioned solves the problem, but this is no solution for me. This causes full redirection to the dialog page instead of showing it using AJAX (as if on top of current page).
My idea was to stop the timer when any hyperlink is clicked. This solves the problem, but I have no idea how to start the timer again when the dialog closes. Is it possible to detect when a JQueryMobile dialog is closed? I know, this sounds stupid, but I can't come up with a better idea. Will you help me, please?
So basically, I don't want the JQueryMobile dialog page to show up for the second time after a timer tick. Could you please advise me how to achieve that?

A: jQuery Mobile with asp.net Web Forms and an UpdatePannel? This just sounds like a horrible combination.
jQuery Mobile and Web Forms fundamentally don't work well together. The specific issue that Web Forms requires a single <form /> element that wraps all controls (and most content). jQuery Mobile attempts to build up the DOM with "virtual" pages via ajax loading. This breaks the PostBack model by submitting the entire form instead of the individual form found within each page template. Now throw UpdatePanels in there...
Your only hope is go exclusively with Single page templates and to disable all ajax loading data-ajax="false" on both links and forms. And just say no to UpdatePanels.
asp.net MVC would give you much greater control over these issues.


text:
Q: Performing class method directly on the output of a function that returns data in that class (C++) I'm brand new to all of this, and I'm sure I'm not quite phrasing things properly - sorry about any dumb questions and mistakes, and thanks for bearing with me! :)
That aside, here's my situation: I've created a class, a member function for that class, and another (non-member) function that returns values in that class. I know that everything works the way it's supposed to on its own - the member function returns the expected values when I use it on normal objects, and the other function returns the objects that it's supposed to - but for some reason I don't seem to get anything at all when I use them this way:
functionReturningMyObject(parameters).memberFunction(other parameters);

Is there no way to get a method to act directly on an object that is the output of another function in this way? Or does my problem lie elsewhere?
EDIT: here is my attempt at a "minimal reproducible example," as requested:
Main.cpp
#include <iostream>
#include <string>
#include "mre.hpp"

//Here are some objects
Class first (1, 'A');
Class second (1, 'B');
Class third (2, 'A');
Class fourth (2, 'D');

//Here is the function returning objects in the class
Class FindMatchingObject(int matchNumber, char matchLetter) {
  if ((first.getNumber()==matchNumber)&&(first.getLetter()==matchLetter)) {
    return first;
  }
  else if ((second.getNumber()==matchNumber)&&(second.getLetter()==matchLetter)) {
    return second;
  }
  else if ((third.getNumber()==matchNumber)&&(third.getLetter()==matchLetter)) {
    return third;
  }
  else if ((fourth.getNumber()==matchNumber)&&(fourth.getLetter()==matchLetter)) {
    return fourth;
  }
}

int main() {

   //User puts in a string consisting of: first, the old number-letter pair to identify the object they'd like to change, then second, the new number-letter pair that they'd like to change it to. In this case, I put in '1B8H' to pick 'second' and change its values to 8 and H.
  std::string userInput;
  std::cin >> userInput;
  int oldUserNumber = userInput[0] - 48;
  char oldUserLetter = userInput[1];
  int newUserNumber = userInput[2] - 48;
  char newUserLetter = userInput[3];

  //Here we see that, indeed, 'second' is being identified by the function.
  std::cout << FindMatchingObject(oldUserNumber, oldUserLetter).getNumber() << FindMatchingObject(oldUserNumber, oldUserLetter).getLetter() << "\n";

  // Here we see that, indeed, the change() method can take an object and set new values for it.
  third.change(7, 'G');
  std::cout << third.getNumber() << third.getLetter() << "\n";

  // But here, after trying to use change() on 'second' directly through the FindMatchingObject() function, the values of the object remain unchanged afterwards.
  FindMatchingObject(oldUserNumber, oldUserLetter).change(newUserNumber, newUserLetter);
  std::cout << second.getNumber() << second.getLetter() << "\n";
}

mre.hpp
#include <iostream>
#include <string>

class Class {
  char letter;
  int number;

  public:
  Class(int number0, char letter0);
  void change(int newNumber, char newLetter);
  int getNumber();
  char getLetter();
};

mre.cpp
#include <iostream>
#include <string>
#include "mre.hpp"

Class::Class(int number0, char letter0) {
  number=number0;
  letter=letter0;
}

void Class::change(int newNumber, char newLetter) {
  number=newNumber;
  letter=newLetter;
}

int Class::getNumber() {
  return number;
}

char Class::getLetter() {
  return letter;
}

Also, I know it's kind of gross having all of that stuff above the main() function, but for some reason I got compiling errors until I put them there.

A: Your FindMatchingObject() function returns a Class object by value, thus returning a copy of the object. So, you are calling change() on a copy of second, not on second itself.  That is why second doesn't change, even though second was returned.
To fix that, your function would have to return a Class object by reference or pointer instead.
However, do note that your function has undefined behavior if no matching object is found, as no return gets executed in that case. Your compiler should be warning you about that.  You would need to either return a default object, or throw an exception, or return nullptr if you change the function to return a Class* pointer.


text:
Q: Read contents of the pdf using vim How can we read contents of the pdf file using vim command in the terminal?
I have tried using pdftk by uncompressing it but still its not working for me. Is there any other way to decrypt or decode the pdf so that we can read by the terminal in any Linux flavour using vim.

A: If you want to read the pdf as text you can try the pdftotext command, though it won't always be beautiful. If you'd like vim to open pdf files in a pdf reader you can use something in your .vimrc like
au BufRead *.pdf sil exe "!xdg-open " . shellescape(expand("%:p")) | bd | let &ft=&ft | redraw!

A: This question is more or less a duplicate of this one.
However, following the answers of @Conner and @Eric, the pdftotext utility is a recommended approach if you are only interested in the text content.
A possible approach to pdftotext can be found e.g. here.
There also exists a rather new Vim plugin to simplify these steps.
This plugin can be found here or here
You might also write some ftplugin acting as a preprocessor to extract the text of a given pdf. Nevertheless, you won"t be able to change anything in the pdf with the proposed tools.

A: Some pdf text contents can be extracted with pdf2txt, then fed to vim. Of course, you will lose most of the formatting, graphics, etc.


text:
Q: Centring in three levels multilevel models with cross-level interaction I am relatively new to multi-level models subject and find it challenging to connect theory to modelling.
My interest is to examine the moderation influence of green space (at level 3) on the relationship between SES variables at the individual level 1 (education)  and the SES variables at the household level (household wealth) with the probability of chronic illness.
A hypothesis is: individuals with lower SES and individuals living in lower SES households who live in areas with better greenspace have better health compared to their counterparts who live in an area with lower greenspace.
My problem is that I have three possibilities to test this:
(1) Raw scores or (grand mean centring which have similar interpretation)
$$y_{ijk}= γ_{000}+γ_{100} x_{ijk} +γ_{010} h_{j_k} +γ_{001} z_k+γ_{101} (x_{ijk}* z_k)+γ_{011} (h_{jk}*z_k)+V_{10k} x_{ijk}+V_{01k} h_{jk}+V_{00k}+ U _{0jk}+ε_{ijk} $$
The argument by Raudenbush, Enders 2007 and followed by a lot of others is that (1) does not lead to pure estimates because the estimates are composed of a within and a between components, whereby cluster mean centring rule out the between components and leads to pure within estimates which are preferable in cross-level interactions.
(2) Cluster mean centring (hierarchically)
$$  y_{ijk} = γ_{000} + γ_{100} (x_{ijk}-x ̅_{jk})+ γ_{010}(h_{jk}- h ̅_k)+γ_{001} (z_k-z ̅_.) + γ_{101} (x_{ijk}-x ̅_{jk})*(z_k-z ̅_.))+γ_{011} ((h_{jk}- h ̅_k)*(z_k-z ̅_.))+V_{10k} x_{ijk}+V_{01k} h_{jk}+V_{00k}+U _{0jk}+ε_{ijk} $$
But because my interest is in the moderation effect of green space at level 3 and that individuals and households usually share the same SES, there is another possibility for centring at level 3: (relative SES position in the area)
(3) Cluster mean centring (only at level 3)
$$ y_{ijk}= γ_{000} +γ_{100} (x_{ijk}-x ̅_k)+γ_{010} (h_{jk}- h ̅_k)+γ_{001} (z_k-z ̅_.)+
γ_{101} ((x_{ijk}-x ̅_k)* (z_k-z ̅_.))+γ_{011} ((h_{jk}- h ̅_k)*(z_k-z ̅_.))+V_{10k} x_{ijk}+V_{01k} h_{jk}+V_{00k}+U _{0jk}+ε_{ijk} $$
These three equations produce different models, my confusion is which one makes more sense and serves better answering my question/hypothesis.
By the way, Kelley et al,.2017 say that (2 and 3) is nonsense and just use 1. Which confused me even more.
I appreciate your advice on which model best serves my purpose.
Thanks

A: The best option appeared to be centring around the clusters means as in (2) but with the addition of the cluster means to the equation to control for their effects else the cross-level interaction is difficult to interpret. Such a model is called a contextual model.
For reference check out this article which says that Kelley's article is just crap


text:
Q: Get binary content of char variable in C as it is Is there a way to print binary content of char variable as it is. Means not to convert the variable in to ASCII.
For example,
char c =  1000001;
printf("%c\n", c);

This print
A
But I want to display without convert it to ascii something like below one.
1000001

Is that possible ?

A: you can do it by as follows
A char in C is guaranteed to be 1 byte, so loop to 8.
Within each iteration, mask off the highest order bit.
Once you have it, just print it to standard output.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(int argc,char *argv[])
{
      char c =  1000001;
      int i;
      for (i = 0; i < 8; i++) {
          printf("%d", !!((c << i) & 0x80));
      }
      printf("\n");

      return 0;

 }

or you can also use itoa library function as follows
char c = 'C'
char output[9];
itoa(c, output, 2);
printf("%s\n", output);

One more solution also
char c = 'C';
int i = 0;
    for (i = 7; i >= 0; --i)
    {
        putchar( (c & (1 << i)) ? '1' : '0' );
    }
    putchar('\n');

A: can try looping.
scan your character,say 'A'.
Get its ASCII(65).
Divide 65 by 2 till quotient is zero, store remainder in array/dynmalloc .
read the array reverse
65/2 32 1
32/2 16 0
16/2 8  0
8/2 4 0
4/2 2 0
2/2 1 0
1/2 0 1


text:
Q: First record which meets GROUP BY and HAVING clauses I have a SQL Server query which takes data from Oracle 8i server using linked server connection. My question here is completely on Oracle SQL.
There is a StyleSizes table.  One style can have one or more sizes associated with it. I need to find any one Style_CD which has more than one Size_CD.  This can be achieved by GROUP BY and HAVING. But I need only one such style. The volume of the table is so big that I cannot wait till the query execution is complete – so I need only one style.
How to get only one record quickly after applying GROUP BY and HAVING clauses in Oracle?
SELECT STYLE_CD
FROM OPENQUERY(LinkedORAServer,
   'SELECT STYLE_CD
   FROM DA.StyleSize M
   GROUP BY STYLE_CD
   HAVING COUNT(SIZE_CD) > 1
    ')

FURTHER READING

*

*Ask Tom - On ROWNUM and Limiting Results

*Limit - Comparison of different SQL implementations

*How do I limit the number of rows returned by an Oracle query after ordering?

*Row Limiting Clause for Top-N Queries in Oracle Database 12c Release 1 (12.1)

*SQL Server - Pagination with OFFSET / FETCH : A better way

A: You should use ROWNUM which is similar to MySQL limit and SQL-SERVER top :
SELECT STYLE_CD
FROM OPENQUERY(LinkedORAServer,
   'SELECT STYLE_CD FROM(SELECT STYLE_CD
                         FROM DA.StyleSize M
                         GROUP BY STYLE_CD
                         HAVING COUNT(SIZE_CD) > 1)
    WHERE rownum = 1
    ')

A: SELECT * FROM (SELECT SIZE_CD, COUNT(STYLE_CD) OVER (PARTITION BY STYLE_CD) CNT FROM STYLESIZE) WHERE CNT > 1

A: If you want one style that has more than one size, quickly, then you can use exists:
select m.*
from da.stylesize m
where exists (select 1 from da.stylesize m2 where m2.style_cd = m.style_cd and m2.size_cd <> m.size_cd) and
      rownum = 1;

Then, you want to be sure you have an index on da.stylesize(style_cd, size_cd).
With this query, you don't even need to do the aggregation, which should be a big savings.

A: SELECT STYLE_CD
FROM OPENQUERY(LinkedORAServer,
   'select VAL from (
select VAL,COUNT(*) from SANDEEP24FEB2016_2 group by VAL having COUNT(*)>1
) where rownum=1
    ') ;


text:
Q: Showing any function in $L^p(\mathbb{R}^n)$ is a tempered function. Definition. Let $f$ be a measurable function defined on $\mathbb{R}^n$ such that $\int_{\mathbb{R}}\frac{|f(x)|}{(1+|x|)^N}dx<\infty$ for some positive integer $N$. Then we call $f$ a tempered function.
Why any $f\in L^p(\mathbb{R}^n)$ is a tempered function?
I imagine that it should start like this,
$\int_{\mathbb{R}^n}\frac{|f(x)|}{(1+|x|)^N}dx=\int_{\mathbb{R}^n}\frac{|f(x)|^p|f(x)|^{1-p}}{(1+|x|)^N}dx$
but I do not know how to continue

A: For $p=1$ the claim is obvious (choose for example $N=1$).
So let $p>1$ and $q=\frac{p}{p-1}$.
Note that $q>1$.
With the Hölder inequality we get
\begin{align}
\int_{\mathbb{R}^n}\frac{|f(x)|}{(1+|x|)^N}\mathrm dx
&=\left\|\frac{f(x)}{(1+|x|)^N}\right\|_{L^1} \\
&\leq\|f\|_{L^p}\left\|\frac{1}{(1+|x|)^N}\right\|_{L^q}
\end{align}
Moreover we have
\begin{align}
\left\|\frac{1}{(1+|x|)^N}\right\|_{L^q}^q
&=\int_{\mathbb R^n}\left(\frac{1}{1+|x|}\right)^{Nq}\mathrm dx \\
&=\int_0^\infty\int_{\partial B_r(0)}\frac{1}{(1+r)^{Nq}}\mathrm dr \\
&=\int_0^\infty\frac{\omega_{n-1} r^{n-1}}{(1+r)^{Nq}}\mathrm dr \\
&\leq\int_0^\infty\frac{\omega_{n-1} r^{n-1}}{(1+r)^{2n}}\mathrm dr \\
&\leq\int_0^\infty\frac{\omega_{n-1}}{(1+r)^2}\mathrm dr \\
&=\omega_{n-1}<\infty
\end{align}
where $\omega_{n-1}$ is the surface area of the unit $n-1$-sphere viewed as a subset of $\mathbb R^n$
The latter of course only holds if we choose $N$ large enough, but we are free to do so to show that $f$ is a tempered function (note that $N=2n$ would be sufficient).
Hence $\int_{\mathbb{R}^n}\frac{|f(x)|}{(1+|x|)^N}\mathrm dx<\infty$ for some $N\in\mathbb N$, so $f$ is a tempered function.


text:
Q: More than two values in array_combine string I am trying to add an extra array in to my array_combine function and I get the following error when more than two values have been added:

[24-Oct-2017 12:18:18 UTC] PHP Warning: Invalid argument supplied for foreach() in /manage/add-users-to-courses.php on line 61

My working code:
$stmtcd = "SELECT id, course_title FROM distributor_course_settings WHERE distributor = ? AND active = 'Y' AND price NOT LIKE '0.00'";
$stmtcd = $conn->prepare($stmtcd);
$stmtcd->bind_param('s', $distributor);
$stmtcd->execute();
$stmtcd->bind_result($id, $course_title);

while($stmtcd->fetch()) {
    $course_id_array[] = $id;
    $course_title_array[] = $course_title;
}

<?php
    foreach (array_combine($course_id_array, $course_title_array) as $course_id => $course_title) {
        echo '
';
        echo '
' . $course_title . ' - ' . $price . '
	';
        echo '
';

        foreach (array_combine($user_id_array, $username_array) as $user_id => $username) {
            echo '
';
            echo '<input type="checkbox" id="" name="" value="' . $course_id . ',' . $course_title . ',' . $price . ',' . $user_id . ',' . $username . '"> ' . $username . '	';
            echo '
';
        }
    }
?>

Whenever I try to add 'price' to the SELECT statement and also in to the for each statement, I get the above error.
Why is this? Is there a limit to values allowed in a foreach/array_combine?

A: Follow good coding standards and best practices
While "best practices" are wide ranging, overwhelmingly numerous, and filled with differing opinions, they're important and usually all agree. In your case, you should initialize variables (see Example1).
PHP array_combine expects Array
More than expects, array_combine requires that all arguments are arrays. Thus, initialize those variables as empty arrays.
$course_id_array = [];
$course_title_array = [];
$user_id_array = [];
$username_array = [];

while($stmtcd->fetch()) {
    $course_id_array[] = $id;
    $course_title_array[] = $course_title;
}

Don't break your data.
In your code, you separate the data's ID and the data into different arrays, only to combine them again in order to loop through them. Create the array properly to begin with, and your code will be much cleaner.
$courses = [];
while($stmtcd->fetch()) {
    $courses[$id] = $course_title;
}

foreach($courses as $course_id => $course_title) {
    // your code here
}

Use objects to make life easier
While building everything procedural is simpler at first, OOP will make life easier.
// build an object for your Course
Class Course
{
    public $id, $title, $price;

    public function __construct($title, $id = 0)
    {
        $this->id = $id;
        $this->title = $title;
    }
}

// Build an object for your db conn and queries
// Note: in a larger app, DB conn, and specific SQL commands, should be built in different objects, Like:
//     $dbo = new DBO($conn);
//     $courseTools = new CourseDBTools($dbo);
//     $course = $courseTools->getOneMatchingCourse([args]);
Class DBO
{
    private $conn;

    public function __construct($conn)
    {
        $this->conn = $conn;
    }

    public function getCoursesByDistrubutor($distributor)
    {
        $title = '';
        $id = 0;
        $price = 99;
        $stmtcd = "SELECT id, course_title, price FROM distributor_course_settings WHERE distributor = ? AND active = 'Y' AND price NOT LIKE '0.00'";
        $stmtcd = $this->conn->prepare($stmtcd);
        $stmtcd->bind_param('s', $distributor);
        $stmtcd->execute();
        $stmtcd->bind_result($id, $title, $price);

        while($stmtcd->fetch()) {
            $course = new Course($title, $id);
            $course->price = $price;
            yield $course;
        }
    }
}

// Then your actual code becomes clean and simple
$distributor = 'ABC';
$conn = null; //set it,
$dbo = new DBO($conn);

foreach ($dbo->getCoursesByDistrubutor($distributor) as $course) {
    echo $course->title . ' - ' . $course->price;
}

A: Keep it simpler.  Change the two loops to these two:
while($stmtcd->fetch()) {
    $titles[$id] = $course_title;
}
foreach ($titles as $course_id => $course_title) { ... }

If you later need only the ids or only the titles (without the ids), see array_keys($title) and array_values($titles).


text:
Q: Suppose that f : X → ]−∞, +∞] is convex and proper, that x ̄ ∈ dom f Suppose that $f : X → ]−∞, +∞]$ is convex and proper, that $x ̄ ∈ dom f$ , and that $λ > 0.$ Show that
$$∂(λf)(x ̄) = λ∂f(x ̄).$$
I am looking for a little help with this one. I am a bit unclear as to what is meant by 'proper'. Also I have the property $$v∈∂f(x ̄) ⇔ (∀x∈X)f(x ̄)+⟨v,x−x ̄⟩≤f(x),$$ but I'm not sure how this helps me.
Any hints or suggestions is greatly appreciated.

A: Let me briefly sketch the proof. Take $v \in \lambda \, \partial f(\bar x)$. Write down the definition of $v/\lambda \in \partial f(\bar x)$. Manipulate the expression to find $v \in \partial(\lambda f)(\bar x)$. Conclude.


text:
Q: How to display php output into a specific div? I am trying to display an output into a specific div without placing the php code into the same section (see below example). How do I do this from elsewhere e.g. another page using php/AJAX?

flex-container 1

full card

 <?php
  if(isset($_GET['submit-search'])){
    $search = mysqli_real_escape_string($conn, $_GET['search']);
    $sql = "SELECT * FROM builders2000 WHERE Suburb LIKE '%$search%' OR Postcode LIKE '%$search%' OR Trading_name LIKE '%$search%' OR Categories LIKE '%$search%' OR State LIKE '%$search%' OR Address LIKE '%$search%'";

    $results = mysqli_query($conn, $sql);
    $queryResults = mysqli_num_rows($results);

    echo "There are '.$queryResults.' results.";

    if($queryResults > 0) {
      while($rows = mysqli_fetch_assoc($results)) {

        $name = $rows['Trading_Name'];
        $address = $rows['Address'];
        $suburb = $rows['Suburb'];
        $state = $rows['State'];
        $postcode = $rows['Postcode'];
        $phone = $rows['Phone'];
        $email = $rows['Email'];
        $website = $rows['Website'];
        $categories = $rows['Categories'];

    echo "

$name

$address $suburb $state $postcode

$categories

";
        } } else {  echo "There are no results matching your search";  }}
 ?>

A: Hi here is a simple example but I think is quite easy to understand the approach:
The index.php file:
<form method="post" id="myformid">
  Name :<input type="text" id="name" name="name">
  <input type="submit"  value="Test">
  </form>

Here is a simple form and div, this div is where you are going to append the data.
The javascript:
function _ajax(action,data){
      return $.ajax({
        url: 'request.php',
        type: 'POST',
        dataType: 'JSON',
        data: {action: action, data: data}
      })
    }
    var result;
    //your form submit event
    $("#myformid").on('submit', function(event) {
      //prevent post
      event.preventDefault();
      //validate that name is not empty
      if ($("name").val() != "") {
        //parameters INS is insert data is the array of data yous end to the server
        var action = 'INS';
        var data = {
          name: $("#name").val()
        };
        console.log(data);
        //run the function and done handle the function
        _ajax(action,data)
        .done(function(response){
          console.log(response);
          //anppend name to the div
          $("#myDiv").append("
"+response.name+"
");
        });
      }
    });

and finally the request.php file:
<?php
//includes and session  start here
//validate that request parameters are set
if (isset($_POST["action"]) && isset($_POST["data"])) {
  //getters
$action = $_POST["action"];
$data = $_POST["data"];
//switch to handle the action to perfom maybe you want to update with the form too ?
switch ($action) {
  case 'INS':
    // database insert  here..
    //return a json object
    echo json_encode(array("name"=>$data["name"]));
    break;
}
}
 ?>

Result:

If you want to replace the data displayed inside the div just empty it before the data is appended to it =)
Hope it helps


text:
Q: microsoft report viewer print button missing in mozilla I am developing a web application and using using rdlc reports. when i preview report in report viewer print button missing in mozilla, it is displayed in IE but prb with mozilla. can you please let me know any plugin or something for mozilla.

A: Print button is an ActiveX control and works in IE 9 (or earlier) only. You can find solution in those topics:
The print button doesn't appear in firefox
SQL Reporting Services - Print Button not shown in Mozilla


text:
Q: Use line range within a fold Is it possible to restrict line range to within current fold? Say I want to do a substitution from second line through end of fold i.e.
2,$s/str/replace/

but I want it to apply to current fold only.

A: There are motions for jumping to the beginning of the current fold (:help [z) or to its end (:help ]z) but they don't have equivalent marks. If that were the case, one could do this with the imaginary '* mark:
:2,'*s/str/replace/

but that mark doesn't exist so it won't work.
One way to achieve what you want would be to visually select the area:
]zv[zj

and then do your substitution on the visual selection:
:'<,'>s/str/replace/

with the range '<,'> automatically inserted for you.
Or you could go the "grok vi" way and place manual marks:
]zme[zmb

before using them in your substitution:
:'b+,'es/str/replace/

but it seems less optimal than the "visual way".
Another solution would be to close the fold:
zc

and do the substitution on the closed fold, with confirmation so that you can skip the substitutions that occur on the first line:
:s/str/replace/c

So there are two approaches, here: one where care is put into defining the exact range and one where care is put into not substituting the wrong thing.


text:
Q: How can I count the occurrence of a key based on array value I have this array
[furnitures] => Array
(
    [0] => Array
    (
        [fi_id] => 8
        [price] => 15.00
    )
    [1] => Array
    (
        [fi_id] => 8
        [price] => 15.00
    )
    [2] => Array
    (
        [fi_id] => 7
        [price] => 15.00
    )
    [3] => Array
    (
        [fi_id] => 7
        [price] => 15.00
    )
    [4] => Array
    (
        [fi_id] => 8
        [price] => 15.00
    )
    [5] => Array
    (
        [fi_id] => 9
        [price] => 15.00
    )
)

I want unique fi_id from it and I also want to count the occurence from it. How many times is this being repreated. Does PHP has any built in function for it?
Like unique items are 7,8,9 and 7 is repreated 2 times, 8 is repreated 3 times and 9 is repreated 1 time.

A: you can try this:
//Here you get unique Ids
$uniqueFiIdList = array_unique(array_map(function ($el)
{
   return $el['fi_id'];
}, $furnitures));

//Here you get the total unique occurences
$totalUniqueFiId = count($furnitures) - count($uniqueFiIdList);


text:
Q: TopComponent resizing behavior At the moment, when you try to manually resize a TopComponent, it will show a black line showing the future size of the TopComponent.

I'd like to know what is the JComponent behind this black line? And how can i access it?

EDIT
The first part of my question was answered. The component shown in the attached picture is a JSplitPane.
Right now, i'd like to be able to access it (i.e get the instance of the JSplitPane's used for TopComponent resizing in the netbeans platform.

A: *

*there is JSplitPane,

*but not sure if Netbeans is compiled in Java (in compare with Eclipse)
EDIT I'd like to add a listener on it.

*add PropertyChangeListener to the JSplitPane,

*there are a few usefull methods for if (propertyName.equals(JSplitPane.XxxXxx))

*notice for Nested JSplitPane, have to add listener for each of JSplitPanes separatelly

*for example
.
import java.awt.Dimension;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;

public class JSplitPaneToy {

    public static void main(String[] args) {
        JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, makePanel(), makePanel());
        JPanel pnl = new JPanel();
        pnl.setLayout(new GridLayout(4, 1, 10, 10));
        pnl.add(makePanel());
        pnl.add(makePanel());
        pnl.add(makePanel());
        pnl.add(makePanel());
        PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {

            public void propertyChange(PropertyChangeEvent changeEvent) {
                JSplitPane sourceSplitPane = (JSplitPane) changeEvent.getSource();
                String propertyName = changeEvent.getPropertyName();
                if (propertyName.equals(JSplitPane.LAST_DIVIDER_LOCATION_PROPERTY)) {
                    int current = sourceSplitPane.getDividerLocation();
                    System.out.println("Current: " + current);
                    Integer last = (Integer) changeEvent.getNewValue();
                    System.out.println("Last: " + last);
                    Integer priorLast = (Integer) changeEvent.getOldValue();
                    System.out.println("Prior last: " + priorLast);
                }else if (propertyName.equals(JSplitPane.RESIZE_WEIGHT_PROPERTY)) {
                    int current = sourceSplitPane.getDividerLocation();
                    System.out.println("Current: " + current);
                    Integer last = (Integer) changeEvent.getNewValue();
                    System.out.println("Last: " + last);
                    Integer priorLast = (Integer) changeEvent.getOldValue();
                    System.out.println("Prior last: " + priorLast);
                }
            }
        };
        sp.addPropertyChangeListener(propertyChangeListener);
        JFrame frame = new JFrame("JSplitPane Toy");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(0, 2, 10, 10));
        frame.add(sp);
        frame.add(pnl);
        frame.pack();
        frame.setVisible(true);
    }

    private static JScrollPane makePanel() {
        JScrollPane pane = new JScrollPane(new JTable(
                new Object[][]{{0, 1, 2}, {1, 2, 3}, {2, 3, 4}}, new Object[]{1, 2, 3}));
        pane.setPreferredSize(new Dimension(200, 100));
        return pane;
    }
}


text:
Q: Подскажите на каком движке сделать CRM Поставили задачу создания CRM по типу, прием просмотр заказов. Заказы будут приходить с одностраничников. Есть готовые crm или луче взять движок и пилить под свои нужды (какой движок луче использовать под такие нужды). Буду благодарен за любую информацию.

A: Обычно такие CRM на php пишут на своем* движке, то есть такие crm как vtiger crm и sugarcrm имеют свои "движки", но ничто не мешает на их основе создать свою crm. То есть вы можете создать свою CRM на базе любой другой open source crm системы. Рекомендую обратить внимание на SugarCRM и VTigerCRM ниже ссылки. Эти CRM с открытым кодом. Также если писать код с ноля можно использовать фреймворки такие как Symfony или Laravel (и другие). Ниже ссылки.
http://www.sugarcrm.com/download
http://www.vtiger.ru
http://www.symfony-project.org
https://laravel.com


text:
Q: SharePoint 2013 - Allow anonymous search results I am using SharePoint 2013 OOTB, and can see that anonymous access to view the "entire site" is checked under site settings -> site permissions for anonymous users.
Why else would my search results web part not be displaying the same results on the page, that is shows when I do log in? It shows nothing when I am logged out.
I simply added the SharePoint search result web part from the ribbon, to my publishing page and gave it a custom search query.
Thanks for any advice on this

A: Could you try few steps give below?

*

*Reset your search index and then do a full crawl. Click below to know how to reset search index.
Reset Search Index

*Disable lockdown feature on the site collection, disable anonymous access, then enable anonymous access again, full crawl of the website

*Web part indexing

*

*Under the SharePoint Site go to Site Settings.  Search Administration -> Search and offline availability -> Indexing ASPX Page Content, Enable the option "Always index all Web Parts on this site"

*Under Search Service Application, do a Full Crawl for the content source to resolve this issue.


text:
Q: Quick Look video scrubbing on macOS High Sierra Previously, when previewing a video in Quick Look, scrolling right and left on the trackpad would scrub forward and backward, but after upgrading to macOS High Sierra, this seems no longer to be the case.
Is there any way to re-enable this setting? Or, if not, are there any alternative ways to scrub? (Dragging the line on the progress bar is not nuanced enough, especially for longer videos.)

A: As of macOS 10.13.2 (17C88) it is working correctly once again.


text:
Q: Make new dynamic CheckBoxList as per selected items of another checkboxlist in asp.net I am making ecommerece website where I have certain filters (5 type of checkboxlists). If user apply any items from checkboxlist the selected items should be added to new checkboxlist. Basically I want to display what users have selected. I can able to do this with following code.
if (IsPostBack) {
    userSelections.Items.Clear();
    foreach (ListItem item in priceFilter.Items) {
        if (item.Selected) {
            userSelections.Items.Add(item);
        }
    }

    foreach (ListItem item in brandFilter.Items) {
        if (item.Selected) {
            userSelections.Items.Add(item);
        }
    }
}

With this code items get added to userselections CheckboxList but now i don't know if something from userselection gets uncheck it should be uncheck from it's main filter as well.Can any one help me to do this.

A: When item is unchecked from userSelections, you have to take the item value from list and loop through with priceFilter and brandFilter using userSelections CheckedChanged Event. When unchecked item value is match with the priceFilter and brandFilter item ,just uncheck from the priceFilter or brandFilter.
String unchecked_item = userSelections.item.value; (Note : unchecked item value)
    foreach (ListItem item in priceFilter.Items) {
            if (unchecked_item == item.value) {
                priceFilter.Item.selected = false;
            }
        }

foreach (ListItem item in brandFilter.Items) {
            if (unchecked_item == item.value) {
                brandFilter.Item.selected = false;
            }
        }

finally remove the unchecked item from the userSelections.

A: Oh I think you can using JavaScript or CheckedChanged Event. When the user checks new checkboxlist, just remove it.

A: You need to apply this on Apply Event for checkbox, not page load event. I think you applied in Page_Load isPostback.


text:
Q: Passing object with wrapped properties don't allow compile on (set) I followed this guide on creating wrapped properties with user defaults:
https://www.vadimbulavin.com/advanced-guide-to-userdefaults-in-swift/
Now, I have LocalStorage class which will take this "Storage()" class at the end of the tutorial and then access that object's references to get the data from UserDefaults values. For some reason, when I set a string in my code, it no longer builds/compiles. It works for booleans. An example below:
// The marker protocol
protocol PropertyListValue {}

extension Data: PropertyListValue {}
extension String: PropertyListValue {}
extension Date: PropertyListValue {}
extension Bool: PropertyListValue {}
extension Int: PropertyListValue {}
extension Double: PropertyListValue {}
extension Float: PropertyListValue {}

// Every element must be a property-list type
extension Array: PropertyListValue where Element: PropertyListValue {}
extension Dictionary: PropertyListValue where Key == String, Value: PropertyListValue {}

struct Key: RawRepresentable {
    let rawValue: String
}

extension Key: ExpressibleByStringLiteral {
    init(stringLiteral: String) {
        rawValue = stringLiteral
    }
}

extension Key {
    static let isFirstLaunch: Key = "isFirstLaunch"
    static let username: Key = "username"
}

@propertyWrapper
struct UserDefault<T: PropertyListValue> {
    let key: Key

    var wrappedValue: T? {
        get { UserDefaults.standard.value(forKey: key.rawValue) as? T }
        set { UserDefaults.standard.set(newValue, forKey: key.rawValue) }
    }
}

struct Storage {
    @UserDefault(key: .isFirstLaunch)
    var isFirstLaunch: Bool

    @UserDefault(key: .username)
    var username: String
}

struct LocalStorage{

    var storage: Storage

    init(storage: Storage){
       self.storage = storage
    }

    func ex(){
         storage.username = "travis" // will not compile... "Abort 6"
         storage.isFirstLaunch= true // without line above, it will compile
     }

}

A: Okay, two changes:
struct Storage {
    @UserDefault(key: .isFirstLaunch)
    var isFirstLaunch: Bool?

    @UserDefault(key: .username)
    var username: String?
}

and
mutating func ex() {
    storage.username = "travis"
    storage.isFirstLaunch = true
}


text:
Q: Does Basemap allow to print the number of datapoints plotted? I have flight locations from several areas around the world and when I choose a specific area to plot the points, I want to know how many points are being plotted.
Is there a functionality to output the number of points that show up on my map?


text:
Q: Sort Months PowerBI Designer I am trying to sort months into PowerBI Designer Preview, it looks like it only can be done alphabetically. But when I look on the internet at images of PowerBI it looks like they are all sorted correctly. Can somebody help me? And there must be other people who are facing this problem right?
Thank you in advance.

A: In Power Pivot, you can set a sort by column. This hints Power Pivot to sort a given column like a column of month names by another column like a column of integers representing the order of month names.  The pattern is to create a Date table - a table with all of your dates.  In this date table you create a column with month names and another column with month indexes. Then you select the column with month names and set the sort by property to the month indexes column.  Usually, I like to create a 'MonthYear' column that has values like "Dec-14", "Jan-15" etc. this then allows me to sort correctly across years.

A: Check what is the data type of the column you are trying to sort. If it's Text then it would sort alphabetically, irrespective that these are numbers. Make sure it's Date or Number to sort correctly.


text:
Q: maven: execute without actually building anything I have a project with finalised version in pom files , lets say 12.3.45 .
I have built the code for this version some time ago already, all the built jars are in the local maven repo.
Then at some point I have run mvn clean, so all the target folders are being removed.
And now I want to execute some code, as quickly as possible, using mvn exec:java. Preferably without building anything, because why not? all the jars at some point were already built, and I know there were no code changes after that. How can I force maven to execute the code as fast as possible , not recompile anything, and just reuse the jars from the local repo?
Thanks.

A: *

*If your artifacts are in a local or remote repository you can use them as dependencies.

*You can use exec-maven-plugin's options includeProjectDependencies or includePluginDependencies to use them in java execution
https://www.mojohaus.org/exec-maven-plugin/java-mojo.html#includePluginDependencies. includeProjectDependencies option is enabled (true) by default.

*You can execute exec-maven-plugin without building anything with mvn exec:java command

Instructions:
To run exec-maven-plugin you would need a main class to run. I assume you have one in your project. If you don't - you need to make a separate project with a main class.

*

*Create a blank maven project.

*In the project add exec-maven-plugin configuration. Set the mainClass

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
                <goals>
                    <goal>java</goal>
                </goals>
                <configuration>
                    <mainClass>pack.App</mainClass>
                </configuration>
        </plugin>
    </plugins>
</build>

*Include you artifacts as dependencies to the project

<dependencies>
    <dependency>
        <groupId>my.group</groupId>
        <artifactId>myartifact</artifactId>
        <version>12.3.45</version>
    </dependency>
</dependencies>

*Run mvn exec:java to execute com.my.package.MyMainClass main class from my.group.myartifact artifact

Edits:

*

*includeProjectDependencies option is enabled (true) by default


text:
Q: Drawing an imperfect circle Programatically drawing a perfect circle is not all that difficult.  It's based on some very simple math, afterall.  You input two parameters (a center and a radius) and output the circle.
But if you don't have tools to help you, drawing a circle freeform (as in holding a pen in your hand) is very difficult!  If I wanted to simulate a person trying to draw a circle, is there any algorithm I could use that takes three parameters (a center, a radius, and a "wrongness factor") and uses the magnitude of the third value to create random imperfections in the circle, while still producing something that looks recognizably like a person trying to draw a circle?

A: Plot the circle as a series of arcs, both "inwards" and "outwards", recalculating the correct center for each segment needed to keep the endpoint of the arc within a certain distance of the actual circumference.

A: A circle drawn by free hand is random but still looks continuous. Adding noise to the radius might result in jumps which look unrealistic.
A slight modification can somewhat resolve this issue. Using a Markov matrix, divide the noise into N levels and have only tri-diagonal entries. This will result in randomness but yet it can only transit to prev/next levels only. Making it look continuous.


text:
Q: Since when do divs support the `onchange` event, and is it a bug? I've just accidentally bound a div that contained a radio button to an onchange event, instead of the actual radio button that was in it, and found that the event still fired. I have now ran the Fiddle below, in Firefox and a Webkit browser, and they both worked.
As I've never seen or heard mention of this before, I am now wondering if this is intended, is it new, and is it okay to use it in production and expect it to work in all (or older) browsers? Neither MDN or W3schools mention non-input elements for the onchange event.
Fiddle here: https://jsfiddle.net/4cjdy9do/

A: div doesn't have its own change event, but change bubbles. (And that's not new.) From the MDN page you linked:

Bubbles: Yes

So you'll see change on any element (not just div) containing an input or select, provided the event isn't prevented from bubbling by stopPropagation.
For instance, you can watch for all (non-stopped) change events on document, because the bubble there from their original target elements:

document.addEventListener("change", function(e) {
  console.log("Got change, new value: " + e.target.value);
});

    One:
    <input type="text">

    Two:
    <input type="text">

    Three:
    <select>
      <option>ay</option>
      <option>bee</option>
      <option>see</option>
    </select>


text:
Q: Get DialogResult from custom dialog I have some custom made dialog that have on it Set Button , I want when i exit from newBlockForm.ShowDialog(this); to get the dialog result if the user pressed on that button or not .
Like i would do in winforms dialog
if(MessageBox.Show("Exit?", "Close UP",
     MessageBoxButtons.YesNo)== DialogResult.Yes)

Any idea how i do so ?

A: Map the AcceptButton property on the Form to Set button in the designer.
Or in the Set button click handler you could set some value.
        private void HandleOnSetButtonClick(object sender, EventArgs e)
        {
            this.IsSetClicked = true;
            this.Close();

            //or
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        public Boolean IsSetClicked
        {
           get;
           private set;
        }

A: You can use the DialogResult Property of the Button on your Dialog form and set it to DialogResult Enumeration like:
//in your dialog form
button1.DialogResult = DialogResult.OK;

then in your main form :
//Create an instance of your dialog form
Form2 testDialog = new Form2();

// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
   //do processing
}
else
{
   //do processing
}

A: ShowDialog method returns a DialogResult by itself which you can set automatically by setting the DialogResult of the buttons in question in your form designer.


text:
Q: CSS, different expand and collapsed behavior in Firefox and IE I have an panel which has expand menu and other like:

When I expand panel in IE 10 and Firefox 55.0.3, it seems like this:

But in chrome, it works well

There is two part on .tbl-main.Expandable search panel and result panel(tbl-container). I use flex layout to cover parent.Search panel is only 15px here.Rest of .tbl-main must be .tbl-container.It is okey here. But Browsers behave strange. Here my html and css codes

.tbl-main {
  height: 100%;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3);
  display: -webkit-box;  /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box;  /* OLD - Firefox 19- (doesn't work very well) */
  display: -ms-flexbox;  /* TWEENER - IE 10 */
  display: -webkit-flex;  /* NEW - Chrome */
  display: flex;  /* NEW, Spec - Opera 12.1, Firefox 20+ */
  -webkit-box-direction: normal;
  -moz-box-direction: normal;
  -ms-flex-direction: column;
  -webkit-flex-direction: column;
  flex-direction: column;
}

.tbl-searchpanel {
  min-height: 15px;
  background: yellow;
}

.tbl-container {
  min-height: 50px;
  background-color: blue;
  -webkit-box-flex: 1;
  -moz-box-flex: 1;
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
}

.tbl-searchpanel input {
  display: none;
  visibility: hidden;
}

.tbl-searchpanel label {
  display: block;
  padding: 0.5em;
  text-align: center;
  border-bottom: 1px solid #CCC;
  color: #666;
  background-color: lightcoral;
  min-height: 100%;
}

.tbl-searchpanel label:hover {
  color: #000;
}

.tbl-searchpanel label::before {
  font-family: Consolas, monaco, monospace;
  font-weight: bold;
  font-size: 15px;
  content: "+";
  vertical-align: central;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 3px;
  background: radial-gradient(ellipse at center, #CCC 50%, transparent 50%);
}

#expand {
  width: 100%;
  height: 250px;
  overflow: hidden;
  transition: height 0.5s;
  /*background: url(http://placekitten.com/g/600/300);*/
  /*color: #FFF;*/
  background-color: red;
  display: none;
}

#toggle:checked~#expand {
  display: block;
}

#toggle:checked~label::before {
  content: "-";
}

    <input id="toggle" type="checkbox" />

A: Remove the min-height: 100%; from the .tbl-searchpanel label rule
Stack snippet

html, body {
  height: 100%;
  margin: 0;
}

.tbl-main {
  height: 100%;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3);
  display: -webkit-box;  /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box;  /* OLD - Firefox 19- (doesn't work very well) */
  display: -ms-flexbox;  /* TWEENER - IE 10 */
  display: -webkit-flex;  /* NEW - Chrome */
  display: flex;  /* NEW, Spec - Opera 12.1, Firefox 20+ */
  -webkit-box-direction: normal;
  -moz-box-direction: normal;
  -ms-flex-direction: column;
  -webkit-flex-direction: column;
  flex-direction: column;
}

.tbl-searchpanel {
  min-height: 15px;
  background: yellow;
}

.tbl-container {
  min-height: 50px;
  background-color: blue;
  -webkit-box-flex: 1;
  -moz-box-flex: 1;
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
}

.tbl-searchpanel input {
  display: none;
  visibility: hidden;
}

.tbl-searchpanel label {
  display: block;
  padding: 0.5em;
  text-align: center;
  border-bottom: 1px solid #CCC;
  color: #666;
  background-color: lightcoral;
  /* min-height: 100%;                     removed  */
}

.tbl-searchpanel label:hover {
  color: #000;
}

.tbl-searchpanel label::before {
  font-family: Consolas, monaco, monospace;
  font-weight: bold;
  font-size: 15px;
  content: "+";
  vertical-align: central;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 3px;
  background: radial-gradient(ellipse at center, #CCC 50%, transparent 50%);
}

#expand {
  width: 100%;
  height: 250px;
  overflow: hidden;
  transition: height 0.5s;
  /*background: url(http://placekitten.com/g/600/300);*/
  /*color: #FFF;*/
  background-color: red;
  display: none;
}

#toggle:checked~#expand {
  display: block;
}

#toggle:checked~label::before {
  content: "-";
}

    <input id="toggle" type="checkbox" />


text:
Q: C++ selective predefined functor initializaiton Predefined functors need to be in-place instantiated (with empty parentheses) for use in algorithms but not as type parameters for container adapters such as priority_queue. Why the difference?
#include <queue>
#include <vector>
#include <numeric>

int main(){

   std::priority_queue<int, std::vector<int>,
   // parentheses are NOT needed here: std::greater<>
                                            std::greater<>> pq;
   pq.push(1);
   pq.push(2);
   pq.push(3);

   std::vector<int> v = {1, 2, 3};

   auto result = accumulate(v.begin(), v.end(), 0,
                              // parentheses are needed here std::plus<>()
                                                  std::plus<>());
}

A: std::priority_queue is a class template with type template parameters. Its specialization requires to specify type template arguments. And std::greater<> is a type used as a type template argument.
On the other hand, in an algorithm you need to supply a functional object as for example std::greater<>().

A: In both cases the type of the callable is a template argument. For the std::priority_queue you explicitly state the template argument, a type. With std::accumulate you pass an instance of the comparator such that the template arugment (the type of the comparator can be deduced).
With CTAD (class template argument deduction) this difference is less pronounced. If you want you can put it the other way around:
#include <numeric>
#include <queue>

int main() {
    std::priority_queue pq(std::greater<int>{},std::vector<int>{});

    std::vector<int> x;
    std::accumulate<std::vector<int>::iterator,int,std::greater<>>(x.begin(),x.end(),0,{});
}

Here, I made use of CTAD to let the constructor deduce the type of the argument passed to the constructor. Then with std::accumulate, its rather uncommon, but if you like you can explicitly specify tempalte arguments for the algorithm. Though you still need to pass a default constructed instance, because there is no overload with a default for the binary operation (there could be, its just not that useful, because usually you want to write just std::accumulate(..) and have all template arguments be deduced).


text:
Q: How to run multiple instances of PFactory on CUDA? I am using PFactory (panorama factory) to stitch images in batch mode. Currently it uses multiple threads to do the same on CPU. I want to run it on my nvidia GPU (which has 144 cores). I wrote a kernel program which calls - system(pfactory) - to execute one instance of PFactory. But when I compile it using nvcc, it throws up an error - can't execute a host function in device..."
Is there a way by which I could run multiple instances of this program on GPU cores?

A: CUDA kernels and device functions cannot directly call host functions. system is a host function.
There is no way to do what you ask.


text:
Q: How to prevent dependency resolution during configuration in gradle I am very new to Gradle. I am trying to write two tasks:

*

*Which will take some archives that have been downloaded manually and put in some directory and then publish them to a repository. This is only run occasionally when that third party archive is updated and we need to use that new version.

*Another copy tasks which will download the archives, unpack them, and then copy them to a local directory. This should be run at compile time.
I got part of the way there but it seems that surprisingly the dependencies are being downloaded at configuration time which seems rather odd. This means that nothing works because I can't even run the first task as the second one cases the dependencies to be downloaded which fails.

Here is what I have got so far:
plugins {
    id 'maven-publish'
}

def mafftGroupId = 'jp.cbrc.mafft'
def mafftArtifactId = 'mafft'
def mafftVersion = '7.388'

def artifactsDir = 'artifacts'
def mafftResourcesDir = 'resources/m2'

// TODO: De-duplicate these
def linux64TarballFile = file("$artifactsDir/mafft-$mafftVersion-linux.tgz")
def linux64TarballArtifact = artifacts.add('archives', linux64TarballFile) {
    classifier = 'linux'
    type = 'tgz'
}
def macZipFile = file("$artifactsDir/mafft-$mafftVersion-mac.zip")
def macZipArtifact = artifacts.add('archives', macZipFile) {
    classifier = 'mac'
    type = 'zip'
}
def win64ZipFile = file("$artifactsDir/mafft-$mafftVersion-win64-signed.zip")
def win64ZipArtifact = artifacts.add('archives', win64ZipFile) {
    classifier = 'win64'
    type = 'zip'
}

publishing {
    publications {
        mafft(MavenPublication) {
            groupId mafftGroupId
            artifactId mafftArtifactId
            version mafftVersion
            artifact linux64TarballArtifact
            artifact macZipArtifact
            artifact win64ZipArtifact
        }
    }

    repositories {
        maven {
            name 'artifactory'
            url 'https://biomatters.jfrog.io/biomatters/libs-release-local'
            credentials {
                username = artifactoryUser
                password = artifactoryPassword
            }
        }
    }
}

// TODO: This should maybe have a type of PublishToMavenRepository but I couldn't figure it out.
task publishMafftToArtifactory {
    dependsOn 'publishMafftPublicationToArtifactoryRepository'
}

configurations {
    mafftArchives
}

dependencies {
    // TODO: Is there a way to just use the artifact files here?
    mafftArchives(group: mafftGroupId, name: mafftArtifactId, version: mafftVersion, classifier: 'linux', ext: 'tgz')
    mafftArchives(group: mafftGroupId, name: mafftArtifactId, version: mafftVersion, classifier: 'mac', ext: 'zip')
    mafftArchives(group: mafftGroupId, name: mafftArtifactId, version: mafftVersion, classifier: 'win64', ext: 'zip')
}

task unpackMafft(type: Copy) {
    // TODO: De-duplicate this too
    configurations.mafftArchives.asFileTree.filter { File f ->
        f.name.endsWith(".zip")
    }.each {
        from(zipTree(it))
    }
    configurations.mafftArchives.asFileTree.filter { File f ->
        f.name.endsWith(".tgz")
    }.each {
        from(tarTree(it))
    }
    rename "mafft-linux64", "Linux64"
    rename "mafft-mac", "OSX"
    rename "mafft-win", "W64"
    into "$mafftResourcesDir"
}

The error is:
FAILURE: Build failed with an exception.

* Where: Build file '/source/trunk/plugins/MafftPlugin/build.gradle' line: 71

* What went wrong: A problem occurred evaluating project ':plugins:MafftPlugin'.
> Could not resolve all files for configuration ':plugins:MafftPlugin:mafftArchives'.
   > Could not find mafft-win64.zip (jp.cbrc.mafft:mafft:7.388).

I wondered whether I could make the dependencies conditional depending on what task is run but as far as I can tell the configuration happens before any of the task graph information is available.
This has got me baffled. I have no idea what to do.
Cheers


text:
Q: Inversion for insertion sort! This a question I found in the Wikipedia site (I want to learn sort algorithms very well). Anyway, this is a question - could you explain to me how I can show it?
Exercise: Show that Algorithm Insertion Sort (A) runs in time O(n + I) given that I is the number of inversions in the array A.

A: Look at the Implementation and Analysis sections of this page.
Consider the algorithm presented there:
private static void insertionsort()
{
    int i, j, t;
    for (i=1; i<n; i++)
    {
        j=i;
        t=a[j];
        while (j>0 && a[j-1]>t)
        {
            a[j]=a[j-1];
            j--;
        }
        a[j]=t;
    }
}

Notice that the while loop runs for v[i] iterations, where v[i] is the number of inversions caused by element i. This should make the proof there very easy to understand.


text:
Q: partials are not rendering, nore are they throwing errors So I have the following in projects#show:

Discussion

<%= render 'discussions/creatediscussion', :project => @project %>

    <%= render :partial => 'discussions/discussion', :collection => @discussions %>

Category

<ul id="categories" data-update-url="<%= sort_categories_url %>">
  <%= render :partial => 'categories/category', :collection => @categories %>

<%= render 'categories/createcategory', :project => @project %>

This essentially renders forms, views and so on and so forth. The issue is that while NONE of these throw errors in any way, and while creating things like discussions and categories work - any of the :partial => '' do not render. while the rest of the renders do.....
any thoughts as to why?

A: Have you tried:
<%= render :partial => 'discussions/creatediscussion', :locals => {:project => @project} %>
or
<%= render :partial => 'discussions/discusion', :locals => {:discussions => @discussions} %>
or
<%= render :partial => 'categories/category', :locals => {:categories => @categories} %>
You might need to rework your partial code a bit, but declaring locals always works for me.


text:
Q: Console.ReadLine returns empty string for unicode input when input/output encoding is Encoding.UTF8? Targeting netcoreapp2.1 with this code:
static void Main()
{
    Console.InputEncoding = Console.OutputEncoding = Encoding.UTF8;
    while (true)
    {
        var line = Console.ReadLine();
        Console.WriteLine($"Length: {line.Length}");
        Console.WriteLine($"Bytes: {string.Join(", ", Encoding.UTF8.GetBytes(line).Select(b => b.ToString()))}");
        Console.WriteLine(line);
    }
}

When I type что (a Russian word), then the output is:
Length: 3
Bytes: 0, 0, 0
<<there is an empty line here>>

When I type Hello world, then the output is:
Length: 11
Bytes: 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100
Hello world

If I set the input/output encoding to Encoding.Unicode then it works as expected (the Russian word yields six bytes like you'd expect). What gives?


text:
Q: Filter duplicate name from database in C# When a method is called, I want to return true if the name already exists, and false otherize. My sample code is below.
private bool NameDuplicate(string txt)
{
    conn.Open();
    com.Connection = conn;
    com.CommandText = "select Cat_d from Category";

    SqlDataReader dr = com.ExecuteReader();
    bool found = false;

    while (dr.Read())
    {
        if (txt == dr["Cat_d"].ToString())
        {
            found = true;
        }
        else
        {
            found = false;
        }
    }

    conn.Close();
    return found;
}

if (NameDuplicate(cat_txt))
{
    MessageBox.Show("Already exist!");
}

Please help me explained.

A: Below is some code you can use to do this but I want to point out that Realistically you probably wouldn't bother doing this in c#. You would add a UNIQUE constraint/index or primary key in the db and just insert values from c#, handling the case where there is an exception because the value already exists. Implementing a uniqueness logic in c# when sqlserver has been capable of doing it forever really is "buying a dog and barking yourself"
private bool NameDuplicate(string txt)
{
  using(var con = new SqlConnection(YOUR CONNECTION STRING HERE)
  using(var com = new SqlCommand("select count(*) from Category where cat_d = @c", con){
    con.Open();
    com.Parameters.Add("@c", SqlDbType.VarChar, 999).Value = txt;
    var o = com.ExecuteScalar();

    con.Close(); //optional; dispose will do this too
    return Convert.ToInt32(o) != 0;
  }
}

if (NameDuplicate(cat_txt))
{
    MessageBox.Show("Already exist!");
}

Always use using blocks to ensure db related resources are disposed of, and don't reuse them (it seems your connection and command are defined somewhere else and you keep them for a long time/reuse them?
To check for existence we can (simplistically) count the number of entries, executescalar it and check the returned number. It might be slightly faster to use an EXISTS query but I picked this route because it is easy to read and keeps the code simpler.
Here is a query you could use in place of the select count, to achieve the same effect. It would be highly beneficial to use it if the column you're searching isn't indexed because, as Aaron points out, there isn't any point in having sqlserver count all of an entire table when realistically it could stop as soon as it finds the value you're looking for and deliver the same answer:
SELECT CASE WHEN EXISTS(SELECT null FROM Category where cat_d = @c) THEN 1 ELSE 0 END


text:
Q: java type for javascript anonymous function What data type will the javascript function like
(event) => {
  event.preventDefault();
  host.somethingsomething();
}

be cast to in Java?
I have host objects for event and for host.
I don't know how to turn that ^^ into a function I can run in Java.


text:
Q: Using COUNTIF + IMPORTRANGE together I'm trying to use the count function in a sheet (sheet 1) while pulling the info from another sheet (sheet 2) through the IMPORTRANGE function.
I've used the function
=COUNTIF(IMPORTRANGE("URL","Sheet2!A1:Sheet2!A10"),">0"),
however, instead of counting the number of cells from sheet 2 that have a number greater than 0, the cell in sheet 1 with the formula just reads 0.
I've tried using =COUNTA as well, and the cell produces 1 when it should count 10.
How can I fix this?

A: first, you need to run importrange in some cell and authorize it:
=IMPORTRANGE("URL", "Sheet2!A1:A10")

then try:
=COUNTIF(IMPORTRANGE("URL", "Sheet2!A1:A10"), ">0")

or:
=INDEX(COUNTA(IFNA(QUERY(IFERROR(IMPORTRANGE("URL", "Sheet2!A1:A10")*1),
 "where Col1 > 0"))))


text:
Q: Create an ActionLink for a DisplayFor value I have coded a C# MVC 5 Internet Application and have a question about an ActionLink in a View.
I have the following code:
<td>
    @Html.DisplayFor(modelItem => item.mapLocations.Count)
</td>

Is it possible to create an ActionLink for this above displayed value?
Thanks in advance
EDIT
I have tried the following code:
@Html.ActionLink(item.mapLocations.Count, "Index", "MapLocation", new { mapCompanyid = item.Id }, null)

I am getting a compilation error as follows:
Compiler Error Message: CS1928: 'System.Web.Mvc.HtmlHelper<CanFindLocation.ViewModels.MapCompaniesViewModel>' does not contain a definition for 'ActionLink' and the best extension method overload 'System.Web.Mvc.Html.LinkExtensions.ActionLink(System.Web.Mvc.HtmlHelper, string, string, string, object, object)' has some invalid arguments

EDIT2
Do I need the DisplayFor code to display the value in the ActionLink?
Maybe something like this:
@Html.ActionLink(Html.DisplayFor(modelItem => item.mapLocations.Count), "Index", "MapLocation", new { mapCompanyid = item.Id }, null)

A: This will work :-
@Html.ActionLink(item.mapLocations.Count, "// action name //", "// controller name //", new{ mapCompanyid = item.Id  }, new{ // html attributes // })

Just match your Actionlink it's structure should look like below :-
Html.ActionLink(item.mapLocations.Count, //  <--Title
            "Index",   // <-- ActionMethod
            "MapLocation",  // <-- Controller Name.
            new { mapCompanyid = item.Id }, // <-- Route arguments.
            null  // <-- htmlArguments.
            )


text:
Q: How to create multiple route with laravel 5.8 I'm using version 5.8 of laravel and I'm trying to initialize the routes. It is not possible to access the route created after the default route:
Route::get('/', function () {
    return view('welcome');
});

I try to add a parameter in the second route:
Route::get('/page', ['as' => 'home', function (/page) {return view('page1') ;}]);

I got 404 error. How can I use multiple routes ?
This is my web.php file:
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/page', function() { return view('page1'); })->name('home');
Route::get('/', function () {
    return view('welcome');
});

A: Did you copied the second route, or what are you trying to do with this?
You can try this one instead as your syntax is wrong:
Route::get('/page', function() { return view('page1'); })->name('home');

-- EDIT
You can also return just the views from your routes if you don't plan to use a controller, like this:
Route::view('/', 'welcome');
Route::view('/page', 'page1');


text:
Q: Puppet Open Source connect to PuppetDB or DB? I installed Puppet Open Source and I want to read the DB how can I do that and what should I do for it?
I found this git repo:
the PuppetDB GitHub repo but I cant start anything with it.
thanks in advance

A: You should follow the docs here to install PuppetDB.


text:
Q: How to tell if nginx sites-available is enabled Ubuntu 20.04? I'm not too familiar with how Nginx works, but a buddy of mine needed another AWS EC2 instance set up. I noticed it was doing a redirect with Nginx on the main instance and saw that sites-available and sites-enabled were being utilized.
The difference between mine and the main instance is that on AWS console, the sites-available .conf on main is highlighted blue and mine isn't. Does this mean mine is not fully enabled?
I get 0 errors when testing files and reloading nginx. Any help is appreciated.


text:
Q: Need help traversing a tree; Huffman Coding I have created a Huffman Tree and It appears to be correct, however I am weak when it comes to traversing data structures. I drew out the Tree on paper based on the information contained in my root tree and it appears to be well, however My code is faulty and I do not know hot to fix it.
The first 0 is persisting and, every time i take right, it seems to append a 0 after.
example:
L: 01
H: 1111

but my traversal gives me:
L: 001
H: 01010101

code Snippets
struct node
{
int symbol;
int frequency;
node* left;
node* right;
};

void Huffman::generateCode(node *tree, std::string code)
{
    if(tree->left == NULL && tree->right == NULL)
    {
        //std::cout << "Leaf Found: " << tree->symbol << "\t" << code << std::endl;
        mapCode.insert(std::pair<int, std::string>(tree->symbol,code));
    }
    if(tree->left != NULL)
    {
        code.append("0");
        generateCode(tree->left, code);
    }
    if(tree->right != NULL)
    {
        code.append("1");
        generateCode(tree->right, code);
    }
}

UPDATE SOLVED: i figure out that the code.append(); function was messing it up. i changed it too code + "0";
void Huffman::generateCode(node *tree, std::string code)
{
    if(tree->left == NULL && tree->right == NULL)
    {
        std::cout << "Leaf Found: " << tree->symbol << "\t" << code << std::endl;
        mapCode.insert(std::pair<int, std::string>(tree->symbol,code));
    }
    if(tree->left != NULL)
    {
        generateCode(tree->left, code + "0");
    }
    if(tree->right != NULL)
    {
        generateCode(tree->right, code + "1");
    }
}

A: you missed the elses:
void Huffman::generateCode(node *tree, std::string code)
{
    if(tree->left == NULL && tree->right == NULL)
    {
        //std::cout << "Leaf Found: " << tree->symbol << "\t" << code << std::endl;
        mapCode.insert(std::pair<int, std::string>(tree->symbol,code));
    }
    else if(tree->left != NULL)
    {
        code.append("0");
        generateCode(tree->left, code);
    }
    else if(tree->right != NULL)
    {
        code.append("1");
        generateCode(tree->right, code);
    }
}


text:
Q: How to use Tcl/Tk with VHDL I am new to both VHDL and Tcl/Tk. Straight to question: I want to know how to use Tcl/Tk  in Modelsim. Suppose I do not know anything in Tcl/Tk, but I have the following VHDL code for a full adder to start with. What can I do with it using Tcl/Tk and what steps should I take.I am using Quartus Prime Standard Edition and Modelsim with Altera Cyclone FPGA.
 LIBRARY ieee;
 USE ieee.std_logic_1164.all;
 USE ieee.std_logic_signed.all;
 ENTITY adder IS
--H&G are 8 bit inputs
--M is 8-bit output

PORT (carryin : IN STD_LOGIC;
        X,Y   : IN STD_LOGIC;
        S         : OUT STD_LOGIC;
        carryout: OUT STD_LOGIC);
 END adder;

 ARCHITECTURE Behaviour OF adderk IS
--SIGNALS ARE VARIABLES THAT WE WILL SIGN OUR OUTPUT VARIABLES TO
Signal Sum : STD_LOGIC;
BEGIN

    Sum <= X XOR B XOR carryin;
    carryout <= X AND B AND carryin AND (A XOR B);
    M<=Sum;
END Behaviour;

A: TCL is just another way to interact with the ModelSim environment. Instead of doing things in GUI using your mouse, TCL gives you the flexibility of creating scripts for simulating and evaluating your design. You can take a look here, which I think you will find very useful.


text:
Q: Update list when route parameter changes I have a component where I get a route parameter:
export class CatalogComponent implements OnInit {

  category: number;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {

    this.route.paramMap.subscribe(parameters => {
      this.category = parameters.has('category') ? +parameters.get('category') : undefined;
    })

  }

}

Then on the template I have:
<product-list [category]="category"></product-list>

And ProductList component is:
export class ProductListComponent implements OnInit {

  @Input() category: number;

  products$: Observable<ProductListModel[]>;

  constructor(private productService: ProductService) { }

  ngOnInit() {

    this.products$ = this.getProducts();

  }

  private getProducts(): Observable<ProductListModel[]> {

    return this.productService.get(this.category);

  }

}

The problem is when route parameter category changes the Products rendered by ProductList component are not updated.
How can I solve this?

A: you need to implement ngOnChanges in ProductListComponent
like below
ngOnChanges(changes: Record<keyof ProductListComponent, SimpleChange>) {

  if (changes.category && changes.category.currentValue) {

    // reload your data here
  }
}


text:
Q: program using named pipes crashed The program is about providing message between people created via FIFO by selected,
./a.out create name_of_person

The first condition if( strcmp(argv[1], "create") == 0 ) works properly, but after that, after selecting ./a.out name1 name2 message and while compiling the program hangs out (it's else condition).
How can I solve the problem?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

int main(int argc, char* argv[]) {

 int i = 0;
 int fifo = -1;

 if( strcmp(argv[1], "create") == 0 ) {
    int fifo = mkfifo(argv[2], 0666);

    if( ( fifo == -1) ) {
        perror("\n The problem occured. The program exited. \n");
        printf("error %d : %s \n", errno, strerror (errno));
    exit( 1 );
    }
 }

 else if( strcmp(argv[2], "history") == 0 ) {

  int process1 = fork();

  if( process1 == 0 ) {

    int process2 = fork();

    if( process2 == 0 )
     {
        char c;
        if (fifo == 0) {
        int FILE = open(argv[1], O_RDONLY);

        for(i=3; i<argc; i++) {
        read( FILE, argv[i], 1 );
        //while( ( Scanner = read( odFILE, &c, 1) ) > 0 )
        }

        close( FILE );
        }
    }
    kill();
 }
 }

 else
 {

 if( (open(argv[1], O_RDONLY, 0777) == -1) || (open(argv[2], O_RDONLY, 0777) == -1) )
 {
  perror("The user does not exist.");
  exit(1);
 }

 printf("< ");
 printf("%s", argv[1]);
 printf(" -> ");
 printf("%s", argv[2]);
 printf(" > : ");

 for(i=3; i<argc; i++) printf("%s", argv[i]);

 int process1 = fork();

 if( process1 == 0 ) {

int process2 = fork();

    if( process2 == 0 ) {
        int FILE = open(argv[2], O_RDONLY);
        write( FILE, argv[3], sizeof(argv[3]) );
        close( FILE );
    }

    kill();
 }
}

 return 0;
}

A: From man 3 mkfifo:

However, it has to be open at both ends simultaneously before you can proceed to do any input or output operations on it.  Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and  vice versa.

In your line
if( (open(argv[1], O_RDONLY, 0777) == -1) || (open(argv[2], O_RDONLY, 0777) == -1) )

you are opening both fifos for reading. Both opens will block until also a writer opens the fifo.
BTW, this if leaks both opened file descriptors.
Your later processing
int FILE = open(argv[2], O_RDONLY);
write( FILE, argv[3], sizeof(argv[3]) );
close( FILE );

has the same problem of blocking during open until a write opens the fifo. And there is another problem: you are opening the fifo for reading only but you are writing to it only.
You need to replace your open for checking if the files exists. Remove it - your later open will fail - or replace it with a stat. And you need to implement both sides of the messaging to test it, not only one side (or you need to run a shell command to write to or read from the fifo in parallel to your program to test it).
Other problems in your code:

*

*You are not including the right header for kill - and you are calling kill without the needed parameters.

*You are not including the right header for mkfifo.

You should consider enabling more warnings to see those problems in your code.


text:
Q: There's a way to filter changes commit on Jenkins? I'd like to know if exists some way (Jenkins plug-in) to filter commits that you doesn't want to see, for example exclude someone who belongs to other team.
Thank you very much,
Regards

A: Assuming you are using polling to determine if Jenkins should run a build
It's possible to do this using the git-plugin.
Under Source Code Management > Additional Behaviours you will have options for:

*

*Polling ignores commits from certain users

*Polling ignores commits in certain paths

*Polling ignores commits with certain messages

EDIT
For subversion, the Subversion Plugin might have what you want.
Under Source Code Management > Advanced you can find the following options:

*

*Excluded Regions

*Included Regions

*Excluded Users

*Excluded Commit Messages


text:
Q: Getting no e-mail alerts when list attachment has been modified In our SP2010 lists, users who created e-mail alerts will not get notified when the list attachment (here: docx files) has been modified. This is the whether version is enabled or not.
Is this behavior intended, a bug or a mis-configuration in our farm? Maybe someone could test it in their farm:

*

*Create a list (Task list, custom list, etc.)

*Create notification for that list (All changes, immediate notification)

*Add a list item and attach a docx file

*Open list item and then the attachment

*Edit list attachment in MS Word

*Make a change to the file and Save

*Wait for a couple of minutes if you get an e-Mail regarding that last change

A: SharePoint send the alerts when item's properties got change, But when change is made on the attachment, then even list created new version but for some reason alert logic not recognized it.
In this case, i believe you have to use some king of custom workflow. check this. Send Attachment in Alert
or 3rd party options
http://blog.pentalogic.net/2013/03/how-to-configure-email-alerts-to-review-documents-in-sharepoint/


text:
Q: Conversion failed when converting date and/or time from character string I have following code :
private void button1_Click(object sender, EventArgs e)
 {

        cnn.Open();
        SqlCommand cmd = cnn.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into Books values('"+ textBox1.Text +"','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','"+ dateTimePicker1.Text +"','" + textBox6.Text + "','" +textBox7.Text+ "')";
        cmd.ExecuteNonQuery();

        cnn.Close();
        textBox1.Text = "";
        textBox2.Text = "";
        textBox3.Text = "";
        textBox4.Text = "";

        textBox6.Text = "";
        textBox7.Text = "";

        MessageBox.Show("book add to Books succesfull");

    }
}

when i run project it shows below error :

Conversion failed when converting date and/or time from character
  string.


text:
Q: Android display video stream in MediaPlayer and encode with MediaCodec Problem:
I have video stream from GoPro camera, in the .m3u8 format. I need to display the content of the stream in application and then stream the video.
For streaming, I have library that works with MediaCodec and ffmpeg. I should be able to stream the outputBuffer of MediaCodec.
I can stream the video with MediaPlayer on SurfaceView, no problem.
The real struggle comes with using MediaCodec.
I can initialize the MediaCodec, get the surface and add it to the MediaPlayer - the steam plays - I can hear the sound.
Now the questions:

*

*display the stream on the SurfaceView - or any other view that MP and MC can work with.
What is the best way to display data from Surface to SurfaceView/TextureView?

*I am not able get the data from MediaCodec.
I only need to support 5.0+ devices, so I tried to use MediaCodec.Callback. But I get error every time. I haven't found the meaning of the error.
What can I do to mate the Callback work?

*Is there any "easy" way of doing this, or do I have to go deep into the buffers and surfaces as in Google Grafika?
Here are the errors I get:
E/ACodec﹕ [OMX.qcom.video.encoder.avc] storeMetaDataInBuffers (output) failed w/ err -2147483648

 1877-1904/com.example.marek.goprorecorder E/ACodec﹕ [OMX.qcom.video.encoder.avc] ERROR(0x80001009)
07-15 15:54:47.411    1877-1904/com.example.marek.goprorecorder E/ACodec﹕ signalError(omxError 0x80001009, internalError -2147483648)
07-15 15:54:47.411    1877-1903/com.example.marek.goprorecorder E/MediaCodec﹕ Codec reported err 0x80001009, actionCode 0, while in state 6

Errror mess: android.media.MediaCodec$CodecException: Error 0x80001009
07-15 15:54:47.454    1877-1877/com.example.marek.goprorecorder D/MediaCodecCallback﹕ Errror diag: android.media.MediaCodec.error_neg_2147479543
07-15 15:54:47.454    1877-1877/com.example.marek.goprorecorder D/MediaCodecCallback﹕ Errror rec: false
07-15 15:54:47.454    1877-1877/com.example.marek.goprorecorder D/MediaCodecCallback﹕ Errror tra: false

And here is my Activity:
public class MainActivity extends ActionBarActivity implements MediaPlayer.OnPreparedListener{
    private final MediaPlayer mp = new MediaPlayer();
    private Surface encoderSurface;
    private static final String MIME_TYPE = "video/avc";    // H.264 Advanced Video Coding
    private static final int FRAME_RATE = 30;               // 30fps
    private static final int IFRAME_INTERVAL = 0;           // 5 seconds between I-frames
    private static final File OUTPUT_DIR = Environment.getExternalStorageDirectory();
    MediaCodec encoder = null;
    MediaCodec.BufferInfo mBufferInfo;
    TextureView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        int width = 432;
        int height = 240;
        prepareEncoder(width, height, 600000);
    }

    private void prepareEncoder(int width, int height, int bitRate) {
        mBufferInfo = new MediaCodec.BufferInfo();
        MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, width, height);
        format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
        format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
        format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE);
        format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);

        try {
            encoder = MediaCodec.createEncoderByType(MIME_TYPE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        CodecCallback callback = new CodecCallback();
        encoder.setCallback(callback);
        encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
        encoderSurface = encoder.createInputSurface();
        preparePlayer(encoderSurface);
        encoder.start();
    }

    void preparePlayer(Surface s) {
        try {
            //mp.setDataSource("http://10.5.5.9:8080/live/amba.m3u8");
            mp.setDataSource("http://playertest.longtailvideo.com/adaptive/oceans_aes/oceans_aes.m3u8");
            mp.setSurface(s);
            mp.prepare();
            mp.setOnPreparedListener(this);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }

    private class CodecCallback extends Callback {

        @Override
        public void onInputBufferAvailable(MediaCodec codec, int index) {
            Log.d("MediaCodecCallback","InputBufferAvailable "+index);
        }

        @Override
        public void onOutputBufferAvailable(MediaCodec codec, int index, MediaCodec.BufferInfo info) {
            ByteBuffer outBuffer = codec.getOutputBuffer(index);
            Log.d("MediaCodecCallback", "OutputBuffer Position: " + outBuffer.position());
            Log.d("MediaCodecCallback", "OutputBuffer Limit: " + outBuffer.limit());
            Log.d("MediaCodecCallback", "OutputBuffer Capacity: " + outBuffer.capacity());
            Log.d("MediaCodecCallback","OutputBuffer: "+outBuffer.toString());
            encoder.releaseOutputBuffer(index, false);
        }

        @Override
        public void onError(MediaCodec codec, MediaCodec.CodecException e) {
            Log.d("MediaCodecCallback","Errror mess: " + e);
            Log.d("MediaCodecCallback","Errror diag: " + e.getDiagnosticInfo());
            Log.d("MediaCodecCallback","Errror rec: " + e.isRecoverable());
            Log.d("MediaCodecCallback","Errror tra: " + e.isTransient());
        }

        @Override
        public void onOutputFormatChanged(MediaCodec codec, MediaFormat format) {
            Log.d("MediaCodecCallback","OutputFormatChanged: " + format.toString());
        }
    }

}

Edit 1:
Is this the right way to add the output to SurfaceTexture?
@Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        Surface s = new Surface(surface);
        preparePlayer(s); //ads Surface to MediaPlayer and starts to play the stream
    }

And can I use the surfaceTexture I get from onSurfaceTextureUpdate?
@Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }

*

*another question, do you have example how to render the SurfaceTexture to Surface?
Thank you!


text:
Q: How to give tooltip in extjs 4.2.1 for rowexpander icon on mouse over? How to give tooltip for rowexpander icon in extjs 4.2.1?.
I am using row expander plugins and want to give tooltip if + icon then Expand All ,if - then Collapse All dynamically.

A:
Use this in the Grid Listeners which has Row Expander Plugin.

afterlayout : function (obj) {
                if (obj.view.getNodes().length > 0) {
                    var nodes = obj.view.getNodes();
                    for (var i = 0; i < nodes.length; i++) {
                        var rowNode = nodes[i],
                        row = Ext.fly(rowNode, '_rowExpander'),
                        isCollapsed = row.hasCls('x-grid-row-collapsed');
                        if (isCollapsed)
                            Ext.DomQuery.selectNode('div.x-grid-row-expander', nodes[i]).title = "Expand record";
                        else
                            Ext.DomQuery.selectNode('div.x-grid-row-expander', nodes[i]).title = "Collapse Record";
                    }
                }
            }