Laravel view not found exception

Question: I have problem with laravel view is not found by route function I did composer  dumpautoload  but no use
ArticleController.php
<?php
class ArticleController extends BaseController
 {
 public function showIndex()
 {
    return View::make('index');
 }

 public function showSingle($articleId)
 {
 return View::make('single');
 }
}

//Route
Route::get('index', 'ArticleController@showIndex');

InvalidArgumentException
View [index] not found.
open: /opt/lampp/htdocs/laravel-project/bootstrap/compiled.php

    foreach ((array) $paths as $path) {
    foreach ($this->getPossibleViewFiles($name) as $file) {
    if ($this->files->exists($viewPath = $path . '/' . $file)) {
    return $viewPath;
    }
    }
    }
    throw new \InvalidArgumentException("View [{$name}] not found.");
    }
    protected function getPossibleViewFiles($name)

Server/Request Data
REDIRECT_UNIQUE_ID  UfWlAn8AAQEAABR2VakAAAAF
REDIRECT_STATUS     200
UNIQUE_ID   UfWlAn8AAQEAABR2VakAAAAF
HTTP_HOST   localhost
HTTP_USER_AGENT     Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0
HTTP_ACCEPT     text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_LANGUAGE    en-US,en;q=0.5
HTTP_ACCEPT_ENCODING    gzip, deflate
HTTP_COOKIE     laravel_session=f94fpel78jn89nhah32mflqn15
HTTP_CONNECTION     keep-alive
HTTP_CACHE_CONTROL  max-age=0
PATH    /usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
LD_LIBRARY_PATH     /opt/lampp/lib:/opt/lampp/lib
SERVER_SIGNATURE
SERVER_SOFTWARE     Apache/2.4.4 (Unix) OpenSSL/1.0.1e PHP/5.4.16 mod_perl/2.0.8-dev Perl/v5.16.3
SERVER_NAME     localhost
SERVER_ADDR     127.0.0.1
SERVER_PORT     80
REMOTE_ADDR     127.0.0.1
DOCUMENT_ROOT   /opt/lampp/htdocs
REQUEST_SCHEME  http
CONTEXT_PREFIX
CONTEXT_DOCUMENT_ROOT   /opt/lampp/htdocs
SERVER_ADMIN    firstname.lastname@example.com
SCRIPT_FILENAME     /opt/lampp/htdocs/laravel-project/public/index.php
REMOTE_PORT     50211
REDIRECT_URL    /laravel-project/public/index
GATEWAY_INTERFACE   CGI/1.1
SERVER_PROTOCOL     HTTP/1.1
REQUEST_METHOD  GET
QUERY_STRING
REQUEST_URI     /laravel-project/public/index
SCRIPT_NAME     /laravel-project/public/index.php
PHP_SELF    /laravel-project/public/index.php
REQUEST_TIME_FLOAT  1375053058.123
REQUEST_TIME    1375053058

Comment: Do you have a `index.php` or `index.blade.php` file in your `app/views` directory?
Comment: Laravel will create the view from your view file. When you do `View::make` Laravel will actually find the view file specified then inflate it with view data. So you it is mandatory for you to create your view file. Laravel will not make it for you.
Comment: That's your problem. You have to actually create the view file... if you do `View::make('index')`, Laravel will look for a file named 'index' (ending with .php or .blade.php) under your `app/views` directory.
Comment: just I want to ask when you call View::make('index'); will create view
Comment: even i am also getting same issue,i have install laravel passport in  my project i dnt no why it is happening.,if anyone knows pls let me know
Comment: Had the some problem. I removed vendors and `composer install` again worked for me.
Answer: This error also occurs when you try to move the whole project directory to other path. And you happened to run the following commands below BEFORE you move.
php artisan optimize --force
php artisan config:cache
php artisan route:cache

Mine error message shows like this

As you can see the old path was written in the compiled.php. So, to fix the problem. Simply run the same command AGAIN under the project folder in your new folder location.
php artisan optimize --force
php artisan config:cache
php artisan route:cache

Hope this helps.
Comment: If you are using `Homestead`, you will have to mind to execute those commands inside your vagrant box and login in with `vagrant ssh`.
Comment: This comment was immensely useful in tracking down this bug. We only encountered this issue when we deployed to our AWS cloud -- we couldn't reproduce the issue locally. For anyone else deploying to AWS via Elastic Beanstalk, you'll need to run these commands AFTER the deployment has completed; in other words, via a post-deployment hook: https://forums.aws.amazon.com/thread.jspa?messageID=678066
Comment: I was able to fix it by doing `source /opt/elasticbeanstalk/support/envvars` before `php artisan config:cache`
Comment: @SamuelMS can you share what you had on your post-deployment script? I'm running `php artisan config:cache` but the env() calls are not resolving so the generated config cache file has all the default values.
Comment: If you're on docker and using persistent volumes mapped to your local drive, ensure you run the artisan commands in the docker container and not your local mapped drive.
Answer: This happens when Laravel doesn't find a view file in your application. Make sure you have a file named: index.php or index.blade.php under your app/views directory.
Note that Laravel will do the following when calling View::make:

For View::make('index') Laravel will look for the file: app/views/index.php.
For View::make('index.foo') Laravel will look for the file: app/views/index/foo.php.

The file can have any of those two extensions: .php or .blade.php.
Answer: This command works for me
php artisan config:cache

As Laravel doc says that by default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the filesystem. So it needs to recache the file system so that newly added views and route are available to show. I also not sure why laravel needs to recache actually
Comment: So far I understand, laravel doc says that  by default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the filesystem. So it needs to recache the file system so that newly added views and route are available to show. I also not sure why laravel needs to recache actually ):
Answer: In my case I had to run php artisan optimize:clear in order to make everything to work again.
Answer: This might be possible that your view is present even though it shows the error. So to solve this issue you need to stop the server and run this command on the terminal.
php artisan config:cache

then restart the server
Comment: To give your application a speed boost, you should cache all of your configuration files into a single file using the 'config:cache' Artisan command. This will combine all of the configuration options for your application into a single file which will be loaded quickly by the framework.

You should typically run the  'php artisan config:cache'  command as part of your production deployment routine. The command should not be run during local development as configuration options will frequently need to be changed during the course of your application's development.
Answer: Somewhat embarrassingly, I discovered another rather trivial cause for this error: I had a full stop in the filename of my blade file (eg resources/views/pages/user.invitation.blade.php). It really did make sense at the time!
I was trying to reference it like so: view('pages.user.invitation')
but of course Laravel was looking for the file at resources/views/pages/user/invitation.blade.php and throwing the view not found.
Hope this helps someone.
Comment: This was my exact issue.
Answer: Just in the controller call
return View('index');

without
::make

Comment: It appears that the OP is using Laravel 4 in which case the `view` helper does not exist. This won't work.
Comment: It works because you are using Laravel 5. As Jared said, the ``view`` helper didn't exist in Laravel 4.
Answer: As @deanchiu said it may happen when you move the whole project to another path or server.
But in my case I had no access to command line on server and running following commands BEFORE I upload my project helped me.
> php artisan route:clear
> php artisan config:clear

Answer: I was having the same error, but in my case the view was called seeProposal.
I changed it to seeproposal and it worked fine...
It was not being an issue while testing locally, but apparently Laravel makes a distinction with capital letters running in production. So for those who have views with capital letters, I would change all of them to lowercase.
Comment: This was my issue. I used _incompleteCreditCheck. Although _sideMenu works fine. Changing it to _incompletecheck fixed it on the server. I am still baffled as to why the other works but not this single case.
Answer: In my case I was calling View::make('User/index'), where in fact my view was in user directory and it was called index.blade.php. Ergo after I changed it to View@make('user.index')  all started working.
Answer: check your blade syntax on the view that said not found
i just fix mine
@if
@component
@endif
@endcomponent

to
@if
@component
@endcomponent
@endif

Answer: Use this on your cmd then run your project.
php artisan config:cache
php artisan route:cache
php artisan controller:cache
php artisan optimize:clear

Comment: I'm afraid `php artisan controller:cache` doesn't exist, at least not in current laravel version
Answer: Create the index.blade.php file in the views folder, that should be all
Answer: If your path to view is true first try to  config:cache and route:cache if nothing changed check your resource path permission are true.
example: your can do it in ubuntu with :
sudo chgrp -R www-data resources/views
sudo usermod -a -G www-data $USER

Answer: I had the same error. I created a directory under views direcotry named users and created an index.blade.php file in it. When calling this file you should write users.index to indicate your path. Or just create index.blade.php file under views. hope this will help someone who gets the same problem
Answer: In addition to these answers, if your view is in an unusual directory for the project, you'll have to add the following to /config/view.php
    'paths' => [
    resource_path('views'),
    resource_path('../path/from/project/route/to/view')
],

Answer: If you are not accessing files as root user you shall change access of files

Change Access group to Access files
Also, others to Access files
it's work for me
Answer: If you are using GIT in your project don't forget make git add . and commit before of move the project to another side and also don't forget clean the cache.
Answer: I'm using Laravel 10, in this time being, and I resolve this when renaming my index.blade.php into different file name such as home.blade.php
I tried using:
php artisan optimize:clear

Seems it doesn't work, so I renamed index.blade.php into home.blade.php
And on the controller
I replaced:
public function showIndex()
{
    return view('index');
}

Into:
public function showIndex()
{
    return view('home');
}

And inside the route on web.php:
In my case it's:
Route::view('/', [HomeController::class, 'showIndex'])->name('home.index');

I hope this works as a solution to this error.
Answer: I did this on cpanel Server :
after i uploaded index.blade.php , nothing changed
So i compress the file (into zip format) then i uploaded on the place, extract it... and bam!
Answer: In my case, Laravel 5.3
Route::get('/', function(){
    return View('test');
});

test.blade.php was not rendering but some other views were rendering on localhost via XAMPP on mac. Upon running artisan server, the view started rendering for same url over XAMPP.
php artisan serve

To avoid any such scenario, one should test the Laravel apps with artisan server only.

Laravel view not found exception


How does one sample all images uniformly when the data set is organized in hierarchies?

Question: I have a data set with $C=64$ classes and $N_c = 600$ images and total images $N = \sum_c N_c$. Each class has a separate folder for each class. I want to be able to sample images as if they were in a union of all folders (i.e. any image has the same probability no matter where it is located and even if classes are unbalanced). The issue is that I don't want to actually flatten the data set into a union as that duplicates the data and higher storage costs. So I want to sample such that if I were to sample a batch e.g. $B=1024$ then every image has the same chance of occurring. I think for that I need that the probability of an image to be equal to:
$$ Pr[X = x] = \frac{1}{N}$$
I think that is what my problem boils down to if I am correct (correct me if that is the wrong modeling please!)
So for that to happen I think what I need to do is first sample a class with probability equal $$Pr[C=c] = \frac{N_c C}{N}$$
and sampling an image given that class uniformly i.e. with probability
$$ Pr[X=x \mid C = c] = \frac{1}{N_c}$$
This is what I get using the marginalization rule for probs:
$$ Pr[X=x] = \sum_c p(c) p(x \mid c) = \frac{1}{N} $$
if you plug in the numbers.
But that seems weird, I would have thought that it's sufficient to simply sample any class weighted by the number of images it has and then sample a image uniformly (i.e. just sample uniformly twice $B$ times to get your batch).
But formal calculations seem to give me something else, what is my mistake?
Answer: just create list of all files, then sample this list and voila!,
as for calculations:
probability sampling image from class $A$ sampling from whole set is $P(class\_A)=size(A)/size(whole\_set)$ but in second sampling/drawing $P(class\_A)=\frac{size(A)-1}{size(whole\_set)-1}$ because I presume you are sampling without replacement, of course after picking class/subset you can sample uniformly from this smaller set


Dúvidas sobre a função realloc

Question: realloc realoca "negativamente" a memória? Quer dizer, se o tamanho original de um vetor for maior do que o valor passado na realocação, o vetor será reduzido?
Por exemplo, se eu faço isso:
char *exemplo = calloc(256, sizeof(char));
strcpy(exemplo, "Teste");
exemplo = realloc(exemplo, 3 * sizeof(char));
printf("%s\n", exemplo);

Por que continua imprimindo "Teste"? É como se o espaço alocado ainda permanecesse...
Comment: Nota: por definição `sizeof (char)` é `1`.
Answer: Em C o espaço que você reserva para os dasdos e como você efetivametne usa esses dados são duas coisas separadas.
COmo o sizeof(char)  é sempre 1, você de fato, ao chamar o realloc deixou apenas 3 bytes reservados para o seu texto de exemplo - como você esperava.
Só que a função "printf" não sabe disso - ao buscar uma string para impressão, como o código de controle "%s" ela vai imprimir toda a string de destino até encontrar um caractére \x00. Se não houver nenhum antes do final da área alocada para a astrign pdem acotnecer uma de duas coisas: o seu programa termina com um segmentatin fault, ou, o pritnf consome dados de uma área de uma área em que podem estar sendo usados para outras coisas dentro do seu programa. Por concidencia, os bytes que você liberou com o realloc continuaram dentro de um segmento usado no seu programa e esses dados não foram usados por mais nada - então seu printf funcionou.
Mas a grande lição para se ter em memte é: em C não existe nenhum mecanismo automático que vai "parar" o acesso a memória e restringi-lo a areas que você alocou (seja com malloc, seja reservando as dimensões na declaração de variável) - você é responsável por saber que todas as funções chamadas pelo seu programa estão acessando areas de memória permitidas.
Se quiser verfificação automática de tamanhos de vetores, e etc, só vai encontrar isso em linguagens de mais algo nível - Java, Go, Pythn, RUby, etc... Em C, e C++ é você e a CPU.
Comment: Muito obrigado, vocês são demais!
Answer: Ao reduzires o espaço reservado para exemplo para 3 bytes, o conteúdo desses 3 bytes é 'T', 'e', 's' (nota especialmente a ausência de '\0'), ou seja, esse conteúdo deixou de der uma string.
Ao passares essa não string para printf() qualquer coisa pode acontecer: é Comportamento Não Definido.
Um exemplo desse comportamento é o programa fazer o que tu esperas ... excepto às sextas-feira de lua nova.
Experimenta
exemplo = realloc(exemplo, 3);
exemplo[2] = 0; // fazer uma string
printf("%s\n", exemplo);

ou
exemplo = realloc(exemplo, 3);
printf("%.3s\n", exemplo); // imprimir 3 caracteres excepto se houver um '\0' antes

Dúvidas sobre a função realloc


Radius of Circle Intersecting 5 other circles?

Question: Five touching circles each have radius 1, and their centers are at the vertices of a regular pentagon. Find the radius of the circle that passes through the points of contact $P,$ $Q,$ $R,$ $S,$ and $T.$

Enter your answer as a trigonometric value, such as $\cos 20^\circ$.
Comment: This post will attract downvotes if you don't explain what you've tried or where you're stuck.
Comment: A very similar question as that of AIME 1991 problem 11. Refer https://artofproblemsolving.com/wiki/index.php?title=1991_AIME_Problems/Problem_11
Answer: From the given right triangle between circle centers and tangent point of copied (regular pentagonal touching) circles
$$ \dfrac{1}{r}= \tan \phi= \tan \dfrac{360^0}{10}$$
or
$$ r= \cot 36^0 $$
Answer: A quick google search will yield the formula for a regular polygon's apothem, which is the length you're looking for.
$$r = \frac{s}{2\tan\left(\frac{\pi}{n}\right)} = \frac{1}{\tan(\frac15\pi)}.$$
Answer: Let $O$ be a center of the pentagon. Let $l$ be a distance from $O$ to some vertex. I hope you can compute it. Call it $l$.
Now draw a secant from $O$ through this vertex. Its length is $l+1$; the length of its outer part is $l-1$. Observe that the radius $r$ you are seeking is a length of a tangent. Recall a theorem which connects these three values.
Can you continue?


Restore file drag and drop

Question: I want to block file drag and drop on an application. For this, I can use win32 API
[DllImport("ole32.dll")]
public static extern int RevokeDragDrop(UIntPtr hwnd);

Now, I would like to restore the drag and drop for that application. Is there any API to restore it back?
Comment: In a C# program you'd normally change the AllowDrop property to get these native functions called.  We can't tell why you want to pinvoke, if *hwnd* belongs to another process then there is no way to correctly re-enable it.  Since the IDropTarget interface reference must belong to that process.
Comment: If it is possible to enable it for an external program, wouldn't it count as a security hazard?
Answer: You'd use the RegisterDragDrop function, which is how it was (likely) originally set.
From https://learn.microsoft.com/en-us/windows/win32/api/ole2/nf-ole2-registerdragdrop:

If your application can accept dropped objects during OLE drag-and-drop operations, you must call the RegisterDragDrop function. Do this whenever one of your application windows is available as a potential drop target, i.e., when the window appears unobscured on the screen.
Comment: Note that `RegisterDragDrop()` is not the only way a window can accept drops. There is also `DragAcceptFiles()`. Also note that `RegisterDragDrop()` requires an `IDropTarget` object, which you can't query from a window, so if you `RevokeDragDrop()` a window you don't own, you can't restore its `IDropTarget` correctly.
Comment: I do not own this window. RegisterDragDrop seems to just one way as it seems we cannot restore it back using RegisterDragDrop.
Looks DragAcceptFiles might be helpful. I will look into this.
Comment: It wasn't clear from the question that you don't own the window. Sorry!
Comment: I tried using      [DllImport("shell32.dll")]
        public static extern void DragAcceptFiles(IntPtr hwnd, bool fAccept);
Then from the code, I called DragAcceptFiles(handleOfThatProcess,false) but it is not blocking drag and drop file in that application.
Comment: Is there any other way to achieve this? Block file drag and drop and unblock it again. I know using mouse hooking can solve this but mouse hooking takes too much CPU.

Restore file drag and drop


'State' is not defined and 'handleToggle' is not defined no-undef

Question:   Line 11:5:  'state' is not defined         no-undef
  Line 15:5:  'handleToggle' is not defined  no-undef

I don't understand why it shows me these errors, please help me resolve this,  I would also appreciate an explanation
const Footer = () => {
    state = {
        langContent: false
    }

    handleToggle = (e) => {
        e.preventDefault();
        this.setState({
            langContent: !this.state.langContent
        })
    }

    return (
        <FooterContainer>

                Questions?
                <Link> Call 1-877-742-1335</Link>

                {/* Language Button */}

                   <Icon icon={iosWorld} size={20}/>
                       English
                   <Icon icon={arrowSortedDown} />

            {/* Toggle Language Content */}
            {this.state.langContent && (

English

Hindi

             )}

                Netflix India

        </FooterContainer>
    )
}

Answer: The component has been created as a functional component, which does not have state, to fix this issue you can use the useState hook.
const Footer = () => {
    const [langContent, setLangContent] = useState(false)

    const handleToggle = (e) => {
        e.preventDefault();
        setLangContent(!langContent);
    }

    return (
        ... // Use existing Code
    )
}

If you want to continue to using class based components then you should use a class that extends React.Component
class Footer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      langContent: false
    };
  }

render() {
... //Use existing Code
}

Additional Reading:
React Docs for hooks-state
Answer: I think you are confusing the syntax for using state in functional components with the syntax for using states in class components.
To use state in functional components, use it like this: (also you forgot to declare const before the function handleToggle, here you are declaring a function local variable thus const is needed. You are confusing it with declaring a method in a class)
const Footer = () => {

const [state, setState] = useState({ langContent: false })

const handleToggle = (e: { preventDefault: () => void; }) => {
    e.preventDefault();
    setState({
        langContent: state.langContent
    })
}

return (
    <FooterContainer>

        Questions?
        <Link> Call 1-877-742-1335</Link>

        {/* Language Button */}

            <Icon icon={iosWorld} size={20}/>
              English
            <Icon icon={arrowSortedDown} />

        {/* Toggle Language Content */}
        {state.langContent && (

English

Hindi

        )}

        Netflix India

    </FooterContainer>
)}

If you want to use functional component style, read more about it here: React docs-Using the state hook


Track unsuccessful login attempts for ID Locking

Question: 1) A typical Login Screen of an application, ID locked for wrong passwords when more than three attempts.
2) The attempt cannot be stored in session, because user might use multiple browsers in same or different machine.
3) I don't want to persist the count in the database since one would have to reset it after 24rs or so.
What is the best way to do this?
Comment: What platform? .NET? Java? What kind of application? Desktop? Web?
Answer: You can persist the date of last correct login, date of last wrong login and count of wrong logins in a row.
The "lock" would happen automatically if count exceeds 3 and the last wrong login was in last X minutes. That way you don't have to reset anything just to compare dates ;)
Comment: I will go with this. Thanks Thomas.
Answer: You'd probably want to use IP address to track incorrect login attempts.
If you are looking to see if someone is trying to brute force a password, then use IP.
If you are trying to lock out users who forgot their password, do it by user name.
Comment: While I see your reasoning, such bruteforce attempts are typically facilitated through distributed attacks, and IP tracking may not prove as useful here.


Right recursive grammar or left recursive?

Question: I have little to no knowledge of what I'm about to ask, so I would like a suggestion based on the level of skills required to implemented a parser for the given grammar ( since I'm a beginner in this kind of formal approach to parsers and languages ).
Just by going back of a couple of years, this situation reminds me a little of Pascal grammar vs C/C++ grammar, this left vs right stuff.
But I'm not going to do any of that, my purpose is to implement a simple parser for a markup language for documents like Markdown.
So considering that I'm starting with a markup language in mind, I want to keep things simple, which is the easiest one to handle between this 2 options and why . Another kind of grammar could be an easier option for me ? If yes which one do you suggest ?
Answer: Right recursive vs. left recursive mostly comes down to how you're going to implement the parser.
If you're going to do a top-down (e.g., recursive descent) parser, you normally want to use right recursion in the grammar (and for pure recursive descent, that's the only option).
If you're going to do a bottom-up parser, you normally want to use left recursion. Bottom up parsers are normally generated with a parser generator like Yacc or Bison, most of which can handle right recursion if needed, but can handle left recursion more efficiently, so it's preferred as long as it doesn't adversely affect semantics.
Comment: could you assign a specific spot to PEG grammars ( https://en.wikipedia.org/wiki/Parsing_expression_grammar ) ? I mean if I'm going to write a parser for a PEG I can assume that something will work better than other options ? I can cut down the options to a smaller number or a more specific area ?
Comment: @user2485710: Sorry, but offhand I'm really not sure.
Comment: PEGs require no left-recursion (as with LL grammars), though there are some implementations that can deal with it basically by transforming the grammar into a non-left-recursive form.  Since PEGs allow */+ closure directly, the problem of wanting left recursion for left associative operations is less important than with LL grammars
Comment: @ChrisDodd at the cost of being slightly OT, can you name a good parser generator in C/C++ for a PEG grammar ? I would like to have a reference to use as a starting point to formally define what I'm talking about here.
Comment: @user2485710: [boost::spirit](http://boost-spirit.com/home/) uses PEG grammars/parsing for its parser generator
Answer: It depends upon what type of parser you are using. If you use an LL type, you have to use right recursion.
If you use an LR type, you can use either left or right recursion. However, left recursion minimizes stack depth.
Comment: what do you mean with "type of parser" how many types of parser exist ?
Comment: Many types of parsers exist. The two main groups are LL and LR. They have subgroups like LR(1), LALR(1).
Comment: so that's why a Pascal compiler uses less memory and a C++ compiler typically requires more memory ? How about the implementation and how hard is to implement the given parser ?
Comment: Also, assuming that my grammar is a PEG grammar, what kind of parsers can meet my requirements ?
Comment: No, it isn't why a Pascal compiler uses less memory. That's because Pascal is a much simpler language, and also has a cleanly defined syntax. Pascal vs C++ has nothing to do with left vs right recursion.
Comment: @EJP I was remembering that Pascal declarations look like the "opposite" as in C++ and viceversa, that kind of left and right. I'll need to study this some more apparently .
Comment: 'That kind of left and right' is about the language itself. Your question is about grammars, in places where you have a choice of left or right recursion: for example, expressions.
Answer: Well there are two basic types of grammars:
LL(k) = Left to tight, leftmost derivation, k symbols look ahead
LR(k) = Left to right, rightmost derivation, k symbols look ahead

LR parsers are much more difficult to write by hand, however, they are more powerful then LL parsers. If you are looking at some popular parser generator tools:
ANTLR : a LL parser
BISON:  a LALR(1) parser (a type of LR parser but a bit less powerful)
CUP:    a LALR(1) parser (outputs Java / C# code)

Comment: Note that LL(k) is a subset of LR(k) -- all LL(k) grammars are LR(k).  In addition, while a grammar describes a language, there are many grammars that describe any given language.  Just because a grammar is not LL(k) (or LR(k)) does not mean that there is not a simpler grammar for the same language that is LL(k) (or LR(k))
Comment: thanks, I already have some names for already available parsers or libraries and tools that can generate a parser. My real problem now is that PEG grammars do not seem to be that popular and for example I can't find a bison or antlr equivalent for a PEG grammar, maybe it's just me getting something wrong or this grammars are not that popular as left or right grammars.
Comment: Well I have only worked with CUP and Bison so far and managed to write a pascal compiler so this things are quite powerfull. IMHO, a good lexer (flex hint hint) and a good parser generator will satisfy your every need when it comes to creating new languages in a robust way:)


React js Issue while setting environment Webpack has been initialised

Question: I am setting the environment for the react js and i am facing the below error.
I am following the
link -- https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.html
Let me correct if i need to make changes
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module has an unknown property 'loaders'. These properties are valid:
   object { exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, defaultRules?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp?, strictExportPresence?, strictThisContextOnImports? }
   -> Options affecting the normal modules (NormalModuleFactory).
Comment: Link -- https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm
Comment: when i am using npm start command i am getting the above error..
Comment: Below is the code for webpack-config.js  ---var config = {
   entry: './main.js',
   output: {
      path:'/',
      filename: 'index.js',
   },
   devServer: {
      inline: true,
      port: 8080
   },
   module: {
      loaders: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
               presets: ['es2015', 'react']
            }
         }
      ]
   }
}
module.exports = config;
Answer: It wasn't expecting "loaders" to be under module. The configuration looks different according to the docs.
https://webpack.js.org/concepts/loaders/
Try:
var config = {
    entry: './main.js',
    output: {
        path:'/',
        filename: 'index.js',
    },
    devServer: {
        inline: true,
        port: 8080
    },
    module: {
        rules: [{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['es2015', 'react']
                }
            }
        }]
    },
};

module.exports = config;


The relation between the closure and the contraction of a matroid M.

Question: Here is the relation I am trying to justify:
$cl_{ M/T}(X) = cl_M(X \cup T) - T$ for all $X \subseteq E - T.$
Why this relation true?
Any proof will be greatly appreciated!
**Here are all what I know about contraction and the closure operator: **
The contraction of $T$ from $M$ is given by $$M/T = (M^* \setminus T)^*$$ where the backward slash means deletion.
I know the following relations between contraction and the closure operator and deletion and the closure operator:
For all $X \subseteq E - T,$ we have
$$cl_{M\setminus T}(X) = cl_{M}(X) - T.$$
$$cl_{M/T}(X) = cl_{M}(X \cup T) - T.$$
I also know some identities about contraction and deletions, but I am not sure if they are useful here, I also know the spanning sets of deletion and contration of a matroid and the condition on the rank function of this matroid $M$ and $T$ that makes contraction same as deletion. But I do not know how to combine these ideas to prove the above identity. Any help will be greatly appreciated!
Comment: @Phicar I am editing my post with more details
Comment: So what have you tried? What is your definition of contraction?
Answer: So, recall that the independents of $M/T$ are sets $A\subseteq E\setminus T$ such that $A\cup R$ is independent on $M$ and $R$ is a maximal independent subset of $T$. This implies that $r_{M/T}(X)=r_M(X\cup T)-r_M(T)$ (or you can use duality and that the rank of deleting is just restricting the rank of the matroid). Now, to show the equality, we can take $x \in cl_{M/T}(X)$ and so $r_{M/T}(X\cup x)=r_{M/T}(X)$ which implies that $r_M(X\cup T\cup x)=r_M(X\cup T)$ and so $x\in cl_M(X\cup T)$. Furthermore, as $x \in E\setminus T$ then $x\not \in T$ so $x\in cl_M(X\cup T)\setminus T$. All of these implications are reversible.
Comment: @Secretly Cause the groundset of $M/T$ is $E\setminus T$.
Comment: Why $x \in E \setminus T$, could you clarify this please?


Angular 2 Select/unselect all checkbox

Question: i want to select/unselect all checkbox. i tried refering other code but nothing worked for me
below is my code. selecting unseleting particular unit is working for me. basically when i clicks on div it selects/unselects checkbox and adds color to it. but i am confused with select all/unselect all
please help me to do it with my code

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { ReactiveFormsModule, FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
  <form [formGroup]="form">

    <input type="checkbox" />Select all
    <input type="checkbox" />unSelect all

          <input type="checkbox" formControlName="{{i}}"/>

{{ unit.num }}

{{ unit.desc }}

  </form>
  `,
  styles: [`.unit-selected { color: red; }`]
})
export class App implements OnInit{
  private units = [
    {num: 1, desc: 'Decription'},
    {num: 2, desc: 'Decription'},
    {num: 3, desc: 'Decription'},
  ];
  private form: Form;

  constructor (private fb: FormBuilder) {}

  ngOnInit () {
    this.form = this.fb.group({
      unitArr: this.fb.array(
        this.units.map((unit) => {
          return this.fb.control(false); // Set all initial values to false
        })
      )
    });
  }

  // Shorten for the template
  get unitArr (): FormArray {
    return this.form.get('unitArr') as FormArray;
  }

  onClick(i) {
    const control = this.unitArr.controls[i];
    control.setValue(!control.value); // Toggle checked
  }
}

@NgModule({
  imports: [ BrowserModule, ReactiveFormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
Comment: i guess you are looking for something like [this](https://embed.plnkr.co/h9wFGz/)
Comment: Why not post this as an Answer instead of a Comment then?
Comment: Don't write this: `formControlName="{{i}}"` but this instead: `[formControlName]="i"`
Comment: To answer your question, you can simply patch all values (https://angular.io/api/forms/AbstractControl#patchValue) to false/true
Comment: Why are people providing answers in the comments?
Answer: Making a combination of the comments provided by Rahul and ncohen we can use patchValue here.
As for the unselecting all checkboxes, I changed it to a button in this answer, to me it seemed that a checkbox wasn't really suitable (?) because of handling the tick in the checkbox. But that is up to you if you rather use a checkbox :)
As for checking if the "Select All" checkbox should be checked or not, you can do:
[checked]="checkAllSelected()"

and then in TS:
checkAllSelected() {
  return this.form.controls.unitArr.controls.every(x => x.value == true)
}

Here we then must remember that this is run on each change detection. So perhaps you'd want to use a variable instead, that is of course depending on the case, i.e how costly this would be for you, but I don't think it would be in this case.
So this is how your template could look like:

   <input type="checkbox" [checked]="checkAllSelected()"
         (click)="selectAll($event.target.checked)"/>Select all

<button (click)="unselectAll($event.target.checked)">Unselect All</button>

where we pass the status of the checkbox to template and evalate to either check all or uncheck all:
selectAll(isChecked) {
  if isChecked
     this.form.controls.unitArr.controls.map(x => x.patchValue(true))
  else
     this.form.controls.unitArr.controls.map(x => x.patchValue(false))
}

And of course when user clicks the uncheck button:
unselectAll() {
  this.form.controls.unitArr.controls.map(x => x.patchValue(false))
}

DEMO: http://plnkr.co/edit/O194WEimjf3XzfiIrWF0?p=preview

Angular 2 Select/unselect all checkbox


Acessar função do controller pela diretiva

Question: ola a pergunta e simples tenho um botao na minha diretiva que e claro ja tem um ng-click("alterardata();") a regra e que o controller que chame essa diretiva tenha essa função por padrao mas o problema e que clico no botao e nao funciona coloquei outro botao na pagina principal e esse funciona
Answer: Utilize um callback (em português, chamada de retorno).
Na sua diretiva, defina uma propriedade de escopo que receberá o callback do controller:
app.directive('exemploDiretiva', function () {
    return {
        restrict: 'AE',
        template: '
Olá!
',
        scope: {
            chamadaCallback: '&' // <- Define uma referência de função externa
        },
        link: function (scope, element, attrs) {
        }
    };
});

Isso feito, defina o valor na view:
<exemplo-diretiva chamada-callback="meuMetodoDoController(arg1)"></exemplo-diretiva>

Perceba que, enquanto que a definição é feita no formato camelCase (chamadaCallback), a parametrização deve ser feita em formato lowercase-dash (chamada-callback).

Com isso feito, crie o método meuMetodoDoController no controller - ele será invocado quando, na diretiva, você invocar o callback da seguinte maneira:
scope.chamadaCallback('qualquerParametroQueVoceQuiser');

Comment: acho que estou quase la esta dando esse erro TypeError: Cannot use 'in' operator to search for 'alterarPeriodo' in 1 no template comtem(ng-click="funcaoPeriodo(0)"), na directive de nome painel contem (funcaoPeriodo: "&"), na pagina principal contem
Comment: Em funcao-periodo="alterarPeriodo()" Você está passando o resultado da função. Ao invés disso, tente funcao-periodo="alterarPeriodo".
Comment: ja tentei e da o mesmo erro ainda nao sei oq fazer :?


Finding if a Set containing a given object or not

Question: A Set contains only one object of entity Community and i am using two objects of same value and one of the objects is stored in that Set
Set<Community> communties = template.get(User.class, "1").getCommunities();
Community com = template.get(Community.class, 1);

for(Community community : communties)
        System.out.println(community.equals(com));

System.out.println(communties.contains(com));

First Statement prints true but Second Statement prints false. Why?
Comment: Have you overridden equals() but not hashCode() in your Community class?
Comment: yes! overriden only `equals()` and not `hashCode()`
Comment: I have posted the solution as an answer, please kindly accept it if you feel it's OK so that question registers as solved. Thx.
Answer: You must override hashCode() as well as equals(), otherwise, the Set won't find the correct bucket for the object and will not even arrive to the equals() comparison.
You can use Eclipse "Source" menu to generate pretty decent equals() and hashCode() methods.
Comment: Paste your equals() and hashCode() methods, please.
Comment: My `Community.java` contains other two Set and if i removed from `equals()` and `hashCode()`.. it is working!
Comment: it means other two entities also should override `equals()` and `hashCode()` ??
Comment: Is it working right already? With hashCode() and equals()? Anyway, here you have an in-depth explanation of hashCode() and equals() implementation (worth reading it to clarify concepts): http://www.javaranch.com/journal/2002/10/equalhash.html


Einstein summation in tensor calculus

Question: I am looking at the Schaum's Outlines "Tensor Calculus" by David C. Kay, and on page 3, the following non-identity and identity are presented:
$$
\begin{align}
a_{ij}(x_i + y_j) &\neq a_{ij} x_i + a_{ij} y_j\tag{1}  \\
a_{ij}(x_j + y_j) &= a_{ij} x_j + a_{ij} y_j \tag{2}
\end{align}
$$
Let's assume that $i,j$ both run over $\{1,2\}$ for simplicity.
For (2), I write:
$$\begin{align}
a_{ij}(x_j + y_j)
&= a_{i1}(x_1+y_1)+a_{i2}(x_2+y_2) \\
&= a_{i1}x_1+a_{i2}x_2+a_{i1}y_1+a_{i2}y_2 \\
&= a_{ij}x_j+a_{ij}y_j
\end{align}$$
where $i$ is a free index, and thus only $j$ is summed over.
For (1), I write:
$$\begin{align}
a_{ij}(x_i + y_j)
&= a_{11}(x_1+y_1)+a_{12}(x_1+y_2)+a_{21}(x_2+y_1)+a_{22}(x_2+y_2) \\
&= (a_{11}+a_{12})x_1+(a_{21}+a_{22})x_2+(a_{11}+a_{21})y_1+(a_{12}+a_{22})y_2\\
&=\ (a_{i1}+a_{i2})x_i+(a_{1j}+a_{2j})y_j
\end{align}$$
Is that correct? Can we go further, or is that as much as we can derive?
EDIT it seems that in (1) the inequality results from the RHS being illegal: in one term on the RHS, i is free, whereas in the other, j is free. The LHS however is legit, and the derivation I propose seems to hold, but cannot proceed any further. In (2), the situation is much better, because the index i is free in both the LHS and RHS.
EDIT 2 the LHS for (1) is actually illegal and meaningless because $x_i+y_j$ is not a proper vector. That combination of $i$ and $j$ indices does not make sense. So for (1) both the LHS and RHS are illegal, and rather than an inequality, it should have bee pointed out that neither the LHS nor the RHS can be written as such.
Answer: Your Eq (1) is wrong because it's not a good tensor equation. The quantity $x_i + y_j$ doesn't have any meaning.
Remember that index notation is used in this manner to simplify the writing of tensors. So, $a_i$ is a shorthand notation to say "the components of the tensor $\mathbf{a} = \sum_i a_i \hat{e}^i$ (written in the basis $\hat{e}^i$)".
When you write $x_i + y_j$, this is not the shorthand for any tensor.
It may help for you to understand tensor math in terms of the underlying tensors, and recognize that index expressions are simply a shorthand to express how the components work in a given (possibly abstract) basis.
For example: if you have tensors $\mathbf{x} = \sum_i x_i \hat{e}^i$ and $\mathbf{y} = \sum_i y_i \hat{e}^i$, then summing the two together, you get $\mathbf{x} + \mathbf{y} = \sum_i (x_i + y_i) \hat{e}^i$. If you then want to contract the resulting sum with the first slot of a two-tensor $\mathbf{a} = \sum_{ij} a_{ij} \hat{e}^i \otimes \hat{e}^j$, then perform the contraction. This leads to the tensor $a_{ij} (x_i + y_i) \hat{e}^j$, which has components $a_{ij}(x_i + y_i)$.
(Note: In this post, all sums can be neglected in favor of Einstein summation convention if desired.)
Comment: Thanks Jolyon! Yes, the more I get comments about it, the more I can see that (1) is meaningless. When I first saw that $\neq$ I thought the author meant that from the LHS you could get to something that would not be the RHS, but it looks like both sides are actually non-sensical. I wish the author had been more explicit about this.
Comment: Thanks - I fixed the typo at the end.

Einstein summation in tensor calculus


Distribute a population size based on fractions using random number generator drand48()

Question: I have a population size of say 5000 people. Every person belongs to either A, B, C or D category. I want to split the population as per a given fraction provided by user. for example, 99% of A, 0.4% of B, 0.3% of C and 0.3% of D ( total = 100% ). I just want to confirm whether my approach for this solution is correct or not. I use random numbers to do this.
let,
fa = fraction of A, fb = fraction of B, fc = fraction of C and fd = fraction of D.

my algorithm is as follows: I write a function :-->
 function( returns a category type A,B,C or D)
 {
   double r = drand48();  // gives me random number between 0 and 1.0 (uniform dist)
   if( r < fa )
      return A;
   if( fa < r < (fa+fb) )
      return B;
   if( (fa+fb) < r < (fa+fb+fc) )
      return C;
   if( (fa+fb+fc) < r < (fa+fb+fc+fd) )
      return D;
 }

I just want to make sure, the population is distributed correctly as per the given fraction of each type provided.
I am not sure what category to tag this is.(sorry for the trouble)
Answer: Your algorithm will give the distribution on average, it doesn't guarantee the distribution. I guess the following is enough: Set $a$, $b$, $c$, $d$ to the number of elements in each category. Generate a random number $x$ uniformly between 0 and 1. Now, if $x \le a / (a + b + c + d)$, add the element to group $A$ and decrease $a$ by one; and do the same for the other groups. This ensures that a group that is full won't get more members. My random-fu isn't up to proving that this will select a distribution uniformly, however.
Comment: It will do it uniformly, perhaps easiest to see if you had as $5000$ categories with one member each. When you say "do the same for the other groups" you mean add to $B$ if $\dfrac{a}{a+b+c+d} \lt x \le \dfrac{a+b}{a+b+c+d}$ and then decrease $b$ by $1$ etc.
Answer: In principle your code is right, except that there is a minuscle probability that r might equal e.g. fa+fb exactly, in which case none of the ifs triggers.
You can drop the <r part of the condition (if repeated comparison is valid in your programming language of choice at all) anyway.
If it is given that fa+fb+fc+fd equals 1, you can also just return D if the third if fails.
So much for potential coding problems.
For the distribution, you are aware that the resulting population will not be distributed completely according to the given proportions, but rather like a sample from an infinite population where the proportions are valid? For example with $5000$ as size and $0.003$ for D, the actual number of Ds produced need not be $15$, but can easily turn out as e.g. $11$ or $19$.
Comment: yes, i observed that in my code. I wont get exact population size as such.


Reference about eigenvalue of Laplace operator

Question: My teacher tell me  that the eigenvalue question
$$
\left\{
\begin{aligned}
& -\Delta u=\lambda u   ~~~x\in \Omega   \\
& ~~~ u=0  ~~~~~~~~~~~x\in\partial\Omega
\end{aligned}
\right.
$$
 has been resolved . All eigenvalue such that $0<\lambda_1<\lambda_2... $ and $\lambda_k \sim C_n(\frac{k}{|\Omega|})^{2/n}$, and $\lambda_1(\Omega)\ge\lambda_1(B) \text{ when }~|\Omega|=|B|$ and  $B$ is ball. And ......
(Sorry, I know it's very inaccurate).
I want to know which paper contains above content.
Answer: This article contains the derivation of some basic facts. The growth of the $\lambda$ to $\infty$ is shown, and if you look closely at the proof you also get an estimate, but not as good as you have asked for I think.
On this page you'll find references to more special results, including the growth estimate you've asked about.


Divisibility by n for 3- digit number

Question: We have 3 numbers:
$\; \overline{xyz}=100x+10y+z$, $\; \overline{yzx}$ and $\; \overline{zxy}$, all 3 divisible by the same number $n$.
Prove that the number $P=x^3+y^3+z^3-3xyz$ is also divisible by n.
$n \mid 100x+10y+z$
$n \mid 100y+10z+x$
$n \mid 100z+10x+y$
$n \mid 111x+111y+111z \Leftrightarrow n \mid 111(x+y+z)$ but since 111 is not a prime, we can't say for sure if $n \mid (x+y+z)$.
Also $P = \frac{1}{2}(x+y+z)((x-y)^2+(y-z)^2+(z-x)^2)$.
So if I managed to prove that $n \mid (x+y+z)$ I think it would be sufficient, right?
Can you help me?
Comment: It isn't always the case that $n\mid(x+y+z)$, as the case $x=y=z=1$, $n=111$ shows.
Comment: Some reductions: if $\gcd(x,y,z,n)>1$, then one can divide each of $x,y,z,n$ by that gcd and the new statement implies the old statement. So we can assume $\gcd(x,y,z,n)=1$. In this case, taking various linear combinations (for instance $10\overline{xyz}-\overline{yzx} = 999x$) proves that $n$ must divide $999=27\times37$. So it suffices to prove the result for $n\in\{3,9,27,37\}$, if that helps.
Answer: Introduction
$\newcommand{\d}[1]{\overline{#1}}$As Greg mentions in the comments, we can make significant improvements. Let $P = x^3+y^3+z^3 - 3xyz$ for $x,y,z$ in context. For $\d{xyz}$ a number, we refer to both $\d{yzx},\d{zxy}$ as its cyclic counterparts or cyclic permutations. I am sure you can generalize this to $m$ digits, which I require only for the last extra section.
$\gcd(n,x,y,z) = 1$ WLOG
Indeed, suppose that we proved the statement for the case $\gcd(n,x,y,z) = 1$. Then, for $\gcd(n,x,y,z)=d>1$, we may consider the statement for $\frac{n}d, \frac xd,\frac yd,\frac zd$ : note that $\frac nd$ will still divide each of the cyclic counterparts of $\d{\frac xd\frac yd\frac zd}$, so by the statement , $\frac{x^3+y^3+z^3-3xyz}{d^3}$ an integer multiple of $\frac nd$, which implies that $x^3+y^3+z^3-3xyz$ is an integer multiple of $n$.
$n$ divides $999$
Now, suppose that $\gcd(n,x,y,z)  =\gcd(n,\gcd(x,y,z)) = 1$. Note that $n$ divides $10\d{xyz} - \d{yzx} = 999x$, and similarly $n$ divides $999y$ and $999z$.
Now, by Bezout's theorem, there is an integer linear combination of $x,y,z$ given by  $ax+by+cz$ which equals $\gcd(x,y,z)$. Then $n$ divides $999(ax+by+cz) = 999\gcd(x,y,z)$ implying that $n$ divides $999$ by our assumption. Thus, we may restrict ourselves to divisors of $999$.
The obvious cases
The divisors of $999$ are : $1,3,9,27,37,111,333,999$.
For $1$ the statement is obvious. For each of $999,333,111$, if $\d{xyz}$ is a multiple then $x=y=z$ so $P=0$.
For $3,9$ the statement is clear , because $\d{xyz}$ is a multiple of $3$ or $9$ if and only if $x+y+z$ is , respectively (follows from a divisibility test for $3$ and $9$ : take the sum of digits etc.), and $P$ is an integer multiple of $x+y+z$. Thus, we are left with just $27$ and $37$. The techniques for these two are somewhat different.
The case $n=37$
Let $n=37$.
We know that $\d{xyz}$ and all its cyclic permutations are multiples of $37$. Let us pick the cyclic permutation that has the lowest unit digit i.e. with $z\leq x$ and $z \leq y$. For example, in the family $592,925,259$ we choose $592$, so that $x=5,y=9,z=2$. So we assume $z\leq x , z \leq y$.
Since $37 \times 3 = 111$, we can subtract $1$ from each digit of a ($3$-digit) multiple of $37$ and we will still get a multiple of $37$. For example, from $592$ we get $481$ which is still a multiple of $37$. In algebraic terms , we get that $\d{(x-1)(y-1)(z-1)}$ is also a multiple of $37$ (this is the number with digits $(x-1)$,$(y-1)$,$(z-1)$ in that order). Going like this $z$ times, we get that $\d{(x-z)(y-z)0}$ is a multiple of $37$ i.e. $\d{(x-z)(y-z)}$ is an at most (since $x-z=0$ is possible) two digit multiple of $37$.
For example, starting from $592$, we get to $481$ then to $370$. Since $592$ is a multiple of $37$, so is $370$ and therefore so is $37$. To take another example, take $962 = 37 \times 26$, subtracting one from each digit gives $851$ and then $740$. So $740$ is a multiple of $37$, hence $74$ is a multiple of $37$.
The only (at most) two digit multiples of $37$ are $0,37,74$.  So, we must have that $\d{(x-z)(y-z)} = 0,37,74$. This gives three cases : $x=y=z$, $x-z=3,y-z=7$ and $x-z=7,y-z=4$.
Now if $x=y=z$ then $P = 0$.
If $x-z=3,y-z = 7$ then $x=z+3,y=z+7$ so we have : $P = (z+3)^3+(z+7)^3+ z^3 - 3z(z+3)(z+7) = 37(3z+10)$ is a multiple of $37$.
If $x-z=7,y-z = 4$ then $x=z+7,y=z+4$ so we have : $P = (z+7)^3+(z+4)^3+z^3 - 3z(z+4)(z+7) = 37(3z+11)$ is a multiple of $37$.
Thus, $n=37$ works out.
The case $n=27$
For $27$ the task can be accomplished from the factorization $$P = \frac 12(x+y+z)((x-y)^2+(y-z)^2+(z-x)^2)$$ Note that the $\frac 12$ is redundant, we only need to prove that $27$ divides $2P$.
Now, $9$ divides $x+y+z$ from the divisibility rules for $9$, so we only need to prove that $3$ divides $x^2+y^2+z^2 -xy-yz-xz$ since then $27 = 3 \times 9$ will divide the product of these. Recall that $3$ divides $x+y+z$, but then:
$$
x^2+y^2+z^2 -xy-yz-xz = (x^2+y^2+z^2 +2xy+2yz+2xz) - 3(xy+yz+zx) \\
= (x+y+z)^2 - 3(xy+yz+zx)
$$
which is a multiple of $3$. Hence, we are done.

A related property of divisors of $999$
All the divisors of $999$ have a property, one that I interestingly had a crush on some fourteen years ago, because I'd discovered some generalization to $n$ digits as well :

For $n$ a divisor of $999$, let $\d{xyz}$ be a multiple of $n$. Then $\d{yzx},\d{zxy}$ are also multiples of $n$.

That is, if one of these cyclic permutations is a multiple of $n$ then the rest of them all are. This generalizes :

For $n$ a divisor of $10^m-1$ and any $m$ digit multiple of $n$ , any cyclic permutation of the digits of $m$ (while retaining leading zeros) results in a number which is also a multiple of $n$.

For example, $271 | 99999$, so qualifies. To generate free multiples of $271$ (this was pastime in school, if you like) we have $271|27100$ and we would get $271|10027$ and $271|71002$ for free.
I leave the above as an exercise.
Comment: Teresa, fantastic solution. Can you please elaborate a bit more on these two points: "there is an integer linear combination of x, y, z" etc. Since we have considered them as co-primes, why do we need this part? Also: in the part where you examine n=27: You say that n divides x+y+z, why is this?
Comment: The first one is called Bezout's lemma : if the $\gcd(x_1,...,x_n) = d$ then we can find integers $a_1,a_2,...,a_n$ so that $a_1x_1+...+a_nx_n = d$. I did this with $\gcd(x,y,z) = d$ and got the existence of $ax+by+cz  =d$. The point is, $x,y,z$ need not be coprime, but whatever their $\gcd$ is, that is coprime to $n$. For $n=27$, $27= 9 \times 3$  so I checked that $x+y+z$ is a multiple of $9$ (using the divisibility test for $9$ : if $\overline{xyz}$ is a multiple of $9$ then so is $x+y+z$) and then I checked that $x^2+y^2+z^2-xy-yz-zx$ is a multiple of $3$.
Comment: Fantastic. Also the part with 37 is not so clear to me, so if you could add some more details, I would appreciate it.
Comment: @ChenAavaz I will do that.
Comment: In the $37$ case, you can choose the cyclic permutation where $z$ is the smallest digit, but cannot then guarantee that $x\ge y$. You'll need to check the $x\le y$ case too, so need to check the $x-z=3$, $y-z = 7$ case.
Comment: @JaapScherphuis Good point! I will edit that in, thanks.
Comment: @JaapScherphuis You may check the edits, thank you very much for the error spotted.
Comment: @ChenAavaz You may check the edits, thank you very much for asking for clarification and accepting the answer.
Answer: COMMENT.-We have the linear system $$\begin{pmatrix}100&10&1\\1&100&10\\10&1&100\end{pmatrix}\begin{pmatrix}x\\y\\z\end{pmatrix}=\begin{pmatrix}na\\nb\\nc\end{pmatrix}$$ whose determinant is equal to
$\Delta=998001=3^6\cdot37^2$. Calculations give
$$x=\frac{n999(10a-b)}{3^6\cdot37^2}=\frac{n(10a-b)}{3^3\cdot37}(\text{ note that }3^3\cdot37=\sqrt{\Delta})$$ and
$$y=\frac{n(10b-c)}{3^3\cdot37}\\z=\frac{n(10c-a)}{3^3\cdot37}$$
Therefore we have after calculations $$x^3+y^3+z^3-3xyz=\frac{n^3}{\Delta}(a^3+b^3+c^3-3abc)$$ This shows that if the proposition is true then $$\frac{n^2}{\Delta}(a^3+b^3+c^3-3abc)\in \mathbb Z$$ This should not be difficult to prove while holding clearly from the system the equality $n(a+b+c)=3\cdot37(x+y+z)$.
Comment: I love this observation. I will try to do something in the future using this trick.

Divisibility by n for 3- digit number


binary subtraction

Question: I am trying to solve binary subtraction:
$$11000_2 - 1011_2 = 1001_2$$
I know that it should be $1001_2$, when checking with answer key however I am not sure how it was calculated as I get different result : $1011_2$, as $0-1$ should give $1$.
Thank you for your help in advance!
Comment: And there should be 1101, if your question has no typos.
Comment: \$18 - \$0b = $0d
Comment: Translation: `24 - 11 = 9` :)
Answer: Don't forget to "borrow" when subtracting $1$ from $0$.
Here it is in "slow motion:"
\begin{array}{c}
&1&\not1 ^ 0 & \not0^\color{red}1 & \not0^\color{red}1&^10\\
-&&1 & 0 & 1 & 1\\\hline
&&&&&1
\end{array}
\begin{array}{c}
&\not 1^0&^10 & \color{red}1 & \color{red}1&^10\\
-&&1 & 0 & 1 & 1\\\hline
&&1&1&0&1
\end{array}
Note: If the answer key has listed $1001$ as the correct answer, they're wrong... <code>:)</code>
Comment: How come we got 1 instead of 0 in the third place? ( 0f 10110)
Comment: @NadiaS I've added some color to attempt to make that clearer.  Basically, the $1$ that we have "left-over" after borrowing replaces the $0$.
Comment: Thank you so much for your help. I think I understood now!
Answer: Computing $1111_2-1011_2$ is easy: you just change each $0$ into $1$ and each $0$ into $1$, getting $0100_2=100_2$. Now adding $1$ is easy as well: you get $101_2$.
I'll leave out the subscript $2$ from now on.
Why is this important? Because you can say
$$
11000-1011=11000+(10000-1011)-10000
$$
and $10000-1011=1+1111-1011=101$ as seen before. Thus we do an addition
$$
\begin{array}{rc}
11000&+\\
101&=\\
\hline
11101
\end{array}
$$
and an easy subtraction
$$
\begin{array}{rc}
11101&-\\
10000&=\\
\hline
1101
\end{array}
$$
Additions are easier than subtraction, because you carry only to the next column (maybe several times), while borrowing can jump several columns away.
Another example: $1001001-10110$. Compute $111111-010110=101001$, so $1000000=101001+1=101010$. Then
$$
\begin{array}{rc}
1001001&+\\
101010&=\\
\hline
1110011&-\\
1000000&=\\
\hline
110011
\end{array}
$$
Final checks:

$11000_2=24$, $1011_2=11$; $1101_2=13$.
$1001001_2=73$, $10110_2=22$; $110011_2=51$.

binary subtraction


How to keep domain consistency (with or without www)?

Question: Some search engines make a difference if the site is found in example.com or www.example.com. So it's important to redirect all users from example.com/some-page to www.example.com/some-page, or the other way around.
Is it possible in Drupal 7?
Comment: it might be done via `.htaccess`
Answer: I found the answer. The .htaccess file contains the following comments.
<code># If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]
</code>
Uncommenting one of those rewriting rules is all you need to do.
Comment: Just make sure that you check when you update Drupal core to ensure that the .htaccess file doesn't get overwritten.


Evaluating the sum of a partial geometric sequence using Sigma notation

Question: I have a worksheet from my instructor with this problem on it, but the solution he has given is different from what I got, and I don't know why.
I'm not sure how to input the Greek letter sigma, but what it tells me is that I need to start with 1 ($k=1$), and end with $k=50$. The formula I am told to use is $3(-2)^{k-1}$
$$\sum_{k=1}^{50} 3(-2)^{k-1} $$
With this I found that $a=3$ and the common ratio is $-2$, so I used the partial sum of geometric sequences $a \frac{1-r^n}{1-r}$ I came up with this:
$$3\cdot\frac{1-(-2)^{50}}{1-(-2)} = 3\cdot\frac{1-2^{50}}3 = 1-2^{50}$$
but according to my math professor the solution is this
$$3\cdot\frac{1-(-2)^{50}}{1-2} = 3\cdot2^{50}-3$$
What did I do wrong? I asked him about it via e-mail, but I haven't received a response and I have a test tomorrow morning.
Comment: If the common ratio is in fact $r = -2$, then your calculation is correct.
Comment: Hint: the sum formula that you used is valid for powers from $0$ to $n-1$.
Comment: "*I'm not sure how to input the Greek letter sigma*" - Check out [this page](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for a primer on how to format mathematics on the site.  In particular, you are looking for \sum\limits_{k=1}^{50} to output $\sum\limits_{k=1}^{50}$
Answer: From what I can interpret from what you have written, your answer appears to be correct. The denominator should be $(1-(-2))$ and not $(1-2)$.


Continuity of positive and negative parts of a function

Question: Let $X$ be a topological space and let $f: X\to\mathbb{R}$ be a continuous function where $\mathbb{R}$ is endowed with standard Euclidean topology.  I need to show that $f^+:=\max\{f,0\}$ and $f^-:=-\min\{f,0\}$ are continuous. Am really stuck on this, so any help will be greatly appreciated, thanks in advance.
Comment: $f^{+}$ is continuous because it can be rewritten as a function composition $f^{+} = g \circ f$ where $g : \mathbb{R} \ni x \mapsto \max(x,0) \in \mathbb{R}$ is a continuous function.
Answer: max{f,0}= (|f|+f)/2. Since $f$ is cont. so is $|f|$ and hence $f^+$ is cont.
Can you find similar expression for $f^-$?
Comment: $f^-=(|f|-f)/2$ but how do I show that $|f|$ is continuous, if $X$ is a metric space then it is easy using $\epsilon-\delta$ definition, but if $X$ is just a general top space, how would go about showing $|f|$ is continuous?  Any help greatly appreciated.
Comment: @Jens: |f|= g composed f where g:$\mathbb{R} \rightarrow \mathbb{R}$ is defined by $g(x)=|x|$. g and f are cont. and hence so is their composition.
Answer: By definition, a function $g:X\to\Bbb R$ is continuous if for every $x\in X$ and every $\epsilon>0$, there is a neighborhood $U\ni x$ such that $\forall y\in U:|f(y)-f(x)|<\epsilon$. I'm just writing this explicitly so that you can see how this comes together.
The theorem follows easily from $|f^+(x)-f^+(y)|\le|f(x)-f(y)|$, since the "positive/negative part" maps are metric maps (you can also show this explicitly). Insert into the definition and you're done.


New angular project, generating new component and selector is not recognized

Question: Before I begin, I have tried every possible stackoverflow/github solution that I've found online. None of them work. Most of the questions involved the user creating a custom module and there was a configuration issue. Mine is not the case as this is a brand new project, with only 1 component generated and being displayed. I've followed the angular tour of heroes twice so far and it has worked. I have created an existing project already and it was working for a few days then suddenly stopped. I will also add that when I am navigating to the website, there are no console errors, everything runs successfully. There are only issues when I run ng test.
Problem
I created a new angular project because my old project suddenly ran into the problem where I can't use the selector of a newly generated component as an html tag in the app.component.html file. This is the error I get when I run ng-test:
Error: Template parse errors:
'app-test' is not a known element:
1. If 'app-test' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

Steps
I ran the command ng new test-project to create a new angular project. I went inside the folder, and ran ng generate component test. This created my test component successfully.
Here is the test.component.ts file:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

Here is the app.module.ts file:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';

@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Lastly, here is my app.component.html file:
<app-test></app-test>

Comment: Possible duplicate of [Angular 2 Karma Test 'component-name' is not a known element](https://stackoverflow.com/questions/44504468/angular-2-karma-test-component-name-is-not-a-known-element)
Answer: If you didn't declare this component into your testbed, then the testbed isn't aware that this component exists.
In your test, provide your new component like this
TestBed.configureTestingModule({
  declarations: [AppComponent, TestComponent],
})
  .compileComponents();

Comment: It doesn't add the component to the testbed because you're supposed to mock the component, not use the real one. And yes, for every dependency you add to your component, you should add (a mock of) it ot your testbed.
Comment: Thank you so much! I find it very surprising that the angular-cli doesn't automatically add the necessary components to the tests, since it auto-populates just about everything else when you create a component. Also, does this mean that for every module/component I add to the declarations/imports section in NgModule, I need to add to the app.component.spec.ts file?


What does it mean by "The differential of a map is independent of coordinate charts"?

Question: We know that the differential is represented by the Jacobian matrix $[\partial F^i/\partial x^j(p)]$, so it definitely depends on the choice of coordinates $x^j$. But the statement in question is written in Tu's introduction to smooth manifolds in the discussion of regular level set theorem. Can somebody please explain what that statement mean?
Comment: I don't have the book with me at the moment, but I'm sure what he means is that the differential is an operator and, as such, it does not depend on the choice of coordinates. Of course the matrix $\partial F_i /\partial x_j$ does, but that's just a representation as you've said. The operator is intrinsically defined.
Comment: The differential at a point is a linear map between the tagentn spaces. It has nothing to do with coordinate charts. A choice of coordinate charts on domain and codomain gives you bases on the respective tangent spaces and your expression is a representation of the differential as a matrix relative to these bases.
Answer: Quick answer:
The differential of a map associate a vector $df[v]$ to any vector $[v]$, and that vector $df[v]$ depends only on $v$, not on the coordinate system.
Detailed discussion:
What is a map? A map $f:M\to \mathbb R^n$ associates to any point  $x\in M$ a vector $f(x)$. The value $f(x)$ depends only on the point, not on local coordinates.
What is the differential of a map? The differential of a map is not a function from $M$ to $\mathbb R^n$. One usual way to define the differential of a function $f:M\to \mathbb R^n$ is the following:
$f$ is differentiable at $x\in M$ if there exists a linear map $L$ so that $$f(x+\epsilon v)=f(x)+\epsilon L(v)+o(\epsilon)$$
In other words, if $f$ is approximable by a linear map at first order. So, now look at $L$. Who is $L$? It is a linear map bur from where to where? The origin vector space is the tangent space of $M$ at point $x$, usually denoted $T_xM$, and the target space is the tanget space at $f(x)$. In the present case, we can canonically identity the tangent space at $f(x)$ with $\mathbb R^n$ (but if you have  $f:M\to N$ you have to take $T_{f(x)}N$). So $$L\in\hom(T_xM,\mathbb R^n)$$.
The map $L$ is called the differential of $f$ at $x$ and it is usually denoted by $d_xf$.
Now, it is a general linear algebra fact that if you have two finite dimensional vector spaces $V,W$ then, for any choices of basis $B_V,B_W$ of $V$ and $W$, you can associate to any $F\in\hom(V,W)$ the matrix of $F$ in those chosen basis. The linear map $F$ exists independently on $B_V,B_W$: it is the matrix that changes when you change coordinates.
Well, for $df$ is the same: the linear map $d_xf:T_xM\to \mathbb R^n$ does not depend on coordinates, the Jacobian matrix --- which describes $d_xf$ as matrix --- does indeed depend on coordinates.
Comment: Thanks! so in other words, we have a differential map from a vector space to a vector space which only depends on the choice of the point $x$ and the function $f$. But since those are vector spaces and $f$ is a linear map, we can choose the basis and find only the coefficients of linear combination of the basis. but these coefficients depends on the choice of basis!


Android Any API for Speech to Text for android 2.3 or above which works offline?

Question: I need Offline Speech Recognition and Speech to Text API. I have found sphinx android client, but its much expensive for RAM and Processor for android phones having API level 8.
Is there any library or any help regarding this?
Comment: Might be related :-http://stackoverflow.com/questions/11893788/use-offline-voice-to-text-in-android-4-1-jelly-bean-from-my-application
Answer: API (Application Programming Interface) generally infers that you are connecting to a server online.
CMU's PocketSphinx probably is your best option as far as offline Speech To Text on Android, because it was specifically made with low powered devices in mind. I think that PocketSphinx is different from Sphinx client for Android that you referenced.
http://cmusphinx.sourceforge.net/2013/01/pocketsphinx-for-android-in-google-play/


html - Duas scrollbars verticais no Android

Question: As Custom Scrollbars e a scrollbar padrão do Chrome estão em conflito, devido ao height:100vh. Mas acho que o Chrome detecta como se 100vh fosse equivalente ao numero de pixels Y do Android, e não o da WebView.
Enfim, eu quero que o site fique em 100% da tela do Chrome Canary, assim removendo a scrollbar padrão como na foto [1].
Mas há um porém, a minha tela é MaxVision, e muitos valores ficaram incomatíveis com a minha tela um deles é a dpi.
No StackOverflow eu vi uma pergunta relacionada, porém na minha tela não deu certo.
Eis o código HTML
<!DOCTYPE html>

    <meta name="viewport" content="user-scalable=no,width=device-width">
    <link href="css/styles.css" rel="stylesheet">

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

      h

No código acima, fiz com que o conteúdo da página fosse maior que a minha tela.
O erro deve estar aqui:
::-webkit-scrollbar {
    -webkit-appearance: none;
    margin:0;
}

::-webkit-scrollbar:vertical {
    width: 12px;
}

::-webkit-scrollbar:horizontal {
    height: 12px;
}

::-webkit-scrollbar-thumb {
    background-color: rgb(255, 0, 0);
}

::-webkit-scrollbar-track {
    background-color: #000;
}

::-webkit-scrollbar-button {
    background-color:#0f0;
    width:12px;
    height:12px;
}

}
body {
    position: relative;
    display: flex;
    flex-direction: column;
}

html,body {
    margin: 0;
    padding: 0;
    border: 0;
    overflow-x: scroll;
    overflow-y: scroll;
    max-height:calc(100vh - 50px);
}

Só quero um jeito de ficar a scrollbar horizontal  dentro da tela
Comment: Tem como vc colocar um print?
Comment: Espere um minuto, mas acho que vai ficar meio difícil de ver.
Comment: Tudo certo agora @Sam
Comment: Vc tentou trocar 100vh por 100% para ver se resolve? e esse calc(100vh - 50px) pq fez isso??
Comment: Eu só fiz um teste, e também não deu certo, mas ficou menor. E quanto melhor a compatibilidade melhor.
Comment: Pelo que entendi, vc está se referindo àquela barra invisível padrão que só aparece quando faz scroll, não é?
Comment: Exato (infelizmente o comentário deve ser maior)
Comment: Cara não sei se te interessa essa opção, mas esse plugin de jQuery é bem legal e super customizável e crossbrowser. Ele remove a scrollbar original do browser, e faz outra com javascript, funciona muito bem! No seu carro ele vai remover todas as scrollbars e vc vai construir uma nova com esse plugin https://nicescroll.areaaperta.com/
Comment: Testando aqui no Bluestacks essa barra não aparece, só a vermelha.
Comment: Ok, se tiver como passar o codigo e a saída for a mesma
Comment: Me parece que até esse Nicescroll tem o mesmo problema, dê uma olhada na scrollbar deles
Comment: Caro Edu, no titulo vc fala uma coisa e na pergunta fala outra, afinal o que deseja? O problema é que aparece 2 scrollbars, quer que apareça apenas um? Ou é o contrário? É um problema de espaçamento? Por favor edite a sua pergunta a torna-la clara para que possamos lhe ajudar.
Comment: Quero que remova a Scrollbar padrão, e o problema tem haver com o height, pois o scroller horizontal esta abaixo da pagina que seria 100vh. como pode ver, existe uma scrollbar horizontal abaixo da pagina que devido ao scroller padrão e pelo width, ele não aparece amenos que role 2 ou 3 vezes no Android
Comment: Com calma edu, tirando a parte toda que você já explicou, responda ao que eu perguntei exatamente, se não fica dificil ajudar, você quer ou não 2 scrollbars? Independente de serem customizados ou não;
Comment: Não, quero apenas os modificados, desculpe a demora
Comment: Voce pode tirar a barra de rolagem do seu navegador , e usar o nicescroll

http://www.lucianosimas.com.br/blog/tirar-barra-de-rolagem-do-navegador/

https://nicescroll.areaaperta.com/how-to-use/

Acho que daria certo, ou tirar somente do mobile usando as media queries do css
Answer: Simulei o mesmo problema, na qual eu ficava com duas barras de scroll
A solução é :
Use o NiceScroll
e faça o scroll desejado, é bem simples de usar, e não é pesado.
Aqui vai um exemplo de código para você ter um norte :

Este código deixará seu scroll em coral e não aparecerá o scroll horizontal.
Após colocar pra funcionar o NiceScroll ele ainda estará dando o erro que você está tendo
a solução é colocar em todos os seus CSS, tanto no principal (Style) como no responsivo(Caso Tiver)
body {
overflow-x: hidden;
overflow-y: hidden; }

Assim, só será exibido o Nicescroll, não aparecendo mais o padrão


Positive root of $2ab x^3 + (a+b) x^2 - (a+b)x - 2 = 0$

Question: For $a>0$, $b>0$, consider the cubic equation
$$2ab x^3 + (a+b) x^2 - (a+b)x - 2 = 0,$$
which by Descartes' rule of sign, has exactly one positive real root $x_{+}>0$.
Can we write down $x_{+}$ as a "simple" function of parameters $a, b$? Obviously, simple is rather ill-defined, but I need something from where I can analyze the qualitative dependence of $x_{+}$ on parameters $a,b$. I tried Sage but the resulting expression was a mess.
If there are other indirect ways to infer the dependence of $x_{+}$ on $a,b$, than writing out the expression, I would be interested in learning that too.
Comment: You could depress the cubic and then use Cardano's formula.  That would give you an explicit (but somewhat ugly) expression for $x_+$.
Answer: Not extremely simple, no. Well, maybe something like this might be useful:
Let's suppose $b$ is much larger than $a$.  Then just looking at the terms with $b$ in the equation, we would have $x_+ = \frac{\sqrt{1+8a}-1}{4a}$.  And in fact we can expand $x_+$ in a series in negative powers of $b$:
$$ x_+ = \frac{\sqrt{1+8a}-1}{4a} -{\frac {2\,\sqrt {1+8\,a}a+\sqrt {1+8\,a}+10\,a-1}{-2+2 \sqrt {1+8
\,a}-16\,a}} b^{-1} + \ldots
$$
Answer: We have $a>0,\,b>0$ and
\begin{eqnarray}
P(x)&=&2ab x^3 + (a+b) x^2 - (a+b)x - 2\\
P^\prime(x)&=&6abx^2+2(a+b)x-(a+b)\\
P^{\prime\prime}(x)&=&12abx+2(a+b)
\end{eqnarray}
So we know that at the point $(0,-2)$ the graph is decreasing and concave up so the root will be greater than $\dfrac{\sqrt{(a+b)(a+b+6ab)}-(a+b)}{6ab}$ which is the $x$-coordinate of the minimum of the graph.
Given the limiting case of $b=0$ the cube term vanishes giving the parabola
\begin{equation}
y=ax^2-ax+2
\end{equation}
which has positive zero $\dfrac{a+\sqrt{a(a+8)}}{2a}$. So we have bounds on the positive root
\begin{equation}
\dfrac{\sqrt{(a+b)(a+b+6ab)}-(a+b)}{6ab}<x_+<\min\left\{\dfrac{a+\sqrt{a(a+8)}}{2a},\dfrac{b+\sqrt{b(b+8)}}{2b}\right\}
\end{equation}
Here is a corrected Desmos animation
Comment: This is great. And +1 for the animation.
Comment: @AbhishekHalder Thanks


Função que mostra lista em ordem reversa

Question: def imprimeDeTrasParaFrente(lista):
    if lista == None :
       return
    imprimeDeTrasParaFrente(lista.proximo)
    print lista,

class Node(object):

   def __init__(self, carga=None, proximo=None):
       self.carga = carga
       self.proximo = proximo

   def __str__(self):
       return str(self.carga)

   no1, no2, no3 = Node(1), Node(2), Node(3)
   no1.proximo, no2.proximo = no2, no3

   imprimeDeTrasParaFrente(no1)

Com a função imprimeDeTrasParaFrente() consegui imprimir os elementos da lista em ordem reversa, sendo que ela apenas checa se a lista esta vazia e chama ela mesma com o próximo nó da lista. Na minha perspectiva a função print nunca é chamada por que quando a lista se encontra vazia a função simplesmente retorna e termina o programa, ou estou errado?
Answer: Não há nada de errado com a lógica do seu programa, ele funciona exatamente como você descreveu: exibe os valores contidos nos nós de uma lista encadeada iterando a partir do último nó em direção ao primeiro.
O que está fazendo ele não funcionar é a indentação dos blocos, que é algo crucial em Python.
Para que tudo funcione perfeitamente, fique atento na indentação do código:

Referência Wikibooks
Comment: consegui compreender a logica agora, funcões recursivas chamam elas mesmas dentro da função, o comando return esta encerrando a funcão dentro do propio escopo da função isso quer dizer o fluxo do programa volta para o escopo da função principal então seria possivel adicionar mais um return ao final da função imprimeDeTrasParaFrente() sendo assim funções recursivas podem conter dois return mas ao final retornar apenas um.


Android Run another application while task lock

Question: I set my application as a device owner and the screen is pinning when i call startLockTask() . my problem now when i try to run another application by using this method :
Intent i = getPackageManager().getLaunchIntentForPackage("com.example.test");
startActivityForResult(i,Intent.FLAG_ACTIVITY_NEW_TASK);

(nothing happen)
what i have to do to make it run?
Edit : i tried adding
 dpm.setLockTaskPackages(deviceAdmin, new String[] { getPackageName() ,"com.example.test"});

its not launching too.
Comment: What are you trying to do? app kiosk? (limit a device to use only specific apps?)
Comment: Can you describe step by step what you're trying to do and how you're doing it?
Answer: You should check the app with an applicationId is installed on the device. for example in your case the applicationId is com.example.test.
If the app was not installed, you can bring user to a market or let them choose an app.
String packageName = "com.example.test";
.
.
.
Intent i = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (i == null) {
    i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse("market://details?id=" + packageName));
    // Open app in google play store:
    // i.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName));
}
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

Comment: Hi @Misagh, Can you able to solve related to like this issue which i'm facing

Link->  https://stackoverflow.com/questions/51190997/open-other-application-in-startlocktask-mode-using-setlocktaskpackages-string

Thank you.
Answer: A DPC must whitelist apps before they can be used in lock task mode. Call DevicePolicyManager.setLockTaskPackages() to whitelist apps for lock task mode as shown in the following sample:
// Whitelist two apps.

private static final String KIOSK_PACKAGE = "com.example.kiosk";

private static final String PLAYER_PACKAGE = "com.example.player";

private static final String[] APP_PACKAGES = {KIOSK_PACKAGE, PLAYER_PACKAGE};
// ...

Context context = getContext();

DevicePolicyManager dpm =
    (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
ComponentName adminName = getComponentName(context);
dpm.setLockTaskPackages(adminName, APP_PACKAGES);

you can declare in your app manifest file how an activity should behave when the system is running in lock task mode. To have the system automatically run your activity in lock task mode, set the android:lockTaskMode attribute to if_whitelisted
android:lockTaskMode="if_whitelisted">

taken from https://developer.android.com/work/dpc/dedicated-devices/lock-task-mode#java
Answer: Just try with startActivity when you are launching the app with FLAG_ACTIVITY_NEW_TASK.
Intent i = getPackageManager().getLaunchIntentForPackage("com.example.test");
startActivity(i);

We shouldn't use FLAG_ACTIVITY_NEW_TASK with startActivityForResult in lock task mode.


Como funciona o lock do C#?

Question: Estava dando uma olhada num artigo da MSDN, mas não ficou bem claro o porque de usar isso.
class Account
{
    decimal balance;
    private Object thisLock = new Object();

    public void Withdraw(decimal amount)
    {
        lock (thisLock)
        {
            if (amount > balance)
            {
                throw new Exception("Insufficient funds");
            }
            balance -= amount;
        }
    }
}

Answer: Lock é uma ferramenta muito útil quando você precisa garantir acesso exclusivo a um dado recurso, ou garantir Thread safety.
Essa função faz uso de um objeto como sinalizador de sincronização (no seu exemplo, o objeto thislock).
No código de exemplo, a primeira thread a executar o método Withdraw irá obter o lock do objeto thislock, e executará o bloco de código. Qualquer outra thread que tentar executar a mesma instância do método irá entrar em WaitState (ou estado de espera) caso encontrem a instrução lock e outra thread possua o direito de acesso.
Uma fila é criada, e as threads em espera irão receber a liberação do lock em estilo FIFO (First In, First Out).
Answer: Para complementar, o lock é uma espécie de semáforo. De fato, através dele é possível implantar uma estrutura de dados capaz de controlar o tráfego de processamento que é chamada de semáforo.
O lock liga uma luz vermelha dizendo para qualquer código que tente acessar aquele trecho de memória que está proibido de fazer até que a luz se apague. Note que embora pareça um semáforo, não o é de fato. Por isto o lock em si pode ser usado em um semáforo que é uma estrutura um pouco mais sofisticada.
Ele indica para toda a aplicação que naquele momento alguma coisa será feita com o objeto que não pode ser interrompida. Que nenhuma parte da aplicação pode considerar o estado do objeto enquanto ele não for liberado porque a operação naquele momento pode estar inconsistente ou incompleta.
Quando seu código for compilado o statement lock se torna um código equivalente a este:
bool lockWasTaken = false;
var temp = thisLock;
try {
    Monitor.Enter(temp, ref lockWasTaken);
    if (amount > balance) {
        throw new Exception("Insufficient funds");
    }
    balance -= amount;
} finally {
    if (lockWasTaken) {
        Monitor.Exit(temp);
    }
}

Coloquei no GitHub para referência futura.
Note que é possível obter o mesmo resultado usando apenas a biblioteca mas não é recomendado.
Em códigos que você tem certeza que nunca terá threads você não precisa e não deve usar este tipo de sincronismo. Para algumas operações o custo de performance da execução dos métodos da classe Monitor pode ser proibitivo.
Veja o Reference Source do .NET para entender o funcionamento interno da classe (não que ajude muito :D).
Comment: +1, excelente menção à estrutura de semáforos.
Answer: Vale pesquisar sobre concorrência de recursos. O semáforo por exemplo pode ser utilizado quando você tem um pool de recursos (por exemplo 3 conexões ativas) e precisa garantir que nenhum seja utilizado por mais de um consumidor.

Como funciona o lock do C#?


Test method with multiple method `Returns` possibilities

Question: I want to execute one Test method  several (3) times with different behaviour of a mocked object. So I can avoid writing multiple Test methods with mocked objects for each.
Code as example:
_mockObj.MockedMethod(Arg.Any<string>(), Arg.Any<string>()).Returns(new objA() { TestProp="bla1" };
_mockObj.MockedMethod(Arg.Any<string>(), Arg.Any<string>()).Returns(new objA() { TestProp="bla2" };
_mockObj.MockedMethod(Arg.Any<string>(), Arg.Any<string>()).Returns(new objA() { TestProp="bla3" };

What I want to do is by using one Test method to test the above 3 behaviours. Is this possible or do I have to write 3 separate Test methods?
EDIT
I've found that I have to use TestCaseSourceAttribute. But now I'm facing another 'issue'. When I have a lot of TestCases and one of them fails, then I can't trace which one of the TestCases failed...
Comment: You can write one method that's either used by 3 test methods or is called 3 times by one test method just like in regular code.
Comment: You mean I can write 3 separate Arrange, Act, Asserts in one Test method?
Comment: That's one way to look at it, but I'd thing writing the common Arrage, Act, and Assert code into the "helper" method and then call it passing in the different mocks would be my suggestion.  Wheather you call that from one Test method or 3 is up to you.   I'd still do 3 separate tests methods so that I could see the asserts/errors for each one.
Answer: A method != a test. Using parameters, one method makes many test cases. For example...
[TestCase("bla1")]
[TestCase("bla2")]
[TestCase("bla3")]
public void MyTest(string blaValue)
{
    _mockObj.MockedMethod(Arg.Any<string>(), Arg.Any<string>())
        .Returns(new objA() { TestProp=blaValue };

    // Your test code
}

Comment: Thanks but my attribute argument is actually not a compile-time constant. It's an object. I wanted to make my example as simple as possible
Answer: Some research led me to this: https://stackoverflow.com/a/10687118/1410501
[Test, TestCaseSource(nameof(MyTestCases))]
public void TestMethod(object obj)
{

}

private static readonly object[] MyTestCases =
{
    new object { TestProp="bla1" },
    new object { TestProp="bla2" },
    new object { TestProp="bla3" },
};


multiple markers fall into one region(polygon), I want to list data for all markers in a particular region in a div panel

Question: hope this makes sense.  I have merged together two tables one containing information about telephone exchanges and their specific location in the uk and another containing region info for the uk.  What I want to do is when I roll over or click on a region I want to be able to list all the exchanges that fall into that area on a panel on my web page. At the moment when I click on a region the last exchange in the table is displayed. I'm guessing this could be something simple that I need to do within my addListeners2() function.  Any pointers in the right direction would be greatly appreciated.
var map, layer;
function initialize()
{

    map = new google.maps.Map(document.getElementById('map_canvas'), {
            center: new google.maps.LatLng(54.54658,-4.87793),
            zoom: 6,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          });
          loadPoint();
    }

        function loadPoint()
        {
           if (layer != null)
           {
                layer.setMap(null);
                google.maps.event.clearInstanceListeners(layer);
           }
           var tableid = '3569550';
           layer = new google.maps.FusionTablesLayer
           ({
                query:
                {
                    select: 'LATITUDE',
                    from: tableid
                    //where: 'latitude is not null'
                },

            map: map
           })
            layer.enableMapTips({
            select: "'REGION','EXCHANGE','MPF','WLR','SMPF','BB_CONNECT'", // list of columns to query, typially need only one column.
            from: tableid, // fusion table name
            geometryColumn: 'LATITUDE', // geometry column name
            suppressMapTips: true, // optional, whether to show map tips. default false
            delay: 100, // milliseconds mouse pause before send a server query. default 300.
            tolerance: 8 // tolerance in pixel around mouse. default is 6.
            });
            addListeners1();
        }

        function loadRegion()
        {
           if (layer != null)
           {
                layer.setMap(null);
                google.maps.event.clearInstanceListeners(layer);
           }
           var tableid = '3569550';
           layer = new google.maps.FusionTablesLayer
           ({
                query:
                {
                    select: 'geometry',
                    from: tableid
                },

            map: map
           })
            layer.enableMapTips({
            select: "'REGION','EXCHANGE','MPF','WLR','SMPF','BB_CONNECT'",
            from: tableid, // fusion table name
            geometryColumn: 'geometry', // geometry column name
            suppressMapTips: true, // optional, whether to show map tips. default false
            delay: 100, // milliseconds mouse pause before send a server query. default 300.
            tolerance: 8 // tolerance in pixel around mouse. default is 6.
            });
            addListeners2();
        }

        function addListeners1()
        {
            google.maps.event.addListener(layer, 'mouseover', function(fEvent)
            {
                var row = fEvent.row;
                myHtml = '

';
                myHtml += 'REGION	';
                myHtml += 'EXCHANGE	';
                myHtml += 'MPF	';
                myHtml += 'WLR	';
                myHtml += 'SMPF	';
                myHtml += 'BB_CONNECT

';
                for (var x in row)
                {
                    if (row.hasOwnProperty(x))
                    {
                        myHtml += '' + row[x].value +'	';
                    }
                }
                myHtml += '

';
                document.getElementById('info').innerHTML = myHtml;
            });
        }

        function addListeners2()
        {
            google.maps.event.addListener(layer, 'mouseover', function(fEvent)
            {
                var row = fEvent.row;
                myHtml = '

';
                myHtml += 'REGION	';
                myHtml += 'EXCHANGE	';
                myHtml += 'MPF	';
                myHtml += 'WLR	';
                myHtml += 'SMPF	';
                myHtml += 'BB_CONNECT

';
                for (var x in row)
                {
                    if (row.hasOwnProperty(x))
                    {
                        myHtml += '' + row[x].value +'	';
                    }
                }
                myHtml += '

';
                document.getElementById('info').innerHTML = myHtml;
            });
        }
}

Answer: I'm not familiar with the Fusion Tips utility library but the documentation shows it does not support a where clause.  Which kind of makes sense. A tool tip would be associated with a single point or polygon.  You need a where clause, i.e. select exchanges where region = XXX.
I'd try the google.visualization library which would allow you to execute such a query or you could use the Fusion Table JSONP API which would allow the same. There's a visualization example here, quite a bit different, but could be modified to handler what you want to do.
Comment: Thanks for your response Eric, I'll check out that  google.visualization library and see if I can get this thing working.
Answer: I have found the solution!!!
function loadRegion()
{
    if (layer != null)
    {
        layer.setMap(null);
        google.maps.event.clearInstanceListeners(layer);
    }
    layer = new google.maps.FusionTablesLayer
    ({
        query:
        {
            select: 'geometry',
            from: tableid
        },
        map: map
    })
    google.maps.event.addListener(layer, 'click', function(e)
    {
        if (e && e.row && e.row["REGION"])
        {
            query4infowindowData(e.row["REGION"].value);
            infowindow.setPosition(e.latLng);
        }
        else
        {
            alert("no row:"+e.latLng);
        }
    });
}
function query4infowindowData(term)
{
    var queryText = "SELECT 'REGION', 'EXCHANGE', 'MPF', 'WLR', 'BB_CONNECT', 'SMPF' FROM "+tableid+" WHERE 'REGION' = '"+term+"';";
    var encodedQuery = encodeURIComponent(queryText);
    var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq='  + encodedQuery);
    query.send(openInfoWindow);
}
function openInfoWindow(response)
{
    if (!response)
    {
        alert('no response');
        return;
    }
    if (response.isError())
    {
        alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
    }
    FTresponse = response;
    numRows = response.getDataTable().getNumberOfRows();
    numCols = response.getDataTable().getNumberOfColumns();
    var dataTable = response.getDataTable();
    var contents = "REGION: "+dataTable.getValue(0,0)+"

#	EXCHANGE	MPF	WLR	BB_CONNECT	SMPF
";
    for(i = 0; i < numRows; i++)
    {
        contents += "
"+i+"	"+dataTable.getValue(i,1)
            +"	"+dataTable.getValue(i,2)
            +"	"+dataTable.getValue(i,3)
            +"	"+dataTable.getValue(i,4)
            +"	"+dataTable.getValue(i,5)
            +"
";
    }
    contents += "
";
    document.getElementById('info').innerHTML = contents;

}