text:
Q: A combination of hist and sum:is there a function for that? Lets say we have following vector:
data=a=[2.3 3.2 4.1 6.2 7.3 6.4 5.5 4.3 3.2 2.6 1.7 3.4 4.5 5.7 6.8];

If we count the numbers only by using the hist-function, we get something like that:
[n xout]=hist(a,[1:1:max(a)])

n =

 0     0     2     4     3     1     3     2

xout =
 0     1     2     3     4     5     6     7

What i now want to make is to sum each element of a bin:
xout =
 0     1     2     3     4     5     6     7

n =
 0     0     2     4     3     1     3     2

binsum =
0      0     4    12.4 etc.

for the third bin for example i have n(3)=2 values that are between 1,5 and 2,5 (size of a bin):1.7 and 2.3 -> 1.7+2.3=4 -> binsum(3)=4
for the fourth bin i have n(4)=4 values that are between 2,5 and 3,5:3.2+3.2+3.4+2.6=12.4-> binsum(4)=12.4 etc.
is there a simple function which do this job?

A: If your histogram bins are defined by the array minBin:binWidth:maxBin, then you can find the indices of the bins, and then sum up the data like this:
minBin = 1;
binWidth = 1;
maxBin = 7;

data=[2.3 3.2 4.1 6.2 7.3 6.4 5.5 4.3 3.2 2.6 1.7 3.4 4.5 5.7 6.8];

%# to create index: First, take care of out-of-range data points
tmp = max(min( data, maxBin),minBin);
%# then, subtract minimum, divide by step, round: this is the binIdx
%# add 1 so that we don't start counting at 0
idx = round( (tmp-minBin)/binWidth ) +1;

%# now we can use accumarray to sum up the data
binSum = accumarray(idx(:),data(:),[floor((maxBin-minBin)/binWidth)+1, 1], @sum, 0)

binSum =

         0
    4.0000
   12.4000
    8.4000
    4.5000
   23.8000
   14.1000

Note that I don't get two zeros first, because I use the bins you used as input to hist, not the ones you apparently used to generate the outputs. Also, you can get the counts by replacing data by ones(length(data),1).


text:
Q: What type of Object does Spinner.getItemAtPosition(...) return? What will this statement return?
parent.getItemAtPosition(position)

Where parent is a parent view for a spinner and position is the selected position from the spinner view.

A: I assume the "parent" you are talking about is a Spinner. In this case:
Spinner.getItemAtPosition(pos);

will always return the type of object that you filled the Spinner with.
An example using a CustomType: (the Spinner is filled with Items of type "CustomType", therefore getItemAtPosition(...) will return CustomType)
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
CustomType [] customArray = new CustomType[] { .... your custom items here .... };

// fill an arrayadapter and set it to the spinner
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, customArray);

spinner.setAdapter(adapter);

CustomType type = (CustomType) spinner.getItemAtPosition(0); // it will return your CustomType so you can safely cast to it

Another example using a String Array: (the Spinner is filled with Items of type "String", therefore getItemAtPosition(...) will return String)
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
String[] stringArray= new String[] { "A", "B", "C" };

// fill an arrayadapter and set it to the spinner
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, stringArray);

spinner.setAdapter(adapter);

String item = (String ) spinner.getItemAtPosition(0); // it will return your String so you can safely cast to it

A: It will return object of dataType you are displaying in spinner.
suppose you are displaying String array then it will return String.
if you are displaying Integer array then it will return Integer and so on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to declare and assign a hash with count of occurrences in one statement I'm working on an NLP project for automatic text classification. Here is a snippet of a code to constitute a primitive bag of words from an XML file. But my question is as follows: in this sequence, is it possible to one-line these 3 lines because i don't really enjoy the empty declaration of %lemma_words
my %lemma_words = ();
foreach my $word (lemmatizer(join(" ", keys %bag_of_words))){
    $lemma_words{$word}++;
}

lemmatizer(join(" ", keys %bag_of_words)) is a python function called with Python::Inline and it returns an array. I would like to know if it's possible to declare lemma_words, the hash with lemmatized tokens as keys and occurrences as values within the same line (with a map, an nmap... i don't know. Here is the entire snippet.
The only guideline for this college task is that the script must be written in Perl (the less python code is and better it will be)
#!/usr/bin/perl

use strict;
#use warnings;
use open qw/ :std :encoding(UTF-8)/;

use Inline Python => <<'END_OF_PYTHON';

import spacy
from spacy.lang.fr.stop_words import STOP_WORDS as fr_stop
nlp = spacy.load('fr_core_news_md')

def lemmatizer(words):
    doc = nlp(words)
    return list(filter(lambda x: x not in list(fr_stop), list(map(lambda token: token.lemma_ , doc))))

END_OF_PYTHON

open my $fh, "<:encoding(utf-8)", "sortiexml-slurp_3208.xml" or die "$!";
# first level bag_of_words. We remove only punct and num
my %bag_of_words = ();
while (my $ligne = <$fh>){
    next if $ligne !~ /^<element>/;
    # let's extract form of the token (word) from an xml file
    if ($ligne =~ /<element><data type="type".+>(.+)<.+<\/element>/){
        $bag_of_words{$1}++ if length($1) > 2 and $1 !~ /\d+/;
    }
}

close $fh;

# now it's time to lemmatize words and counter new occurrences of each token lemmatized and we have a primitive bag of words
# to apply it after with Cosine Similarity or Naive Bayes for automatic text classification (example)
# we also remove stop words
my %lemma_words = ();
foreach my $word (lemmatizer(join(" ", keys %bag_of_words))){
    $lemma_words{$word}++;
}

# here it's simply a debug print to check errors
for my $key (keys %lemma_words) {
    print "$key => $lemma_words{$key}\n";
}

A: Can roll it in a subroutine ... or use the ones provided in libraries
For simple and fast element-frequency counter there is List::MoreUtils::frequency
use List::MoreUtils qw(frequency);

my %freq_count = frequency LIST;

The LIST is any dynamically generated list (that lemmatizer(...) here), or an array variable.
If you'd like a possibility to fine-tune what is counted there is count_by in List::UtilsBy
use List::UtilsBy qw(count_by);

my %freq_count = count_by { $_ } LIST;

Again, LIST is any dynamically produced list or an array variable, and in your case that would be lemmatizer(...) (which returns a list).
The frequency count is returned for values to which the code inside the block evaluates; each element in turn is provided in $_. So with lone $_ the count is for elements themselves.
Both List::MoreUtils and List::UtilsBy probably need be installed from CPAN.


text:
Q: 500 error while doing Vargrant Up for http shared box I'm creating a vagrant base box of windows server 2012, and i want to share it internally for which i'm using Vagrant http share with below command
vagrant share --http 80
    C:\Isentia\Vagrant>vagrant share --http 80
==> dev: Detecting network information for machine...
    dev: Local machine address: 169.254.202.14
    dev: Local HTTP port: 80
    dev: Local HTTPS port: disabled
==> dev: Checking authentication and authorization...
==> dev: Creating Vagrant Share session...
    dev: Share will be at: caring-dragon-2751
==> dev: Your Vagrant Share is running! Name: caring-dragon-2751
==> dev: URL: http://caring-dragon-2751.vagrantshare.com

and accessing the box with vagrant up in another machine
    C:\Isentia\DevVM>vagrant init http://caring-dragon-2751.vagrantshare.com:80
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

C:\Isentia\DevVM>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'http://caring-dragon-2751.vagrantshare.com:80' could not be fo
und. Attempting to find and install...
    default: Box Provider: virtualbox
    default: Box Version: >= 0
==> default: Box file was not detected as metadata. Adding it directly...
==> default: Adding box 'http://caring-dragon-2751.vagrantshare.com:80' (v0) for
 provider: virtualbox
    default: Downloading: http://caring-dragon-2751.vagrantshare.com:80
    default: Progress: 0% (Rate: 0curl:/s, Estimated time remaining: --:--:--)
An error occurred while downloading the remote file. The error
message, if any, is reproduced below. Please fix this error and try
again.

The requested URL returned error: 500 Internal Server Error

below is the vagrant file content
Vagrant.configure(2) do |config|
  config.vm.box = "BuzzNumberDevBox"
  config.vm.guest = :windows
  config.vm.communicator = "winrm"
  config.vm.boot_timeout = 600
  config.vm.graceful_halt_timeout = 600
  # Admin user name and password
  config.winrm.username = "vagrant"
  config.winrm.password = "vagrant"
  config.vm.define "dev" do |dev|
    dev.vm.network "private_network", ip: "192.168.100.10"
    dev.vm.host_name = "vagranttests.dev"
    dev.vm.network :forwarded_port, guest: 5985, host: 5985, id: "winrm", auto_correct: true
  end
  config.vm.provider :virtualbox do |vb|
      # Customize the name of VM in VirtualBox manager UI:
      vb.name = "BuzzNumber-Dev-VM-Web"
  end
end

what i do not understand is what could be stopping it from being accessible from any machine. The documentation asked to use the link directly.

A: Vagrant share is designed for sharing access to an application hosted on a VM, NOT for sharing the actual VM. If you want to share the VM itself you need to run vagrant package to pack it, and then put it on a web server with a metadata.json or at a URL where the other user can add it directly. Can you clarify if you want to copy this box to another machine or simply access a service running on the initial vagrant box?


text:
Q: protecting a zip through PHP + SQL Without going in to, too much detail about the rest of the site I have a pretty standard user setup with a users table, id, name, password etc. Some users are "free" users and some have paid through paypal this is set by the "user_premium" table as a 1 or 0.
What I want to do is only allow the download of a zip file if the user has premium. Obviously I can hide the link on my pages if they don't, but they can still access domain.com/myfile.zip directly.
I tried blocking direct access to the zip via htaccess and used fpassthru in a PHP script to get access to the file e.g. (on the fly example code)

if($user->can_download()) {
     $fp = fopen('myfile.zip', 'rb');

     header("Content-Type: application/zip");

     fpassthru($fp);
} else {
     redirect('domain.com/premium.html');
}

However I got memory exhausted errors each time (the file is 4GB).
Is there another way around this?

A: You should look into using Apache mod_xsendfile instead of fopen. With xsendfile, you respond with an HTTP header with the path to the file on your server, which Apache scoops up and serves the file to the user's browser directly, allowing your PHP script to complete execution.
You can find a great guide for getting started with mod_xsendfile here: http://codeutopia.net/blog/2009/03/06/sending-files-better-apache-mod_xsendfile-and-php/

A: From comments in the php doc.

While adding CFLAGS="-D_FILE_OFFSET_BITS=64" immediately before calling "./configure" on the PHP source will enable support for using fopen() on large files (greater than 2 GB), note that -- if such an installation of PHP is used in conjunction with Apache HTTPD [2.x], Apache will become completely unresponsive even when not serving output from a PHP application.
In order to gain large file support for non-web applications while maintaining the operability of Apache, consider making two distinct PHP installations:  one with the above CFLAGS specified during configuration (for non-web uses), and the other without this flag (for use with Apache).


text:
Q: Figure generated with gnuplot-cairolatex is not properly shown when the figures are in a different directory I use gnuplot with the term cairolatex to create and incorporate graphics to my LaTeX projects. This terminal returns two files. One is *.tex and the other one is *.svg.
But I'm having trouble when I try to organize the project into different directories. For instance, I've created a folder \fig for all the figures. To include them, I use the piece of code below.
\begin{figure}[H]
  \centering
  \scalebox{0.55}{\input{project/fig/fig1.tex}}
  \caption{some caption}
  \label{fig:some label}
\end{figure}

But when I do so, even though, when both files are in the directory project/fig/ it seems like just the file *.tex is imported.
I've got something like this:

But I'm expecting this:

It's a bit annoying because sometimes I have to manage several figures.

A: If you look inside the file fig1.tex, you will find a line like this
\put(0,0){\includegraphics{fig1}}%

This means that TeX expects the file fig.svg or fig1.pdf in the current directory, i.e. the directory where your main tex file resides.  However, the file is in project/fig/ directory, so TeX cannot find it.
Try adding the subdirectory to graphicspath:
\graphicspath{{project/fig1/}{another subdirectory}{yet another directory}...}

Another option is directly editing tex files produces by gnuplot to give the explicit location of included graphics files.


text:
Q: Zipline import error. No module named zipline.transforms I am not able to import the zipline.transforms module
>>> from zipline.transforms import batch_transform
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'zipline.transforms'

A: Disclaimer: I'm currently a maintainer of Zipline.
I'm guessing the reason you're seeing this error is because that particular module was removed a while back (assuming you're using zipline 1.0.0 or later). If you want to do things similar to transforms you'll need to call data.history() to get your pricing data, and call numpy/pandas functions like .avg() or .std(), or use talib.

A: I think you should firstly print out your sys.path (print sys.path), and then see where you zipline module is installed (somewhere like  .../lib/python2.7/site-packages/zipline).  Usually "no module named XXX" is caused by you sys.path doesn't contain the path you installed zipline.  You should just add your zipline path into sys.path.  Also use anaconda is good for zipline (http://www.zipline.io/install.html), so as to keep the environment tidy and clean.


text:
Q: Need the "top five "id's" from this query I had someone helping me earlier and have gotten close, What I need to to get the top five "id's" from this query. What is happening is am am getting on one id and not the top five. Anyone know how to correct this? Here is the query:
(
SELECT id,
     firstName,
     lastName,
     SUM(fileSize) AS TotalBytes,
     SUM(fileSize)/COUNT(*) AS Average
FROM   roster_cs368 AS a
JOIN htmp_cs368  AS b USING (id)
) UNION (
SELECT id,
     firstName,
     lastName,
     SUM(fileSize) AS TotalBytes,
     SUM(fileSize)/COUNT(*) AS Average
FROM   roster_cs368 AS a
JOIN atmp_cs368  AS b USING (id)
)
ORDER BY TotalBytes DESC
LIMIT 5

Thank You! This is also part of a larger program, hence the java tag.
Here is the schema:
mysql> select * from roster_cs368
-> ;
+--------+-----------+-----------+
| id     | firstName | lastName  |
+--------+-----------+-----------+
| apn7cf | Allen     | Newton    |
| atggg3 | andrew    | goebel    |

Where is is the primary key,
mysql> select * from htmp_cs368;
+------------+----------+------------+----------+----------+-------+------+-------+----------------------+
| filePerms  | numLinks | id         | idGroup  | fileSize | month | day  | time  | fileName             |
+------------+----------+------------+----------+----------+-------+------+-------+----------------------+
| drwx------ |        2 | schulte    | faculty  |      289 | Nov   |    7 | 2011  | Java                 |
| -rw-r--r-- |        1 | schulte    | faculty  |      136 | Apr   |   29 | 2012  | LD                   |
| drwxr-xr-x |        3 | schulte    | faculty  |      177 | Mar   |   20 | 2012  | Upgrade              |

No primary key here,
mysql> select * from atmp_cs368;
+------------+----------+--------------+----------+----------+-------+------+-------+-----------------------------+
| filePerms  | numLinks | id           | idGroup  | fileSize | month | day  | time  | fileName                    |
+------------+----------+--------------+----------+----------+-------+------+-------+-----------------------------+
| drwxr-xr-x |        2 | remierm      | 203      |      245 | Sep   |   17 | 14:40 | 148360_sun_studio_12        |
| drwx---rwx |       31 | antognolij   | sasl     |     2315 | Oct   |   24 | 12:28 | 275                         |
| -rwx------ |        1 | kyzvdb       | student  |       36 | Sep   |   19 | 13:05 | 275hh                       |

and no primary key here.
What my query is:
produce a list of the five members of roster_cs368,
    and their ids who use the most space (number of bytes)
    in htmp_cs368 and atmp_cs368 in descending order--
    greediest first.  display total number of bytes and
    average size of file

A: You can do it like this:
SELECT * FROM(
(
SELECT id,
     firstName,
     lastName,
     SUM(fileSize) AS TotalBytes,
     SUM(fileSize)/COUNT(*) AS Average
FROM   roster_cs368 AS a
JOIN htmp_cs368  AS b USING (id)
) UNION (
SELECT id,
     firstName,
     lastName,
     SUM(fileSize) AS TotalBytes,
     SUM(fileSize)/COUNT(*) AS Average
FROM   roster_cs368 AS a
JOIN atmp_cs368  AS b USING (id)
)
) as somealias ORDER BY TotalBytes DESC
LIMIT 5


text:
Q: Using InterfaceBuilder ONLY for positioning objects on the view Have created a UIButton programmatically, all works as expected but how can I use the IB ONLY for positioning the objects on the view?
To be more precise I like to use the IB for this line only (see: setViaIB)
 self.searchBtn.frame = CGRectMake(setViaIB, setViaIB, 36, 36);

Full code for UIButton creation:
 self.searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
 self.searchBtn.frame = CGRectMake(100, 0, 36, 36);
[self.searchBtn setBackgroundImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];
[self.searchBtn addTarget:self action:@selector(searchBtnTapped::) forControlEvents:UIControlEventTouchUpInside];
[self.searchBtn setNeedsDisplay];
[self.view addSubview:self.searchBtn];

A: You can only position the button in IB if you created it in IB. You can change searchBtnTapped method to an IBAction and link it up to your button via files owner in IB. You can then move the button wherever you want in IB. If not you will just have to reposition the button via coordinates until you are happy.

A: I'm pretty sure you can't, why don't you use initWithNibName: bundle: to create the whole view in an nib (Interface Builder) file?


text:
Q: Why can't I read the input text file? I try to read the name of a file using scanf but failed.
I am very bad at pointers and could not find the problem.
Is there a problem with the pointer to the array of string?
Here is my code:
int* Read_file(char* str[])
{
    FILE* fp = fopen(str[1], "r");
    if(fp == NULL)
    {
        printf("File cannot open\n");
        return NULL;
    }
    int rows = 0;
    while(!feof(fp))
    {
        if(fgetc(fp) == '\n')
        {
            rows ++;
        }
    }
    rows ++;
    int* keys = (int*)malloc(3 * rows * sizeof(int));
    fseek(fp, 0L, 0);
    while(!feof(fp))
    {
        for(int i = 0;i < rows;i ++)
        {
            for(int j = 0;j < 3;j ++)
            {
                fscanf(fp,"%d", &keys[(3 * i) + j]);
            }
        }
    }
    fclose(fp);
    return keys;
}
int main()
{
    char* str[20];
    printf("Build_tree ");
    scanf("%s",&str);
    int* keys = Read_file(str);
    return 0;
}

A: Okay, so the thing is:
You need a char array to store a string(file-name). So you should use a char array. Instead, you were using an array of char pointers.
An array is actually a series of memory blocks. The name of the array represents a pointer to the first element of the array(in this case the first char variable).
While reading a string, scanf needs a location to store it. So you need to give it the address of the first char variable of your char array, which is available in your char array itself. So you have to pass str only to scanf. In the case of normal int,float, and such fundamental data types, their names represent memory blocks and not pointers to memory blocks, and hence you had to use a &.
Then for fopen, fopen expects a char*(which points to the first character of the char array stoing the filename) and you have to provide it with a char* . So you should pass str.
I think your code should go like
int* Read_file(char str[])
{
    FILE* fp = fopen(str, "r");
    if(fp == NULL)
    {
        printf("File cannot open\n");
        return NULL;
    }
    int rows = 0;
    while(!feof(fp))
    {
        if(fgetc(fp) == '\n')
        {
            rows ++;
        }
    }
    rows ++;
    int* keys = (int*)malloc(3 * rows * sizeof(int));
    fseek(fp, 0L, 0);
    while(!feof(fp))
    {
        for(int i = 0;i < rows;i ++)
        {
            for(int j = 0;j < 3;j ++)
            {
                fscanf(fp,"%d", &keys[(3 * i) + j]);
            }
        }
    }
    fclose(fp);
    return keys;
}
int main()
{
    char str[20];
    printf("Build_tree ");
    scanf("%s",str);
    int* keys = Read_file(str);

    //Whatever you want to do with the keys

    return 0;
}

Comment for any queries.


text:
Q: Spring JPA specification like number field I have a table named Citizen:
public class Citizen {
    private Long id;
    private String name;
    private Long code;

    //get,set
}

I used Specification for searching Citizen with filter:
public class CitizenFilter(){
    private String name;
    private Long code;

    // get, set
}

public class CitizenSpecification implements Specification<Citizen>{
    private CitizenFilter filter;
    // get, set

    @Override
    public Predicate toPredicate(Root<Citizen> root, CriteriaQuery<?> query, CriteriaBuilder builder)
    {
        List<Predicate> restrictions = new ArrayList<>();
        if(filter.getName != null){
            restrictions.add(builder.like(root.get("name"), "%"+filter.getName()+"%"));
        }
        if(filter.getCode != null){
            restrictions.add(builder.like(root.get("code"), "%"+filter.getCode ()+"%"));
        }
        // disjunction().....
        // return expression
    }
}

When I call the API, it throws exception that: Parameter did not match with type java.lang.Long
I know this error since I tried to use like with a number field.
I have 2 questions:

*

*How can native query do this like query on number field but JPA query ?

*If there is a way I can do this with JPA, please help me !
Thank you in advanced

A: LIKE on a number column is not possible.
This works with some Databases because the cast the number to a VARCHAR when you execute the statement.
To do this with Criteria API you must cast the number to a string like this:
restrictions.add(builder.like(root.get("name").as(String.class), "%"+filter.getCode ()+"%"));


text:
Q: Problems with compiling I am pretty new to this here but i hope to learn quick. Anyways, i am trying to install a open source software but i get an error when trying to build it.
it says
:~$ ~/trunk/src/autogen.sh

Preparing the Delft3D build system...please wait
Found GNU Autoconf version 2.69
Found GNU Automake version 1.14.1
Found GNU Libtool version 2.4.2
grep: Makefile.am: No such file or directory
grep: Makefile.am: No such file or directory
Automatically preparing build ... Warning: autoreconf failed
Attempting to run the preparation steps individually
Preparing build ... ERROR: aclocal failed
what is wrong??

A: It seems your autoconf and automake packages are not up to date, did you try to update them? if not, you may run:
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get upgrade

and afterwards if your problem is still unsolved try to install autoconf and automake again:
sudo apt-get install automake
sudo apt-get install autoconf


text:
Q: URL , Scanner & Delimiter : How does this Java Line of Code Works? Can anyone help me  understand how does this line of code works:
String s = new Scanner(new URL("http://example.com").openStream(), "UTF-8").useDelimiter("\\A").next();

The code is used to directly read from the webpage.
How exactly is the scanner object converted to a string and why we use delimiter.
Thanks.

A: Adding to Kuzeko's answer, \A matches the beginning of the entire text. So, I don't think his 'hello world' example is valid.

A: Scanner is not "converted". On the freshly created instance, useDelimiter is called, which returns a Scanner instance with the delimiter property set accordingly, then on that instance next is called which returns a String.
You may want to lookup Scanner in Java Doc for further reading:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

A: Here is what happens, with abuse of  indentations
     new Scanner(                           // A new scanner is created
             new URL("http://example.com")  // the scanner takes a Stream
                                            // which is obtained from a URL
          .openStream(),                    // - openStream returns the stream
       "UTF-8")                             // Now the scanner can parse the
                                            // stream character by character
                                            // with UTF-8 encoding

     .useDelimiter("\\A")                   // Now the scanner set as
                                            // delimiter the [Regexp for \A][1]
                                            // \A stands for :start of a string!

   .next();                                 // Here it returns the first(next)
                                            // token that is before another
                                            // start of string.
                                            // Which, I'm not sure
                                            // what it will be

From the Java documentation

A simple text scanner which can parse primitive types and strings using regular expressions.
  A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

So you just replaced \A as delimiter (instead of  whitespace).
BUT \A has a specific meaning when evaluating as regular expression!
If your stream contains only the following text
\Ahello world!\A Goodbye!\A
Your code will return the entire line \Ahello world!\A Goodbye!\A
If you wanted to strip on the sequence of a backslash followed by a upper case A, then you should use \\\\A.
Thanks to @Faux Pas to point out that!


text:
Q: Catch the problematic line in JSF-page-debugging? I get an exception of
SEVERE: Error Rendering View[/consult_carto.xhtml]
java.lang.IllegalArgumentException

Now I can't solve it yet, so I thought I might debug the JSF page and I went on to find that the <ui:debug /> helps with that, tried it just to find that it doesn't give much information.
My Question is : is it possible to know which line throws the exeption in a JSF page ? If so, how do we do that ?
Thanks.
Links : used this one :  tag not working in Facelets (JSF 2.0) (and it works fine).


text:
Q: python 3.5.1 sorting of multivariate Tuples using 2 sorts and the operator module fn I'm working through 3.5.1 Python and I'm working through basic Tuples. I expanded the basic tuple array by 1 additional variable and I wanted to sort the program by name and then grade.
My code is:
l1 = [('lee', 'a', 5, 38), ('kim', 'b', 3, 28), ('jung', 'b', 10, 36)]

sortedl1 = l1.sort(l1, key=itemgetter(0,1))

print ('sorted by name: ', sortedl1)

When I run the code, I get a compiler error of:
sortedl1 = l1.sort(l1, key=itemgetter(0,1))
TypeError: Argument given by name ('key') and position (1)

Any help would be appreciated. Thanks.

A: I think you meant to use sorted:
sortedl1 = sorted(l1, key=itemgetter(0,1))

because

*

*list.sort does not return unlike sorted, but just sort the list in-place.

*list.sort does not accept positional argument.


text:
Q: add CSS animation to a website with background picture The question is very silly but I've never created a webpage so please do not immediately downvote. AND please don't tell me to watch totorials, I really need to do something like described below only once. For some reasons, I need to make a really simple webpage, containing only a background picture and a CSS3 heart animation I found around. I need the CSS heart animation to be postioned on the left corner with a 100px margin from bottom, overlaying the other image I use as background What do I need to add to HTML to achieve that?
my HTML
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Test page</title>
   </style>

And the CSS I'm trying to use
SO has very poor CSS formatting so I added the CSS code to pastebin.
Please note that I never worked with CSS and need a detailed explanation. Thanks.

A: Create a

and style it with
#bigwrapper{
   width:100%;
   height:100%:
}

and the picture of your heart in there. After that, apply the needed CSS
The HTML markup needs work, because without properly formatted tags, several things may not work. You need to open and close tags properly.

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Test page</title>

The center tag has been deprecated in HTML5, and the transitions you are using only work with HTML5 and CSS3.


text:
Q: Aframe + vuejs - core:schema:warn Unknown property `color` for component/system `undefined`. +10ms aframe.js:327 I'm trying to get Aframe and vuejs to work well with each other, however the console is returning warning messages. I'm guessing this is due to aframe checking the attribute values before vue gets a chance to change them.
Warning messages
core:schema:warn Unknown property `color` for component/system `undefined`. +349ms 2aframe.js:327
core:schema:warn Unknown property `color` for component/system `undefined`. +2ms aframe.js:327
core:schema:warn Unknown property `color` for component/system `undefined`. +1ms aframe.js:327
core:schema:warn Unknown property `height` for component/system `undefined`. +1ms aframe.js:327
core:schema:warn Unknown property `color` for component/system `undefined`. +1s aframe.js:327

Here is the code:
App.vue
<template>

        <test-component v-for="block in blocks" :color="block.color" :position="block.pos"></test-component>

</template>

TestComponent.vue
<template lang="html">

</template>

index.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>aframetest</title>

main.js
import Vue from 'vue'
import App from './App.vue'

new Vue({
  el: '#app',
  render: h => h(App)
})

A: working code with simpler setup:
( vuejs 2.4.4 + aframe 0.6.1 )
https://jsfiddle.net/jg6uhh21/
html:

  <test-component v-for="block in blocks" :color="block.color" :position="block.pos"></test-component>

javascript:
Vue.component('test-component', {
  props: ['color','position'],
  template: `<a-box :color="color" :position="position"></a-box>`
})
new Vue({
  el: '#app',
  data(){
    return {
      blocks: [
        {color: 'red', pos: "1 0 0"},
        {color: 'orange', pos: "2 0 0"},
        {color: 'yellow', pos: "3 0 0"}
      ]
    }
  },
  mounted(){
    setTimeout(() => {
      this.blocks.push({color: 'lime', pos: "4 0 0"})
    }, 1000)
    setTimeout(() =>{
      this.blocks[3].pos = "5 0 0"
    }, 2000)
  }
})

small interactive demo I build combining vue.js and aframe in the same way:
https://rawgit.com/frederic-schwarz/aframe-vuejs-3dio/master/index.html
https://github.com/frederic-schwarz/aframe-vuejs-3dio/blob/master/index.html

A: I was looking for an answer to this same issue and I game across this demo on GitHub
The part that I was missing was
Vue.config.ignoredElements = [
  'a-scene',
  'a-entity',
  'a-camera',
  'a-box'
]

I'm a little new to Vue and I had no idea that Vue.config.ignoredElements existed. I added this to my main.js and added all the aframe primitives that I'm using.


text:
Q: (MDX) how to use current member name as another column? Example MDX query from https://quartetfs.com/resource-center/mdx-query-basics:
SELECT
NON EMPTY {[ASIN].[ASIN].Members} ON ROWS,
NON EMPTY {[Category].[Category].[LCD]} ON COLUMNS
FROM [Amazon]
WHERE ( [Measures].[Gross.Profit],
        [Time].[ALL].[AllMember].[2011].[5],
        [Brand].[Brand].[LG])

How could one repeat the ASIN field (pink column) in another column?
I tried adding [ASIN].[ASIN] to ON COLUMNS expression
SELECT
NON EMPTY {[ASIN].[ASIN].Members} ON ROWS,
NON EMPTY {[Category].[Category].[LCD],[ASIN].[ASIN]} ON COLUMNS
FROM [Amazon]
WHERE ( [Measures].[Gross.Profit],
        [Time].[ALL].[AllMember].[2011].[5],
        [Brand].[Brand].[LG])

Which resulted in Two sets specified in the  function have different dimensionality. Adding .CurrentMember resulted in the same error.
I tried adding ASIN property through new measure:
MEMBER Measures.ASIN AS [ASIN].[ASIN].CurrentMember
SELECT
NON EMPTY {[ASIN].[ASIN].Members} ON ROWS,
NON EMPTY {[Category].[Category].[LCD],Measures.ASIN} ON COLUMNS
FROM [Amazon]
WHERE ( [Measures].[Gross.Profit],
        [Time].[ALL].[AllMember].[2011].[5],
        [Brand].[Brand].[LG])

Which adds a new column with null values.

What I want to see is:
______________LCD________ASIN__________
B003D4WAVW      124,420.16      B003D4WAVW
...
Is there a way to achieve this?

A: Try this one:
MEMBER Measures.ASIN AS [ASIN].[ASIN].CurrentMember.Member_Name
MEMBER Measures.LCD AS ([Category].[Category].[LCD],[Measures].[Gross.Profit])
SELECT
NON EMPTY {[ASIN].[ASIN].Members} ON ROWS,
NON EMPTY {[Measures].[LCD],[Measures].[ASIN]} ON COLUMNS
FROM [Amazon]
WHERE ( [Time].[ALL].[AllMember].[2011].[5],
        [Brand].[Brand].[LG])

You tried to use dimension and measure member on the same axis. I've transformed this into two measures.
Tested on my own data:


text:
Q: Issue with implementing phong reflectance in glsl fragment shader I've written a fragment shader that shades a sphere using ray tracing.I'm now trying to implement the phong model for specular reflectance which uses one equation: R = 2 (N • L) N - L where L is the light direction and N is the surface normal. The value of reflection vector R is then plugged into:                  s_rgb max(0, E • R)^p where E is the eye direction of the viewer (in this case it is -w or the negative direction of the ray), p is the specular power and s_rgb is the color of the specular reflection. In my current implementation of the function used to determine the color of the sphere, I'm getting errors with the max and power functions. Here is the code for the function:
vec3 shadeSphere(vec3 point, vec4 sphere, vec3 material,vec3 eyeDir) {
      vec3 color = vec3(1.,2.,4.);
      vec3 N = (point - sphere.xyz) / sphere.w;
      float diffuse = max(dot(Ldir, N), 0.0);
      vec3 ambient = material/5.0;
      vec3 R = 2.*(dot(N, Ldir))*(N - Ldir);
      float reflect = max(0.0,dot(eyeDir,R));
      float phong= pow(reflect, 2);
      color = phong + ambient + Lrgb  *diffuse *  max(0.0, dot(N , Ldir));
      return color;
   }

For some reason, the pow() function is returning the error
ERROR: 0:49: 'pow' : no matching overloaded function found```
I think that the second parameter of the max function might be causing the problem but it seems like it should work. Can anyone spot the problem with the function?

A: It kinda looks like you're just missing the dot.  "There's no overload" for pow that takes a float with an int.
float phong= pow(reflect, 2);   // nope
float phong= pow(reflect, 2.);  // ok


text:
Q: Gson serialize to LinkedTreeMap instead of my Entity I'm trying to consume a REST service in an Android application, but am having problems in serializing an ArrayList:
My RESTful service returns:

My Android application receives:

I'm using Gson library for serialization of my objects and certainly the problem is related to it. In this sense I tried to make Serializer as follows:
public class MySerializer<E>
    implements JsonSerializer<Collection<E>>, JsonDeserializer<Collection<E>> {

    @Override
    public Collection<E> deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
        Type type = new TypeToken<List<E>>(){}.getType();
        return context.deserialize(json, type);
    }
    @Override
    public JsonElement serialize(Collection<E> src, Type typeOfSrc,
        JsonSerializationContext context) {
        Type type = new TypeToken<List<E>>(){}.getType();
        return context.serialize(src, type);
    }
}

Registered the apapter (registerTypeAdapter(ArrayList.class, new MySerializer<Object>())), but this not work...
Could anyone help me please?

A: Can you please try to change the gradle version to an updated version and check whether the issue is resolved.
I too had the same issue and it got resolved when I changed the gradle version from 1.5.0 to 2.1.0


text:
Q: MAX(Date) Query running very slow - MySQL The below query is running very slow as the table is very huge and I just want to select a max of date form the table, I have some id1,id2, and date column as PK. Any trick to fetch it faster?
SELECT DATE_FORMAT(DATE_SUB(MAX(Date), INTERVAL 2 DAY), "%Y-%m-%d %H:00")
FROM mytable.

Thanks in advance.
Regards,
Vijay

A: In order for your query to be fast on a huge table (as you mention) you'll need to create an index on the specific column. For example:
create index ix1 on mytable (Date);

Also, avoid naming columns with reserved words such as Date. It'll make your queries more complicated.


text:
Q: Fraction as sum of fractions with prime power denominators Given any fraction $\frac{s}{t}=\frac{s}{\Pi_pp^{i_p}}$ with $s,t$ relatively prime, I would like to know if it is possible to write $\frac{s}{\Pi_pp^{i_p}}=\sum_p\frac{s_p}{p^{i_p}}$ for some unique integers $s_p$.
It seems like this is a simple algebraic fact, but I'm not totally sure how to prove it, especially the uniqueness part. The furthest that I've gotten is that for all nonzero $i_p$ we must have $s_p$ nonzero, because otherwise $s$ would be divisible by that $p$, contradicting that $t$ and $s$ are relatively prime.
I guess an equivalent question would be to ask for solutions to some finite equation $\sum_i a_ix_i=a$ where $\text{gcd}(a,\{a_i\})=1$.

A: No, this is not true. We can consider the simple case where $t=pq$ where $p,q$ are distinct primes, and $s=1$. Here, we choose $s_p, s_q$ to satisfy $ps_q + qs_p=1$, and such $s_p, s_q$ exist per Bezout's identity. Then observe that
$$\frac{s_p}{p} + \frac{s_q}{q} = \frac{qs_p + ps_q}{pq} = \frac{1}{pq} = \frac{s}{t}$$
In general, numerous $s_q, s_p$ can be found which satisfy $ps_q + qs_p=1$. For instance, take $s_p'=s_p-pk$, $s_q' = s_q+qk$ where $k$ is an arbitrary integer, so that $ps_q' + qs_p' = p(s_q+qk) + q(s_p-pk)=ps_q + qs_p = 1$.


text:
Q: API to get artifacts created in last 24 Hrs I know JFrog provides APIs to fetch the artifacts info like latest build etc.
Can some one help by telling if JFrog provides an API to fetch the artifacts created/promoted in last 24 hr / last month etc.
Would like to pull all the artifacts updated in last one month for audit purpose.

A: You can achieve this functionality using AQL (Artifactory Query Language) and JFrog CLI.

*

*Build an AQL query using RelativeTimeOperators ({"$last" : "30d"} for example).

*Create a file spec with the "aql" field.

*Use the download command of the CLI and provide the file spec you created with the --spec flag to download the files.

If you'd like to just get a list of artifacts, you can use the search command.


text:
Q: Translation: Multiple websites, multiple languages I'm building a store for a client, and this is the first time I'm working with multiple websites AND multiple languages.
I'm a bit uncertain how to handle the translation aspect. My store structure is similiar to:
WEBSITE 1
   - English
   - German

Website 2
   - English
   - German

Of course with stores set up for each website as well, but in order to keep it simple, this is the basics.
Now, each website has set the correct locale, so they're using the same basic translation for the UI and common terms.
My questions are:
Firstly, where does Magento save product translations and the like? We don't want to have to translate products separately for english and german, for each website, as there will be quite a few down the line.
Secondly, do I need to do anything other than set locale, to make sure that product texts in german are translated in both Website 1->German and Website 2->German?
I can copy values when creating the product, but what happens when the product is edited? Are they also copied, dynamically?
This is a bit basic, but I'd like to be reasonably certain of the mechanics before we start adding hundreds of products to dozens of stores. :)
Regards

A:
Firstly, where does Magento save product translations and the like? We don't want to have to translate products separately for english and german, for each website, as there will be quite a few down the line.

Unfortunately those are saved by store view and not associated to a language at all. The best advice here is, to not manage your products in Magento but use an external product management software (PIM) that can export to Magento. Most shops with a significant amount of products import the product data from another system because managing them in Magento is not really a pleasure.

Secondly, do I need to do anything other than set locale, to make sure that product texts in german are translated in both Website 1->German and Website 2->German? I can copy values when creating the product, but what happens when the product is edited? Are they also copied, dynamically?

See above. Product attributes are not translated, you can only define different values for each store view.

A: Firstly, where does Magento save product translations and the like? We don't want to have to translate products separately for english and german, for each website, as there will be quite a few down the line.
While Magento keeps product translations in separate stores, each store representing a language, most users would find it much easier and simpler to manage translations in a PIM solution, such as Bluestone PIM (we have easy-to-use translation UI for that).
Our extension also will soon support multiple stores sync for languages, and will sync each language into separate stores in Magento.
Secondly, do I need to do anything other than set locale, to make sure that product texts in german are translated in both Website 1->German and Website 2->German? I can copy values when creating the product, but what happens when the product is edited? Are they also copied, dynamically?
Setting the fallback language would help here, which means that if the translation is missing in some value, the value will be fetched from the set fallback language. You won't need to copy value, you can just use the translation you prefer. I assume you would need to implement PIM for such functionality. In Bluestone PIM, when you finish updating the data, it is enough just to select 'Sync to Magento'.


text:
Q: What exactly does "closing over" mean? In conjunction with closures I often read that something closes over something else as a means to explain closures.
Now I don't have much difficulty understanding closures, but "closing over" appears to be a more fundamental concept. Otherwise one would not refer to it to explain closures, would one?
What is the exact definition of closing over, and what is the something and the something else? Where does the term come from?

A: Consider:
something closes over something else
|_______| |_________| |____________|
    |          |             |
 subject      verb        object

Here:

*

*The subject is the closure. A closure is a function.

*The closure "closes over" (as in encloses) the set of its free variables.

*The object is the set of the free variables of the closure.

Consider a simple function:
function add(x) {
    return function closure(y) {
        return x + y;
    };
}

Here:

*

*The function named add has only one variable, named x, which is not a free variable because it is defined within the scope of add itself.

*The function named closure has two variables, named x and y, out of which x is a free variable because it is defined in the scope of add (not closure) and y is not a free variable because it is defined in the scope of closure itself.

Hence, in the second case the function named closure is said to "close over" the variable named x.
Therefore:

*

*The function named closure is said to be a closure of the variable named x.

*The variable named x is said to be an upvalue of the function named closure.

That's all there is to it.


text:
Q: Can't upgrade compileSdkVersion 28 to 29 because of dependencies issue My app was created many years ago. Maybe 2016. Now I make some changes to my app. But when I tried to publish my app to my play console, it told me to upgrade the compileSdkVersion and target SDK version to 29. I change to version 28 to 29 and now there are lots of dependency issues like, could not resolve some dependencies, migrate to androidx, and lots more. I converted my app to androidx via android studio and upgraded all/some dependencies but it did not work and my app crashed. I searched all of those individual issues and implement those solutions but my app is still crashed. what can I do now? Can anyone help me to solve this? It is really needed for me. can anyone suggest to me any fix for this issue?
buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
        maven { url 'https://plugins.gradle.org/m2/'}

    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.4, 0.99.99]'
    }
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
repositories {
    maven {
        url 'https://maven.fabric.io/public'
    }
    maven {
        url "https://adcolony.bintray.com/AdColony"
    }
    maven {
        url 'http://swisscodemonkeys.github.io/appbrain-sdk/maven'
    }
    maven {
        name "Fyber's maven repo"
        url "https://fyber.bintray.com/maven"
    }
    maven {
        url "https://maven.google.com"
    }
}
android {
    compileSdkVersion 28
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "____________"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 25
        versionName "4.1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
        manifestPlaceholders = [.......]
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'android.arch.navigation:navigation-fragment:1.0.0'
    implementation 'android.arch.navigation:navigation-ui:1.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation "com.android.support:design:28.0.0"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    implementation 'com.google.android.gms:play-services:12.0.1'
    implementation 'com.google.android.gms:play-services-ads:10.2.1'
    implementation 'com.android.support:multidex:1.0.1'
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    implementation 'uk.co.chrisjenx:calligraphy:2.3.0'
    implementation 'com.squareup.picasso:picasso:2.3.2'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.google.code.gson:gson:2.6.2'
    implementation 'com.android.volley:volley:1.1.0'
    implementation 'io.paperdb:paperdb:2.0'
    implementation 'com.onesignal:OneSignal:3.+@aar'
    implementation 'com.google.android.gms:play-services-gcm:10.2.1'
    implementation 'com.google.android.gms:play-services-location:10.2.1'
    implementation 'com.google.android.gms:play-services-auth:11.4.2'
    implementation('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true;
    }
    implementation 'com.adcolony:sdk:3.2.1'
    implementation project(':SDKAndroid')
    implementation 'com.appbrain:appbrain-sdk:+@aar'
    implementation 'com.github.vungle:vungle-android-sdk:5.3.2'
    implementation 'com.fyber:fyber-sdk:8.20.0'
    implementation "com.android.support:support-core-utils:28.0.0"
    implementation 'pub.devrel:easypermissions:0.3.0'
    implementation('com.google.api-client:google-api-client-android:1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    implementation('com.google.apis:google-api-services-youtube:v3-rev186-1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    implementation 'org.jsoup:jsoup:1.12.1'
    implementation 'com.facebook.android:audience-network-sdk:5.+'
    implementation "com.android.support:support-core-utils:28.0.0"
}
configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '25.3.0'
            }
        }
    }
}
apply plugin: 'com.google.gms.google-services'

this is the error log:
13533-13533/<Package Name> E/AndroidRuntime: FATAL EXCEPTION: main
    Process: <Package Name>, PID: 13533
    java.lang.RuntimeException: Unable to start activity ComponentInfo{<Package Name>/<Package Name>.MainActivity}: android.view.InflateException: Binary XML file line #17 in <Package Name>:layout/abc_screen_simple: Binary XML file line #17 in <Package Name>:layout/abc_screen_simple: Error inflating class androidx.appcompat.widget.FitWindowsLinearLayout
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: android.view.InflateException: Binary XML file line #17 in <Package Name>:layout/abc_screen_simple: Binary XML file line #17 in <Package Name>:layout/abc_screen_simple: Error inflating class androidx.appcompat.widget.FitWindowsLinearLayout
     Caused by: android.view.InflateException: Binary XML file line #17 in <Package Name>:layout/abc_screen_simple: Error inflating class androidx.appcompat.widget.FitWindowsLinearLayout
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Field.get(java.lang.Object)' on a null object reference
        at uk.co.chrisjenx.calligraphy.ReflectionUtils.getValue(ReflectionUtils.java:29)
        at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.createCustomViewInternal(CalligraphyLayoutInflater.java:203)
        at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.access$000(CalligraphyLayoutInflater.java:20)
        at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:302)
        at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:239)
        at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1069)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:997)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:659)
        at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
        at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:631)
        at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:518)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:466)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at <Package Name>.MainActivity.onCreate(MainActivity.java:105)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 2021-04-12 12:24:40.753 13533-13533/<Package Name> E/AndroidRuntime:     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 2021-04-12 12:24:40.849 13533-13533/<Package Name> E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{<Package Name>/<Package Name>.MainActivity}: android.view.InflateException: Binary XML file line #17 in <Package Name>:layout/abc_screen_simple: Binary XML file line #17 in <Package Name>:layout/abc_screen_simple: Error inflating class androidx.appcompat.widget.FitWindowsLinearLayout
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: android.view.InflateException: Binary XML file line #17 in <Package Name>:layout/abc_screen_simple: Binary XML file line #17 in <Package Name>:layout/abc_screen_simple: Error inflating class androidx.appcompat.widget.FitWindowsLinearLayout
     Caused by: android.view.InflateException: Binary XML file line #17 in <Package Name>:layout/abc_screen_simple: Error inflating class androidx.appcompat.widget.FitWindowsLinearLayout
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Field.get(java.lang.Object)' on a null object reference
        at uk.co.chrisjenx.calligraphy.ReflectionUtils.getValue(ReflectionUtils.java:29)
        at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.createCustomViewInternal(CalligraphyLayoutInflater.java:203)
        at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.access$000(CalligraphyLayoutInflater.java:20)
        at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:302)
        at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:239)
        at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1069)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:997)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:659)
        at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
        at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:631)
        at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:518)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:466)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at <Package Name>.MainActivity.onCreate(MainActivity.java:105)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 2021-04-12 12:24:40.850 13533-13533/<Package Name> E/UncaughtException:     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 2021-04-12 12:24:41.880 13533-13664/<Package Name> E/FirebaseCrash: Unable to parse Json response string to get message: No value for crashes


text:
Q: Error with encoding Code:
SELECT
       ta_name,
       countt,
       ta_unit,
       ta_id_producer_goods
FROM (
    SELECT  ta.name AS ta_name,
        ta.unit  AS ta_unit,
        ta.id_producer_goods AS ta_id_producer_goods,
        count(*) over(partition by ta.name) as countt,
        ROW_NUMBER() over(partition by ta.name order by getdate()) as r
    FROM  Table ta
    WHERE  id_city = '24'
       AND id_firm = '22131'
       AND id_service = '5'
) x
WHERE r=1

When I run the above query in SQL Server Management Studio, I get this result:

Why do I get results in bad encoding and how do I get the right encoding ?

A: Manage your collation by:
SELECT SERVERPROPERTY('Collation')

A: You can get the default collaction by:
SELECT SERVERPROPERTY('Collation')


text:
Q: Virtual Ground Paradox? I'm unable to come to terms with something I think is a paradoxical situation relating to the virtual ground of an Operational Amplifier.Please pardon me if this is a really stupid question.
When the 'Negative Feedback' in an Op-Amp (Ideal) makes the difference between its input terminals equal to 'Zero'. Shouldn't the output become zero too because the Op-Amp is fundamentally a Differential Amplifier and according to the equation:
Vo = (Open loop gain)*(Differential voltage b/w the inputs)

The Explanations I've come up with so far are:-
1) The Op-Amp Output is indeed zero and it is the External Circuitry
 (consisting of resistors Rf and Rin) that create the voltage, which adds up to the Op-Amp output voltage (in this case Zero) at point B to create the actual output of the system.
2) The virtual ground is not perfect and there exists a very very small differential voltage at the input which gets multiplied by the very high gain and produces the output.
I'm fundamentally unable to understand how the actual definition of Op-Amp behavior is consistent with the virtual ground phenomenon without making the output zero.   Please Help!

A: The problem is that you mix-up two different models of the op-amp.
A real, but somewhat idealized op-amp, is a differential amplifier whose output depends on the inputs as follows (neglecting saturation):
$$
V_{out} = A_{Vol} \cdot (V^+ - V^-)
$$
Using this simplified model (simplified because it neglects saturation, offset voltage, bias currents, bandwidth and other real-world effects) and the fact that \$A_{Vol}\$ (open loop gain) is huge, you can prove that, when the op-amp is connected in a negative feedback circuit, then the virtual short circuit holds, but only when you approximate \$A_{Vol}\$ as infinite.
With this drastic approximation you can have a zero differential input AND still a finite output, since the open loop gain is assumed infinite.
In reality the open loop gain isn't infinite and your finite output is due to a very small differential input (in the μV range, usually). Multiply that small differential input by the actual open loop gain and you have your finite output.
Using the virtual short circuit, is much simpler, though. Once you realize that an op-amp circuit has negative feedback, you can use the virtual short circuit idealization (\$V^+ = V^-\$) to analyze how the circuit works, without bothering with the actual value of the differential input, which becomes irrelevant (unless you need the finer details), as long as you avoid output saturation.

A: Let's just do the WHOLE shebang, start to finish, instead of doing this piecemeal.  Let's start with the definition for the op amp.
$$ V_{out}= A_{OL}(V_+ - V_-)$$
As has been pointed out, \$A_{OL}\$ is a very big number, but let's leave it in place for the time being.
Just converting this into the notation in the original figure,
$$ V_{B}= A_{OL}(0 - V_A)$$
$$ V_B=-V_AA_{OL}$$
Now, we can start applying Kirchoff's Current Law.
$$\frac{V_{in}-V_A}{R_{in}}= \frac{V_A-V_B}{R_f}$$
$$\frac{R_f}{R_{in}}(V_{in}-V_A)=V_A-V_B$$
$$ V_B=V_A - \frac{R_f}{R_{in}}(V_{in}-V_A)$$
$$ V_B  = V_A \left(  1 + \frac{R_f}{R_{in}} \right)- \frac{R_f}{R_{in}}V_{in}$$
Now, we can substitute in for \$V_A\$, based on the definition of the op amp
$$ V_B  = -\frac{V_B}{A_{OL}} \left(  1 + \frac{R_f}{R_{in}} \right)- \frac{R_f}{R_{in}}V_{in}$$
Lastly, now we can apply \$A_{OL}\to\infty  \$ , which makes the first term go to zero.
$$\lim_{A_{OL}\to\infty} V_B = - \frac{R_f}{R_{in}}V_{in}$$
This is your standard inverting amplifier equation.  Also, note that \$V_A=-\frac{V_B}{A_{OL}}=0\$, leaving us with a "virtual ground" at the inverting input. Thus, there is no paradox.  The virtual ground concept is entirely consistent with an infinite open loop gain op amp in a negative feedback arrangement.  For giggles, try the same exercise in positive feedback, and watch it explode.
Carrying these things through without throwing out terms due to assumptions also shows you where errors are likely to crop up.  For example, you can see from the equation before taking the limit that if you're asking for obscene gain, and \$R_f\$ is many orders of magnitude larger than \$R_{in}\$ that things may not work out so well.

A: Math-wise, you can think of it like this:
0 * infinity (which is the ideal op-amp assumption) isn't 0, it's an indeterminate form.
To be fully rigorous, you'd be taking the limit as the gain approaches infinity (and the input difference approaches zero).
If you went to the trouble of doing all that (it's a pain so in practice nobody bothers, except maybe when a prof is introducing the idea), you'd see the value is determined by the surrounding circuity.

A: It's #2.  For a "perfect" theoretical opamp, the open-loop gain is infinite, and this makes the difference at the inputs zero. When introducing opamp circuits, or when working out how things are supposed to work, people normally think about the "perfect" opamp.
When thinking about the performance of a circuit, we usually have to start thinking about the imperfections of a real opamp. For a real opamp, the open-loop gain is not infinite, and there is some difference between the inputs. To take the example of an LM324, the open loop gain is about 115dB. That's a little less than a million volts/volt, so if there is a 1V DC output, then the inputs are different by about 1uV.  Most of the time you can ignore that.
It gets more complicated for AC. At higher frequencies, the gain drops. For the LM324, it goes to 0dB, i.e. 1V/V at about 1MHz.  At that point, the inputs certainly will have a large difference.  Practically speaking, the amplifier just doesn't work any more.  For frequencies in-between, the gain of the amplifier (inc. feedback) will vary. The term "Gain Bandwidth Product" is used to describe what gain you can have at what frequency for a given opamp.
This is just one of many imperfections a real opamp has.  Another very relevant one is input offset voltage. This is the difference in inputs which results in a zero output, and it's not always exactly 0.  This might be more important than the limited gain in many cases.  Other imperfections you might want to consider are saturation/clipping, input current, PSRR, CMRR, nonzero output impedance and many more.

A:
When the 'Negative Feedback' in an Op-Amp (Ideal) makes the difference
  between its input terminals equal to 'Zero'. Shouldn't the output
  become zero too

Imagine the op-amp had an open loop gain of only 100. Negative feedback causes some fraction of the output signal to be fed back to the input and this "restricts" that output signal.
So, what would be the final steady state with equal value resistors and 1 volt at the input? What value of output voltage would satisfy the situation?
You can derive a two simple formulas for the "unknown" voltages: -
\$V_A\times 100 = -V_{OUT}\$
\$V_A = \dfrac{V_{IN}+V_{OUT}}{2}\$
This means that \$V_{OUT} = \dfrac{V_{IN}}{1+\frac{1}{50}}\$
Or, put more generally, for equal value resistors,
\$\dfrac{V_{OUT}}{V_{IN}} = \dfrac{-1}{1+\frac{2}{A_{OL}}}\$ where \$A_{OL}\$ is the open loop gain.
This means that \$V_{OUT}\$ would be -0.9804 for 1 volt inputted.
It also means that the voltage at the inverting input is 9.804 mV.
Now that isn't a virtual ground (or zero volts) but it isn't far off. If the open-loop gain (\$A_{OL}\$) became 1000 then \$V_{OUT}\$ is now -0.998004 and the voltage at the input is fractionally under a milli volt and, by most folks practical standards, it's a virtual ground.
So, if you take this to extremes you can see that the voltage at the inverting input is "virtually" ground.
Here's a way of looking at it from a control system point of view this time using the non-inverting op-amp configuration.

A: I am not sure what your question exactly is but your 2nd explanation is OK and can be applied to any op-amp circuit as long as you treat the op-amp ideal (infinite gain, infinite input impedance, zero output impedance).
You can also imagine why this operating point is the only stable one : if the voltage difference between the terminals was larger ever so slightly the op-amp would immediatelly saturate its output voltage to the opposite terminal voltage and the voltage difference would swing back and forth until the stable point (voltage difference almost zero) is reached.

A: The way I think about it is, if the output voltage of an opamp in its linear region is:
$$V_o=A_{ol}(V^+-V^-) $$
You could rewrite this as:
$$V^+-V^-=\dfrac{V_o}{A_{ol}} $$
Then if \$V_o\$ is finite, and ideally \$A_{ol}\$ is infinite, then the differential input has to approach zero, \$V^+-V^-\to0\$. Even if \$A_{ol}\$ wasn't infinite, as it truly is, this number could be on the other of \$10^6\$, so the approximation is still valid.
This means there is still a small difference between the inputs, but it is convenient to assume that \$V^+=V^-\$ because it makes the analysis simpler.

A: rev B
A "virtual ground" means it is effectively 0V between, no matter what the common mode voltage is ( as long as the output is not saturated)  The inputs are high impedance so  no current between these points, but (Vin-) must be tracking the Vin+ if possible , so it always has ~ 0V between them.
This occurs due to negative feedback in the Op Amp and very high gain.
This comparison is fedback via negative feedback to make it ~0V difference , yet it may be a Vcc/2 reference , then it goes to Vcc/2 but still ~0V difference.
e.g. the V in offset = Vout/k

*

*where k is the open loop gain* feedback ratio .

*

*if Av(ol)=1e6 and Rf/Rin gain = 100 then the feedback ratio is 1e2/1e6=1e-4 so the input voltage difference is very small. e.g. 5V/1e4= 0.5mV

*a virtual ground may be high impedance but at DC it must be near 0V in order for the output with high gain to be in the linear region with negative feedback.  Generally we try to keep the impedances balanced on each input port to match bias current Voltage drop and common mode noise from becoming a differential noise problem.
This low voltage difference it essentially 0V so we call this difference  a virtual ground on the inputs.  Another circuit which uses this method is called Active Guarding, where as in EEG probes the common mode signal is buffered and drives the shield of the signals to reduce the voltage difference to ~0V with low impedance so stray noise is suppressed and capacitance is eliminated by the dv/dt reduction to 0.  The same is done around   high Z, or low phase noise circuits to reduce EMI from stray coupling by "gaurding" it with the common mode buffered signal around the inputs or sensor.
A floating ground means it is a 0V reference for that circuit but galvanically isolated from earth up to a limited breakdown voltage, with mandatory  HIPOT tests for AC units when made. It blocks DC and AC low f but not RF. THis is good to remember when you get EMI.  An RF cap to ground can reduce RF noise on floating grounds.
An earth ground is 0V reference but also tied to earth via the AC receptacle and ground path to earth for safety reasons. Even earth ground has a relative impedance. Why? becuase all grounds are 0V by definition as a point of reference and another reference point may have resistance, inductance and current flowing between will create that voltage difference. But for safety Power Line grounds may be as high as 100 Ohms or more in dry areas.
A logic ground is (again) a 0V reference for logic chips and may be noisy.
An Analog ground is (again) a 0V local reference for analog signals so that the return path is not shared with noisy loads or sources to keep ohmic loss voltages to a minimum.
So in electronics, ground ALWAYS implies 0V reference point somewhere ( by design)  and the adjective in front may be implied or explicit to reference to special characteristics such as above.

A: The apparent paradox arises because in one case you are dealing with a real (or at least more realistic model of) op-amp and in the other case you are dealing with an idealised abstraction that is useful for quick static (DC) analysis of the circuit.
In the real case, you do have some small differential voltage at the inputs, this is what drives the output.
If you 'let the gain go to \$\infty\$' then the small differential voltage
disappears and you end up with a nullator/norator model which gives rise to the 'virtual ground'.

A: Lets talk about distortion. With 0.1volt pp output from the opamp, which has openloop gain of 1Million, and UGBW of 1Mhz. With bipolar diffpair input devices, and no resistive linearization/degeneration. The 2nd and 3rd order input-referred intercepts are, for any bipolar, approximately 0.1voltpp.
At 1Hz, the virtual-ground input will be 0.1v / 1e6 = 100 nanovolts. This differential input, across the bases of the diffpair, is 100nV/0.1v = 1millionth of the distortion intercepts, and the 2nd and 3rd order products will be -120dBc or more.
At 1MHz, the openloop gain is ONE. The virtual-ground input will be 0.1v/ONE = 0.1volt. The opamp will produce heavy distortion.
Now for some interesting results.
At 1KHz, the openloop gain is 1,000x (60db). The virtual-ground input will be 0.1v/1,000 = 100 microVolts. This 100microVolts across bases of the input diffpair is -60dB; the 2nd order distortion will be -60dBc. The 3rd order distortion will be -120dBc.
Additionally, if you reduce the input by 10dB, the 2nd order Harmonic Distortion drops by 10dB. The 3rd order drops by 20dB. Life can be very good.

A: You can see an OpAmp as a P-only controller.
It will have allways some offset error if outut is non-zero.
The offset is, however, very small if open loop gain is high. It is virually zero.


text:
Q: How can I render a red box? I want to render a red box on my screen, clicking on the button "Criar quadrado". My code can do it, but just once. I want to render a red box on each click. That's my code :

//Crie um botão que ao ser clicado cria um novo elemento em tela com a forma de um quadrado
//vermelho com 100px de altura e largura. Sempre que o botão for clicado um novo quadrado deve
//aparecer na tela.

function criarQuadrado() {
  var boxElement = document.querySelector(".box");

  boxElement.style.width = 300;
  boxElement.style.height = 300;
  boxElement.style.backgroundColor = "#f00";
}

<button onclick="criarQuadrado()">Criar quadrado</button>

It renders, but I want on each click another box side by side. How can I do it?

A:

      function criarQuadrado() {
        var boxElement = document.createElement("div")

        boxElement.style.width = "30px";
        boxElement.style.height = "30px";
        boxElement.style.display = "inline-block";
        boxElement.style.backgroundColor = "#f00";

        var container = document.getElementById("container")
        container.appendChild(boxElement)
      }

<button type="button" onclick="criarQuadrado()">Click me</button>

A: To do this you need to create a new element every time the button is clicked using document.createElement(), then you can append it to something such as a div

let btn = document.querySelector('button')
btn.addEventListener('click', criarQuadrado)

function criarQuadrado() {
  var boxElement = document.createElement('div')

  boxElement.style.width = '20px';
  boxElement.style.height = '20px';
  boxElement.style.backgroundColor = "#f00";
  boxElement.style.float = 'left';

  document.querySelector('.boxes').appendChild(boxElement)
}
.boxes{margin-top: 20px}
<button>Add Box</button>

A: function mostraBox(){

var boxElement = document.querySelector('.box');
var color =  "#" + (Math.random() * 0xFFFFFF << 0).toString(16);

boxElement.style.width = 100;
boxElement.style.height = 100;
boxElement.style.backgroundColor = color;

return color;
}


text:
Q: Unity Physics.Raycast does not detect an object when it should I am making a 2D game and I am using Raycast to detect if the player is on the ground.  No matter what Raycast always returns false.  I have used Debug.DrawRay which shows that the ray is hitting the ground.  I have tried solutions from several different tutorials but nothing worked.  I am pretty new to Unity so hopefully someone who is more experienced knows what's wrong.
 if (Physics.Raycast(transform.position, transform.TransformDirection(-Vector3.down), DistanceDown, LayerMask)){
        Debug.Log("Grounded");
        return true;
    }
    else
    {
        Debug.Log("Not Grounded");
        return false;
    }

Revised Code:
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.down), (float)(GetComponent<Collider2D>().bounds.extents.y + Offset)))

A: A Raycast has a few parameters. I will explain each as there could be a few reason as to why it is not working, so possibly breaking this up can help you realize what's wrong.
Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
The origin is the point in space that the ray will start from. Currently, you have it as transform.position, so it will start at the position of whatever the script is on, most likely your player.
The direction is a vector that should be normalized so there is no scale to determine where from the origin the ray should be cast. Right now you are using -Vector3.down, which would result in Vector3.Up as up and down are opposites, so negating one gives the other. For a ground check, I would be using Vector3.down as the ground is generally down or below the origin of your player.
The maxDistance is the length that the ray is cast. Right now you have it as DistanceDown which I am assuming is some float. Generally, for a ground check, I would take the collider of your character, then add some offset to determine when grounded. Something along the lines of GetComponent<Collider>().bounds.extents.y + OFFSET. The bounds.extents.y is half the size of the collider and since your origin is the center of your player, this should land at the feet or base of your collider, which is why you need the offset.
The layermask is used to ignore particular layers when casting. It is rather useful when you only want to cast and hit a single layer, where in your case could just be the ground. I do not see code for this, but I will provide an example in case this is where you are going wrong. LayerMask mask = LayerMask.GetMask("GroundLayer"); and use mask as your mask. Now the ray will only hit objects on the layer GroundLayer.
The last parameter which you are not using is called queryTriggerInteraction.  Raycast by default do not hit triggers, but with this parameter, you can override it and tell it to hit triggers.
Read over each of these sections and check to make sure what you are doing matches what I am describing. If you are still unable to figure out your issues based on what I have written, I would need to know a bit more about your situation to help out.


text:
Q: Jquery .attr() sets value as undefined, why?

                    Email Visible (Fill other means of contact to change)
                    <select id="emailVisible" required name="emailVisible" class="form-control" disabled="disabled">
                        <option value="yes" selected = "selected">Yes</option>
                        <option value="no">No</option>
                    </select>

setInterval(function(){
            console.log("GOOO");
            if ($("#twitterInput").val() == "" && $("#facebookInput").val() == "" && $("#steamInput").val() == "") {
                console.log("1");
                $("#emailVisible").attr("disabled","disabled");
            } else {
                console.log("2");
                $("#emailVisible").attr("disabled",false);
                console.log($('#emailVisible').attr('disabled'));
            }
        }, 1000);

"console.log($('#emailVisible').attr('disabled'));" prints undefined
  in the console.

"2" is printed every second.
I do not know what is incorrect in my syntax.

A: Try with prop() instead of attr() .And change the value with boolean type not with string .And dont forget to add 3 input

setInterval(function() {
  if ($("#twitterInput").val() == "" && $("#facebookInput").val() == "" && $("#steamInput").val() == "") {
    console.log("1");
    $("#emailVisible").prop("disabled", true);
  } else {
    console.log("2");
    $("#emailVisible").prop("disabled", false);
    console.log($('#emailVisible').prop('disabled'));
  }
}, 1000);

<input id="twitterInput">
<input id="facebookInput">
<input id="steamInput">
  Email Visible (Fill other means of contact to change)
  <select id="emailVisible" required name="emailVisible" class="form-control" disabled="disabled">
                        <option value="yes" selected = "selected">Yes</option>
                        <option value="no">No</option>
                    </select>

A: You can observe that there will be no disabled attribute in <select> with id="emailVisible when you execute the jquery
 $("#emailVisible").attr("disabled",false);

This is because it removes this attribute to make the selectbox enable. That is why when you access $('#emailVisible').attr('disabled') it is undefined as there is no such attribute. You can verify yourself by using inspect element on this selectbox.

A:

setInterval(function(){
            console.log("GOOO");
            if ($("#twitterInput").val() == "" && $("#facebookInput").val() == "" && $("#steamInput").val() == "") {
                console.log("1");
                $("#emailVisible").prop("disabled","disabled");
            } else {
                console.log("2");
                $("#emailVisible").prop("disabled",false);
                console.log($('#emailVisible').prop('disabled'));
            }
        }, 1000);

                    Email Visible (Fill other means of contact to change)
                    <select id="emailVisible" required name="emailVisible" class="form-control" disabled="disabled">
                        <option value="yes" selected = "selected">Yes</option>
                        <option value="no">No</option>
                    </select>

Just change the attr to prop as disable is a property.


text:
Q: RedHat for desktops Is there any RedHat variant for desktops and FREE? If yes, is there any Wubi like tool that can be used to install from within Windows XP?

A: Yes, it's called Fedora now. No WUBI is an Ubuntu creation.

A: If you want cutting edge stuff, Fedora is where RedHat does their technology previews.
If you want something more stable -- ie security and bug updates only, not new versions of things -- look into one of the rebuilds of RHEL.  CentOS is a good place to start.
Fedora is updated with new stuff faster, but it also gets obsolete faster so you have to do updates.  RHEL/CentOS is supported longer so you don't have to upgrade, but you'll find that the user-facing applications get long in the tooth.

A: The 2 main forks are Fedora and CentOS. You can use UNetbootin to configure an install over the internet or from an ISO. The configuration can be done in Windows, and once you reboot you will have a boot menu containing Windows and your Linux distribution. Choosing the Linux distribution will bring you through the regular installer. A great tutorial on the process can be found here.


text:
Q: ssh: connect to host host port | No firewall I have a Debian server and I'm trying to access it by ssh from another server and I'm getting timeout error. I have no iptables rules on any of them, and actually I can ssh to target host from any other server and devices I have, The problem is just with this one server (which I can ssh to other servers from it without problem) and it's not just for port 22, when I do traceroute, I get Port Unreachable for port 22 and 80, but the host is reachable.
The only thing different about this one server is, it's not in the same region as others, Could it be some restriction applied by my Data center or ISP? It seems unlikely since I can ssh the second server from first one.

A: So, I used tcpdump to see how tow servers are communicating, I found out my target server does not receive any packet from my source server, I reported the problem to my Data Center and the problem was in one of the routers in their network.


text:
Q: Как правильно верстать изображение на Андройд? Всем привет. Решил попробовать написать свое первое приложение. Сразу же возник вопрос.
Есть такой шаблон. Фон в принципе понятно как сделать, сделаю через стандартные xml background. А вот как работать с изображением в центре, что бы оно пропорционально сжималось на разных смартфонах. Расскажите как вы верстаете такое? может быть есть сервис которые нарезает изображение под все устройства?
p.s Параметры шаблона Ширина 640px высота 960px

A: Разбиваете на 4 элемента:
Красный фон - бэкграунд
  Логотип манчестера с черной полосой - ImageView
  Белая надпись - TextView
  Белый значок внизу - ImageView - изображение .9.png , с растягивающимися концами , где нет изображения. В Android Studio есть встроенный инструмент для работы с 9patch изображениями.
Все это компонуете в вертикальный LinearLayout , указываете вертикальный маржин (margin) для логотипа манчестера от верха и паддинги (отступы) для всех элементов. Для логотипа манчестера, текста и значка под текстом размер по горизонтали указываете - match_parent- занимать всю ширину , текст внутри позиционируете с помощью гравити по центру и в общем то готово.
ImageView делаете с прозрачным фоном.
Для подготовки двух ImageView можно использовать встроенный в Android Studio Asset Manager. Делаете одно изображение под максимальное разрешение (самую большую картинку) , добавляете в проект , затем в IDE правый клик по картинке -> New -> Image Asset.
 Там уже разберетесь - инструмент подготовит изображения под нужные плотности экрана и сам раскидает по нужным папкам.
Если вы не знакомы с поддержкой разных разрешений экрана в android - необходимо ознакомиться, в частности с выбором системой подходящего для конкретного устройства изображения.
Для TextView указываете размер шрифта в sp - этого должно хватить для масштабирования

A: Все размеры в dp.
Графику нарезаешь в 4 экземплярах в папки drawable
xlarge (xhdpi): 640x960
large (hdpi): 480x800
medium (mdpi): 320x480
small (ldpi): 240x320
Верстку в xml в папки layout.
Используй утилиту 9patch http://habrahabr.ru/post/113623/
Поддержка различных экранов http://developer.android.com/training/multiscreen/screensizes.html
Если не хочешь мучиться с растровой графикой и нарезкой, то изображения можно подключить в векторе. Для этого нужна библиотека типо androidsvg


text:
Q: Error en la base de datos couchdb, no estoy autorizado para acceder Estoy intentando acceder a la base de datos de couchdb con el comando curl -X GET http://127.0.0.1:5984/channel_cc3
pero me da el siguiente error:
{"error":"unauthorized","reason":"you are not authorized to access this db."}

¿Alguien sabe cómo solucionar esto?

A: Es que le tienes que pasar en la petición GET el usuario y la contraseña para realizar el proceso de autenticación, la petición sería algo así:
http://usuario:clave@127.0.0.1:5984/channel_cc3


text:
Q: prevent firefox from displaying "To display this page, Firefox must send information that will repeat any action ..." Whenenver I reload a page that submits data via POST, I get this message.
However, for some pages (particularly games) I do not mind re-sending a POST request. The action is of little consequence, and I want it to be as fast as possible.
Can I, as a USER, not a website developer, turn off this warning for a specific page?

A: You cannot turn off this warning. There is no mechanism for doing that,
because this is a pretty serious warning about an action that might have
serious consequences.
This happens when you have accepted a form and wish to go Back to that form.
However, doing that may possibly not display an empty form, but, depending on
the browser, may execute again accepting the form.
If you have just bought your new washing machine and went back to the
payment form, you might be surprised to later see that your bank account
was debited twice for this one machine ...
The web developer that created the form did not think about this possibility
and has not taken steps to avoid it using
Post/Redirect/Get.
You, the user, should be absolutely sure when going back that you don't
mind if the form gets executed again, or must know from experience that
your browser will not re-submit this one form.


text:
Q: I'm getting a 42000 sql syntax error in netbeans but the same query string works fine in mysql console Ok...here's my code and I don't understand where i'm going wrong...I'm getting a 42000 error in netbeans which i understand is an sql syntax error but it works perfectly fine in the mysql console
 try
     {
         Class.forName("com.mysql.jdbc.Driver");

         Connection CC =
         DriverManager.getConnection("jdbc:mysql://localhost:3306/pulsedb", "root", "carrizo");

String q1 = String.valueOf(jComboBox1.getSelectedItem());
         String ans1 = jTextField9.getText();

         String q2 = String.valueOf(jComboBox2.getSelectedItem());
         String ans2 = jTextField10.getText();

         String recovQA  = "INSERT INTO pulsedb.mstuffrecovery (recov_qsn,recov_ans)     VALUES('"+q1+"',"+ans1+"')";
         String recovQA2  = "INSERT INTO pulsedb.mstuffrecovery2 (recov_qsn2,recov_ans2) VALUES('"+q2+"',"+ans2+"')";

         PreparedStatement PQS = CC.prepareStatement(recovQA);
         PreparedStatement PQQ = CC.prepareStatement(recovQA2);

         PQS.executeUpdate(recovQA);
         PQQ.executeUpdate(recovQA2);

catch(SQLException e)
             {

                 System.out.println(e.getSQLState());
                 e.getMessage();
                 e.getErrorCode();
                 e.printStackTrace();

             }

A: 1) I doubt very much that the same query works in SQL console because you are missing a single quote (at least) and it would through an error. If you missed it, that means you are not running the same queries in console and in your code...
2) you should always use parameters when passing values to your SQL


text:
Q: Sending information Main swf to loaded in swf I have already properly loaded in a swf in my main fla file. The swf I am loading in has interactions and has it's own code level. The swf loaded in uses some XML to run different objects. I want to pass the file path of xml from my main FLA file down to the loaded in swf.
Any suggestions on how to do this?


text:
Q: get all keys from json column and convert to rows I have a table like the following, where cities is a JSON column

ID
cities

1
["madrid"]

2
["london", "madrid", "paris"]

3
["london", "paris"]

4
["london"]

5
["rome", "berlin"]

I would like to convert that column to rows, where all individual city gets its own row

city

madrid

london

paris

rome

berlin

I've tried something like
SELECT distinct JSON_VALUE(JSON_EXTRACT(cities, '$[*]'), '$[*]') as cities FROM table_cities

but I get this instead

city

madrid

NULL

london

A: *

*If you are using MySQL version 8.0, you can try using the function JSON_TABLE (tested on dbfiddle)

SELECT DISTINCT tmp.city
FROM table_cities c,
JSON_TABLE(
  c.cities,
  '$[*]'
  COLUMNS(
  city VARCHAR(10) PATH '$[0]'
  )
) tmp;

*For MariaDB 10.4.2, you can try this. (tested on dbfiddle)

CREATE TABLE main_table (
    cities VARCHAR(1000)
);

-- create procedure
CREATE PROCEDURE proc1()
BEGIN
SET @index := 0;
SELECT @json_length := MAX(JSON_LENGTH(cities))
FROM table_cities;

REPEAT
   INSERT INTO main_table (cities)
   SELECT JSON_EXTRACT(cities,CONCAT("$[",@index,"]")) FROM table_cities;
   SET @index = @index + 1;
UNTIL @index = @json_length
END REPEAT;
END;

-- call procedure
CALL proc1;

-- query result
SELECT DISTINCT REPLACE(cities, '"', '') AS city
FROM main_table
WHERE cities IS NOT NULL;


text:
Q: Postgres: copy errors when extra tab on tab delimited text file I have the three statements below that all work until it hits a row with an extra tab at the end of the tab delimited text file that I am trying to import.
Any way to tell Postgres to ignore extra tabs?
copy mara FROM 'c:/Postgres MME/AG00_MARA.txt' DELIMITER E'\t' NULL '' CSV HEADER;
copy mara FROM 'c:/Postgres MME/AG00_MARA.txt' DELIMITER E'\t' CSV HEADER;
copy mara FROM 'c:/Postgres MME/AG00_MARA.txt' WITH (FORMAT csv, DELIMITER E'\t', NULL '', HEADER);
Image of Notepad++ Where I see the extra tab at the end of the row

A: Don't try to ignore it, just fix your data by removing all the trailing tabs with regex \t$. For example in Linux:
sed -i 's/\t$//g' AG00_MARA.txt


text:
Q: Why is response coming through in Postman working but not my test? I have this express controller in order to find the amount of unread notifications, that a user is a recipient of. Here:
app.get('/api/user/:uid/notifications/newcount', (req, res, next) => {
    const firebaseUID = req.params.uid;

    User.findOne({ firebaseUID })
      .select('_id')
      .then(user => Notification.count({
          recipients: { $eq: user._id },
          usersRead: { $ne: user._id }
        })
      )
      .then(notificationCount => {
        console.log(notificationCount.toString());
        return res.send(notificationCount.toString())
      })
      .catch(next);
  });

This works just fine in postman.
I am trying to test it with Mocha/Supertest. Yet for some reason, the res.body always come back as an empty object.
The console logs in the actual controller always come through just fine though.
If I don't send as toString() in the res.send(), then I get errors.
res.body should be coming back as 1.
How can I grab the res.body in the below test in order to make an assertion?
it.only('GET to /api/user/firebaseUID/notifications/newcount, gets users unread notifications',
  done => {
      request(app)
        .get(`/api/user/${matt.firebaseUID}/notifications/newcount`)
        .end((err, res) => {
          console.log(res.body);

          done();
        });
  });

Thanks!

A: In the superagent module that supertest is based on, the response.body property is only populated when the response can be parsed into a Javascript Object. The response.text property will include the plain response body as a string.
The text property comes from responseText in XMLHttpRequest.


text:
Q: Angular 6 SCSS compile error from util.js I'm just starting out with Angular 6, using the Angular CLI and getting familiar with the file structure. I intend on using SCSS to create a singular global stylesheet. However, when i compile i am receiving the error:
ERROR in ./src/app/top-bar/top-bar.component.scss
Module build failed (from ./node_modules/sass-loader/lib/loader.js):

// Copyright Joyent, Inc. and other Node contributors.
^
Invalid CSS after "...N THE SOFTWARE.": expected 1 selector or at-
rule, was "var formatRegExp = "
in /Users/me/Documents/projects/node_modules/util/util.js
(line 1, column 1)

My custom scss folder is located under src/assets/scss.
My top-bar component is located under src/app/top-bar.
I am trying to access src/assets/scss/app.scss in src/app/top-bar/top-bar.component.scss and receiving the above error.
I've tried numerous ways of importing the file @import "~/assets/scss/app.scss"; and @import "../assets/scss/app.scss"; to include the necessary variables but i cant be sure of what i'm doing wrong as the error seems vague and not pointed at any specific file besides a core angular utility.
If anyone can shed some light, even on the debugging process for such an error it would help immensely.

A: I encountered the same problem. The root cause is a bug in the SCSS file loader/resolver used by webpack (used by the @angular/cli) that loads JS files in addition to SCSS files.
The bug is that JS files take precedence over SCSS files. The GitHub issue is here:
https://github.com/webpack-contrib/sass-loader/issues/556
The bad news is that the issue has been open for 8 months, and pull requests to fix it haven't been accepted.
The good news is that you can work around the problem by using SCSS file names that don't match JS filenames in node_modules subdirectories.
For example, I had a SCSS file named _util.scss, and so my error was:
  Invalid CSS after "...N THE SOFTWARE.": expected 1 selector or at-rule, was "var formatRegExp = "
     in C:\src\project\node_modules\util\util.js (line 1, column 1)

My fix was to rename my SCSS file to _sass-util.scss. Hope that helps.

A: As pointed out by @crimbo the problem is in https://github.com/webpack-contrib/sass-loader/issues/556 , but I cannot rename files, because I use third party library ( Foundation 6 ).
I have downgraded to sass-loader@6.0.7
npm install --save-dev sass-loader@6.0.7

and it works for me for Angular 7.1.4 which used originally sass-loader@7.1.0
As per release notes https://github.com/webpack-contrib/sass-loader/releases/tag/v7.0.0 the breaking changes are:

*

*Drop official node 4 support

*This slightly changes the resolving algorithm. Should not break in normal usage, but might break in complex configurations.

*The sass-loader throws an error at runtime now and refuses to compile if the peer dependency is wrong. This could break applications where npm's peer dependency warning was just ignored.

which are not problem for my case

A: Workaround for Angular7+ (unable to revert sass-loader version) & Foundation6+ & SASS combination:
Do not @import util/util from foundation in your .scss files but separated packages combination (breakpoint, color, direction, flex, math, mixins, selector, typography, unit, value), based on what you need or trick it with ./util/util. Also foundation.scss and settings.scss imports util inside them and so this files should be avoided or patched locally until sass-loader fix.