text:
Q: Wrong resolution for Lightdm/GDM on Ubuntu 13.04 using HDMI I've tried all the solution I could find on the matter so far, but the error persists. My problem is that the login screen (both under gdm and lightdm) runs with the wrong resolution, even though all is fine when I log in. The error occurs solely when I have my HDMI cable connected to my other screen. The login screen resolution becomes 1024x768 (for my 1366x768 laptop screen) and mirrored on my screen, which is 1920x1080.
I've had this issue on version 12.04 (the last one before I upgraded to 13.04), but I got it fixed by adding the xrandr commands on the begining of the /etc/gdm/Init/Default file. This doesn't seem to work anymore.
I've also tried telling lightdm to run a script fixing the resolution with xrandr (by editing /etc/lightdm/lightdm.conf), but lightdm crashes, and I'm forced to log in with low graphic settigs.
Hint: when ubuntu is loading, the resolution starts OK, then goes bad right before the login screen is initialized. Does that mean that there's nothing wrong with my graphic cards?
What do you think? Cheers!

A: I faced the same problem running Ubuntu Gnome 13.04. My laptop uses a ATI Radeon graphics card. The laptop display runs at 1980x1080 resolution and I have a Dell 1980x1200 screen connected through the HDMI port. This morning, I installed the fglrx proprietary display driver and it solved the issue. I get the full resolution login screen now and the laptop has been running 15o cooler since! You may want to try this, and see if it works for you.


text:
Q: In the Halo universe, what is Fletcher's Syndrome? In the animated film Halo: The Fall of Reach, "Fletcher's Syndrome" is mentioned as a potential side-effect of the augmentation process.
Is there any source or material that says what this syndrome is, and what the effects of having it are? It doesn't sound pleasant.

A: If you look through all the lore and the equivalence to real life, Fletcher Syndrome is a systemic failure of vitals in a long lasting and painful manner.
Symptoms: Cranial Hemorrhaging, Cardiac Hemorrhaging, Spasms in disconnected tissue, Complete Muscle Collapse, Sensory Deprivation, Digestive Tract Bloating, Malnutrition, and the lowering of the immune system.
There is no cure and presumably wouldn't have any due to the lack of ability to address so many situations at once.
Multiple organ dysfunction syndrome (MODS) is the less extreme, yet real life version of Fletcher Syndrome. Though it doesn't contain all of the symptoms, it does contain the most crucial symptoms of Total Organ Failure.

A: The other answers are in-universe correct, but it's worth noting that the name might be a nod-and-wink writer's joke from author Eric Nylund regarding the character of Jessica Fletcher in the TV series Murder, She Wrote. It's an old joke about a fictional disease that results in people you meet continuously getting murdered under mysterious circumstances...

Fletcher's Syndrome is a dangerous and potentially fatal disorder that affects main characters who are detectives or otherwise investigators of crime.  Symptoms of Fletcher's Syndrome include, but are not limited to, someone being murdered while at a friend's dinner party, someone being murdered while on that weekend getaway that has been in planning for months, someone being murdered while at a class reunion or extracurricular club reunion, a long-estranged (or at least hasn't been seen an a few years) relative being murdered and the affected being the main suspect, a celebrity who the affected either idolizes or is seeing live being murdered or suspected of murder, and pretty much any leisure or professional situation the affected may find him- or herself in resulting in or involving murder.
The Theater's Reader: Cliché Play: Fletcher's Syndrome

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to static_assert that a lambda is not generic? I implemented a Visit function (on a variant) that checks that the currently active type in the variant matches the function signature (more precisely the first argument). Based on this nice answer.
For example
#include <variant>
#include <string>
#include <iostream>

template<typename Ret, typename Arg, typename... Rest>
Arg first_argument_helper(Ret(*) (Arg, Rest...));

template<typename Ret, typename F, typename Arg, typename... Rest>
Arg first_argument_helper(Ret(F::*) (Arg, Rest...));

template<typename Ret, typename F, typename Arg, typename... Rest>
Arg first_argument_helper(Ret(F::*) (Arg, Rest...) const);

template <typename F>
decltype(first_argument_helper(&F::operator())) first_argument_helper(F);

template <typename T>
using first_argument = decltype(first_argument_helper(std::declval<T>()));

std::variant<int, std::string> data="abc";
template <typename V>
void Visit(V v){
using Arg1 = typename std::remove_const_t<std::remove_reference_t<first_argument<V>>>;//... TMP magic to get 1st argument of visitor + remove cvr, see Q 43526647
if (! std::holds_alternative<Arg1>(data)) {
std::cerr<< "alternative mismatch\n";
return;
}
v(std::get<Arg1>(data));
}
int main(){
    Visit([](const int& i){std::cout << i << "\n"; });
    Visit([](const std::string& s){std::cout << s << "\n"; });
    // Visit([](auto& x){}); ugly kabooom
}

This works, but it explodes with a user unfriendly compile time error when users passes a generic (e.g. [](auto&){}) lambda. Is there a way to detect this and give nice static_assert() about it?
Would also be nice if it worked with function templates as well, not just with lambdas.
Note that I do not know what possible lambdas do, so I can not do some clever stuff with Dummy types since lambdas may invoke arbitrary functions on types.
In other words I can not try to call lambda in 2 std::void_t tests on int and std::string and if it works assume it is generic because they might try to call .BlaLol() on int and string.

A: Yet another simpler option:
#include <type_traits>
...
template <typename V>
void Visit(V v) {
   class Auto {};
   static_assert(!std::is_invocable<V, Auto&>::value);
   static_assert(!std::is_invocable<V, Auto*>::value);
   ...
}

The Auto class is just an invented type impossible to occur in the V parameters. If V accepts Auto as an argument it must be a generic.
I tested in coliru and I can confirm the solution covers these cases:
Visit([](auto x){}); // nice static assert
Visit([](auto *x){}); // nice static assert
Visit([](auto &x){}); // nice static assert
Visit([](auto &&x){}); // nice static assert

I'm not sure if that would cover all the possible lambdas that you don't know which are :)

A: #include <variant>
#include <string>
#include <iostream>

template <class U, typename T = void>
struct can_be_checked : public std::false_type {};

template <typename U>
struct can_be_checked<U, std::enable_if_t< std::is_function<U>::value > >  :  public std::true_type{};

template <typename U>
struct can_be_checked<U, std::void_t<decltype(&U::operator())>> :  public std::true_type{};

template<typename Ret, typename Arg, typename... Rest>
Arg first_argument_helper(Ret(*) (Arg, Rest...));

template<typename Ret, typename F, typename Arg, typename... Rest>
Arg first_argument_helper(Ret(F::*) (Arg, Rest...));

template<typename Ret, typename F, typename Arg, typename... Rest>
Arg first_argument_helper(Ret(F::*) (Arg, Rest...) const);

template <typename F>
decltype(first_argument_helper(&F::operator())) first_argument_helper(F);

template <typename T>
using first_argument = decltype(first_argument_helper(std::declval<T>()));

std::variant<int, std::string> data="abc";

template <typename V>
void Visit(V v){
    if constexpr ( can_be_checked<std::remove_pointer_t<decltype(v)>>::value )
    {
        using Arg1 = typename std::remove_const_t<std::remove_reference_t<first_argument<V>>>;//... TMP magic to get 1st argument of visitor + remove cvr, see Q 43526647
        if (! std::holds_alternative<Arg1>(data))
        {
            std::cerr<< "alternative mismatch\n";
            return;
        }
        v(std::get<Arg1>(data));
    }
    else
    {
        std::cout << "it's a template / auto lambda " << std::endl;
    }

}

template <class T>
void foo(const T& t)
{
    std::cout <<t << " foo \n";
}

void fooi(const int& t)
{
    std::cout <<t << " fooi " << std::endl;
}

int main(){
    Visit([](const int& i){std::cout << i << std::endl; });
    Visit([](const std::string& s){std::cout << s << std::endl; });
    Visit([](auto& x){std::cout <<x << std::endl;}); // it's a template / auto lambda*/
    Visit(foo<int>);

    Visit<decltype(fooi)>(fooi);
    Visit(fooi);

    // Visit(foo); // => fail ugly
}

I don't know if it's you want, but you can, with that static_assert if an auto lambda is passed as parameter.
I think it's not possible to do the same for template function, but not sure.

A:
Is there a way to detect this and give nice static_assert about it?

I suppose you can use SFINAE over operator() type.
Follows an example
#include <type_traits>

template <typename T>
constexpr auto foo (T const &)
   -> decltype( &T::operator(), bool{} )
 { return true; }

constexpr bool foo (...)
 { return false; }

int main()
 {
   auto l1 = [](int){ return 0; };
   auto l2 = [](auto){ return 0; };

   static_assert( foo(l1), "!" );
   static_assert( ! foo(l2), "!" );
 }

Instead of a bool, you can return std::true_type (from foo() first version) or std::false_type (from second version) if you want to use it through decltype().

Would also be nice if it worked with function templates as well, not just with lambdas.

I don't think it's possible in a so simple way: a lambda (also a generic lambda) is an object; a template function isn't an object but a set of objects. You can pass an object to a function, not a set of objects.
But the preceding solution should works also for classes/structs with operator()s: when there is a single, non template, operator(), you should get 1 from foo(); otherwise (no operator(), more than one operator(), template operator()), foo() should return 0.


text: Q: How to Generate code with lambda notation using spring-roo Currently I can not generate Lambda notation using spring-roo. It seems the antlr-javaparser that spring-roo use don't support lambda notations. Now how can i upgrade or replace the project from spring-roo. It seems if I change the project version it stop working.


text:
Q: Using Unicode character assertion 0x22a6 I am trying to typeset a document using Xelatex. The document contains assertion unicode character 0x22a6 but unable to render it.
I have tried several methods such as using newunicodechar package, fontspec, etc. but could'nt render the character successfully.

A: If your font has no U+22A6 glyph, you can add a font face having it:
\documentclass{article}
\usepackage{fontspec}
\usepackage{newunicodechar}

\setmainfont{Old Standard} % it has no U+22A6
\newfontface{\assertionfont}{FreeSerif} % it has U+22A6

\newunicodechar{⊦}{\mbox{\assertionfont ⊦}}

\begin{document}

This is \texttt{U+22A6}: ⊦

\end{document}

Among the fonts in TeX Live having the glyph you find Asana Math, Latin Modern Math, Libertinus Serif and Sans, Linux Libertine, Linux Biolinum, STIX and STIX Math, TeX Gyre {Bonum|Pagella|Schola|Termes} Math, XITS and XITS Math.
Note that you can use, say, Asana Math in a \newfontface declaration.

A: This should be available in any math font (and some text fonts) for example it is in latin modern math:

\documentclass{article}
\usepackage{unicode-math}
\setmathfont{latinmodern-math.otf}
\begin{document}

You can (perhaps) use the math font as text font for example

\documentclass{article}
\usepackage{unicode-math}
\setmathfont{xits-math.otf}
\setmainfont{xits-math.otf}
\begin{document}

[text ^^^^22a6]

$ a \assert b $

\end{document}

The same markup would work for any font tha has the character.
$ a \assert b $

\end{document}

If you don't need it to be in Unicode position the actual character is available in any tex math font set (as \vdash)


text:
Q: Xcode 5 : AdHoc iTunesAdwork I've an AdHoc distribution for my iOS application.
However, I find it very ugly that the application has no icon in iTunes.
I've added the iTunesArtwork without extension to the root of the project, but it won't appear in iTunes.
What can I do now?
I'm running the latest version of XCode.
I've searched online, it says to put the file in the resources folder - but my application does not contain any folder named resources.


text:
Q: Heroku deploy deletes server files automatically? I'm new to HEROKU APPS.
In my heroku app i have a problem. that is I'm using a php script to save data on server.
Example :
<?PHP

$file = "example.txt";

$data = "Something...";

file_put_contents($file,$data);

?>

This PHP script run successfully and save data perfectly.
But, when I deploy my APP to HEROKU to update -> in this precess example.txt file is automatically deleted.

A: Heroku does not supply hard disk space to persistent files between git pushes, you'll have to use something like Amazon S3 for file storage. That is why Heroku calls their filesystem Ephemeral filesystem. It was even read-only in earlier versions of the stack.
Heroku has a tutorial on it: Using AWS S3 to Store Static Assets and File Uploads

A: Heroku File Systems
Heroku behavior varies depending a little on the stack you use. With Bamboo, most of the file system is read-only. With Cedar, it is ephemeral.
In either case, the file systems are not shared between dynos, and should not be used for storage. To reliably store data server-side, you will need to use the database (perhaps storing your uploads as blobs), or as external assets on another host or service.

A: Please see the docs:

Ephemeral filesystem
Each dyno gets its own ephemeral filesystem, with a fresh copy of the most recently deployed code. During the dyno's lifetime its running processes can use the filesystem as a temporary scratchpad, but no files that are written are visible to processes in any other dyno and any files written will be discarded the moment the dyno is stopped or restarted.

So you can not save much with your Heroku dyno. Especially after you've pushed your new version, the dyno is restarted and the file-system is reset then.
You need to store files into a remote location then if they should survive the dyno reset.


text:
Q: Изменятся ли данные если остановить update запрос? Написал Update запрос он получился на две строки, по тупости выделил
только часть запроса до Where. Когда увидел что запрос выполняется долго
обратил внимание что не выделил весь запрос, и нажал кнопку остановки запроса.
Результата с кол-вом строк я не получил.
Изменились ли данные ? Там очень много строк поэтому я не смог
проверить это сам.


text:
Q: bash script doesn't run properly in crontab but runs fine manually I wrote a small script to determine the average IOPs per hour in which I later manually convert to a graph and spreadsheet for management to discuss a potential SAN upgrade for an upcoming expansion project. The system running is currently a physical machine running RHEL 6.
I have the script scheduled in root's crontab like below:
0 * * * * /bin/bash /IOPsLogs/IOPs.sh  >> /var/log/cronjobIOPs.log 2>&1

My script IOPs.sh looks like:
#!/bin/bash
date >> /var/log/cronjobIOPs.log
date +"%Y-%m-%d--%H:00" >> /IOPsLogs/Daily$(date +%Y-%m-%d).log
timeout -sHUP 60m iostat -x 1 | grep sda -B 1 >> /IOPsLogs/IOPs_$(date +%Y-%m-%d--%H:00).log
grep "sda" /IOPsLogs/IOPs_$(date +%Y-%m-%d--%H:00 -d "1 hour ago").log | awk '{sum+=$4} END { print "Average IOPs read'/'sec= ",sum/NR}' >> /IOPsLogs/Daily$(date +%Y-%m-%d).log
grep "sda" /IOPsLogs/IOPs_$(date +%Y-%m-%d--%H:00 -d "1 hour ago").log | awk '{sum+=$5} END { print "Average IOPs write'/'sec= ",sum/NR}' >> /IOPsLogs/Daily$(date +%Y-%m-%d).log

the log file "/var/log/cronjobIOPs.log" looks like: (Which is good since I don't see any errors.)
Mon Apr 27 00:00:01 MST 2015
Mon Apr 27 01:00:01 MST 2015
Mon Apr 27 02:00:01 MST 2015
Mon Apr 27 03:00:01 MST 2015
Mon Apr 27 04:00:01 MST 2015
Mon Apr 27 05:00:01 MST 2015
Mon Apr 27 06:00:01 MST 2015
Mon Apr 27 07:00:01 MST 2015
Mon Apr 27 08:00:01 MST 2015
Mon Apr 27 09:00:01 MST 2015
Mon Apr 27 10:00:01 MST 2015
Mon Apr 27 11:00:01 MST 2015
Mon Apr 27 12:00:01 MST 2015
Mon Apr 27 13:00:01 MST 2015
Mon Apr 27 14:00:01 MST 2015
Mon Apr 27 15:00:01 MST 2015
Mon Apr 27 16:00:01 MST 2015
Mon Apr 27 17:00:01 MST 2015
Mon Apr 27 18:00:01 MST 2015
Mon Apr 27 19:00:01 MST 2015
Mon Apr 27 20:00:01 MST 2015
Mon Apr 27 21:00:01 MST 2015
Mon Apr 27 22:00:01 MST 2015
Mon Apr 27 23:00:01 MST 2015
Tue Apr 28 00:00:01 MST 2015
Tue Apr 28 01:00:01 MST 2015
Tue Apr 28 02:00:01 MST 2015
Tue Apr 28 03:00:01 MST 2015
Tue Apr 28 04:00:01 MST 2015
Tue Apr 28 05:00:01 MST 2015
Tue Apr 28 06:00:01 MST 2015
Tue Apr 28 07:00:01 MST 2015
Tue Apr 28 08:00:01 MST 2015
Tue Apr 28 09:00:01 MST 2015

Now my problem is that the daily logs are inconsistent with it providing one read and write average per hour. Sometimes it provides more than two answers to a time stamp or two time stamps. Something seems to be off with the timing somehow? (Not a VM and not seeing any time slippage over the years.) If I run it manually every hour then it works just fine. Does anyone have any ideas or a different approach?
Average IOPs read/sec=  0.0442611
Average IOPs write/sec=  13.4663
2015-04-27--00:00
Average IOPs read/sec=  79.1727
Average IOPs write/sec=  22.7509
2015-04-27--01:00
2015-04-27--02:00
Average IOPs read/sec=  0.0370389
Average IOPs write/sec=  13.1389
Average IOPs read/sec=  36.6858
2015-04-27--03:00
Average IOPs write/sec=  250.514
Average IOPs read/sec=  32.6261
2015-04-27--04:00
Average IOPs write/sec=  391.811
Average IOPs read/sec=  1.64334
Average IOPs write/sec=  84.6204
2015-04-27--05:00
2015-04-27--06:00
Average IOPs read/sec=  0.0487056
Average IOPs write/sec=  12.8323
Average IOPs read/sec=  0.0617611
Average IOPs write/sec=  14.0306
2015-04-27--07:00
2015-04-27--08:00
Average IOPs read/sec=  0.11815
Average IOPs write/sec=  14.094
Average IOPs read/sec=  0.0817611
Average IOPs write/sec=  14.9651
2015-04-27--09:00
Average IOPs read/sec=  0.0434278
Average IOPs write/sec=  13.6037
2015-04-27--10:00
Average IOPs read/sec=  0.613706
Average IOPs write/sec=  14.9003
2015-04-27--11:00
Average IOPs read/sec=  0.0389833
Average IOPs write/sec=  13.9256
2015-04-27--12:00
2015-04-27--13:00
Average IOPs read/sec=  0.0642528
Average IOPs write/sec=  15.1321
Average IOPs read/sec=  0.144817
Average IOPs write/sec=  13.8244
2015-04-27--14:00
Average IOPs read/sec=  0.0384222
2015-04-27--15:00
Average IOPs write/sec=  13.0468
Average IOPs read/sec=  0.0312028
Average IOPs write/sec=  12.7255
2015-04-27--16:00
Average IOPs read/sec=  0.0781472
Average IOPs write/sec=  13.7179
2015-04-27--17:00
Average IOPs read/sec=  0.0798139
Average IOPs write/sec=  15.9144
2015-04-27--18:00
Average IOPs read/sec=  0.138147
Average IOPs write/sec=  13.7297
2015-04-27--19:00
Average IOPs read/sec=  0.0362028
Average IOPs write/sec=  13.2324
2015-04-27--20:00
Average IOPs read/sec=  0.254536
Average IOPs write/sec=  14.9013
2015-04-27--21:00
Average IOPs read/sec=  0.0314806
Average IOPs write/sec=  12.8527
2015-04-27--22:00
2015-04-27--23:00
Average IOPs read/sec=  21.6865
Average IOPs write/sec=  70.7389

A: It is an overlap between one execution of the script and the one made an hour later.
Sometimes the new execution writes its first line before the first execution has written its last two lines.
The first two lines are from the last execution made on 2015-04-26.
When they are written the date is the 2015-04-27 since the log file used is based on the time at the write time, not start of execution.
An option is to store date & time in variables and write all three lines at the same time in the correct date file.


text:
Q: What is the relationship between cURL, WordPress and cacert.pem? I've run into a problem concerning wp_remote_get() and the underlying cURL call. On some WordPress installations I see the following SSL error:
httprequest_failed: SSL certificate problem, verify that the CA cert is OK. Details:      error:14090086:SSL routines:SSL3_GETSERVER_CERTIFICATE:certificate verify failed
From my research it looks as if the following should resolve my problem:
    curl_setopt ($handle , CURLOPT_CAINFO, dirname(FILE)."/cacert.pem");
I'm uncertain what I need to configure on my server so that this error doesn't occur. I found the above line of code set in a different plugin but I'm unsure of the reason why.
Thoughts?
Shepherd

A: HTTPS isn't all about encryption alone. SSL also uses a process known as certificate verification to prevent host forgery. This is a multi-layered process, but here's the quick overview:
There exist in the world a number of Certificate Authorities (CAs). When you get a certificate for your domain name to allow it to do SSL, generally you buy it from one of these CAs. They digitally "sign" the certificate, verifying that they've checked it or what have you.
Every web browser comes with a list of CAs (and their cryptographic signature) that that browser trusts. Thus, when you go to an HTTPS URL, the server presents its signed certificate. Your browser performs an operation to verify the signature against the CAs it knows about. If it knows it, and the domains match, then it assumes the domain is valid and it trusts that site. Generally this means it displays the trusted icon or something. If it doesn't match, then it usually presents the viewer with a box saying that it can't verify the certificate and that the user should proceed with caution.
Now, curl is a web browser too. It also verifies certificates in the exact same way. However, curl is a program installed on your web server, and it's probably not up-to-date on all the latest and greatest CAs and revocation lists and such. So when it checks the signature, the check fails because it doesn't know the relevant CAs.
The fix for this that you're thinking about involves getting the newest cacert.pem file (the CA certificates list) and then telling the curl library where that file is and to use it. This would work fine, if you have the cacert.pem file and you put your code into the wp-config.php file. Every once in a while you may have to update the cacert.pem file to the latest version.
The other alternative is to tell curl to ignore the verification phase and to just use SSL for encryption. This works well, but means that you'd potentially be vulnerable to a specialized kind of attack, but what they could do depends on what you're using the remote get for. To do this, you can add the sslverify argument to the wp_remote_get call, like so:
wp_remote_get('https://whatever',array('sslverify'=>false));
Edit to avoid a new "answer", as my reputation is null and I cannot comment - MeanderingCode:
In answer to MikeSchinkel's comment/question: The absence of verifying that the signature on the certificate is from a "trusted" Certificate Authority means that anyone could have created the certificate in order to initiate the encrypted HTTP session, and potentially there is a Man-In-The-Middle, decrypting your traffic, reading or altering it, re-encrypting it, and sending it along in their own session with your intended destination.  Potentially, sensitive information is traveling over the connection; most commonly, authentication credentials.  A MITM would see in plaintext any information sent over the link, and then have your credentials and any other information that was sent either direction.


text:
Q: Unable to understand behaviour of Finally Block I am new to Java language and cannot understand the behavior of finally block in this program. This program should exit after printing BC whereas it is printing BCD. Please help.
class Main
{
    public static void main(String [] args)
    {
        try
        {
            badMethod();
            System.out.print("A");
        }
        catch (Exception ex)
        {
            System.out.print("B");
        }
        finally
        {
            System.out.print("C");
        }
        System.out.print("D");
    }
    public static void badMethod() throws Exception
    {
        throw new Exception(); /* Line 22 */
    }
}

A: You're catching the exception (in the catch block) and not rethrowing it - so you're effectively handling the exception, and execution then proceeds as if it weren't thrown. The program only exits because it reaches the end of the main method - it's not like it's terminated abruptly.
If you change your code to either rethrow the exception from the catch block or just don't catch it in the first place (both of which will require you to declare that main throws Exception, of course) then it won't print D.

A: There is nothing to cause the program to exit.
The whole point of a catch block is to catch the exception and prevent it from propagating further.
After catching an exception, execution continues.

A: The finally block doesn't finalize the program, it just ensure to execute every time the try catch block runs whereas there is an exception or not..

A: It would print BC if you re-throw the exception in catch block.
catch (Exception ex)
{
    System.out.print("B");
    throw ex;
}

Then you'll have to declare your main as
public static void main(String [] args) throws Exception

A: Finally is called at the end of a try/catch block. It gets called even if the try fails and the catch is executed. The Finallyblock itself is only not executed if the program is killed somehow (JVM dies, forced to close, etc.)
In your example D is executing because it is outside of the try/catch/finally{} blocks.
There is a nice blog post on catching exceptions and the try/catch/finally behaviour here.

A: Which is correct. The above code will.

*

*Try to execute badMethod and will fail

*Execute the code in catch

*Execute the code in finally

*Continue in execution - print out the D

A: The finally block is processed after the try or catch block runs (depending on whether an exception was thrown/caught or not). If the exceptions were all caught properly and handles by the catch, it will run finally and then continue running the rest of the method.

A: Your program is functioning in the following way:
1. Call a bad method that throws an exception
2. Catch the exception
3. Execute the finally block
4. Resume
In Java, when an exception gets thrown it does not necessarily end program execution if the exception is handled. Your program does not actually handle the exception but catches it anyway and this is enough for the JVM to think it's ok to resume execution.
The output BCD is quite the right output.

A: Finally is the must executable block of java program.
It allows all the allocated resources of the currently running program to get free and make it available for the other applications if required.
This is mainly used when we share the common resources like Database or the devices.

A: Think of the finally block as an independent block of code(s) you'll still expect your method to continue executing irrespective of whether an exception occurs or not.
And so in your case, badMethod throws an exception which is consequently caught by the catch block, your main then continue by executing the finally block independently.
In other words, if badMethod decides not to throw an exception, your finally block would still continue execute before reaching the end of the method.
Therefore with finally been an independent block it is then possible to also do something like this in your main code if prefered.
try
{
 fooA();
}
finally
{
 fooB();
}


text:
Q: Constantly append element to list in json file Sorry if this is a very simple answer but I cannot find an answer to this question.
I have a very simple JSON file with a currently empty list.
{
    "times": [

    ]
}

In a while loop, i'd like to constantly append items to this list so that after the program is ended this file should look something like this.
{
    "times": [
        1.64,
        2.24,
        3.13,
        4.19
    ]
}

So in order to do this I tried out the following code and a couple other variations.
import json

while True:
    with open("data.json", "r") as jsonFile:
        data = json.load(jsonFile)
    datat.append("EXAMPLE")
    with open("data.json", "a") as jsonFile:
        json.dump(data, jsonFile)

Just looking at this, it looks very wrong.
My json file now looks like.
{
    "times": [

    ]
}["EXAMPLE"]

and I get the error

Traceback (most recent call last):   File
"/Users/aspera/Documents/Eluv/live_stream_check/test.py", line 5, in

data = json.load(jsonFile)   File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/init.py",
line 293, in load
return loads(fp.read(),   File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/init.py",
line 346, in loads
return _default_decoder.decode(s)   File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/decoder.py",
line 340, in decode
raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 5 column 2 (char 25)

How can I append elements to a list in the json file (in a loop)?


text:
Q: Python: Импорт через __init__.py в IDE работает, а в командной строке - нет У меня есть бот, который основан на уже готовом проекте, и вот пришло время писать и своего. Решил сделать такой же импорт плагинов:
# содержимое /plugins/__init__.py
import importlib
import pkgutil

__all__ = []

def import_plugins(package):
    if isinstance(package, str):
    package = importlib.import_module(package)

    for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
        full_name = package.__name__ + '.' + name

        module = importlib.import_module(full_name)

        for name in dir(module):
            if name[0] == "_":
                continue

            e = module.__getattribute__(name)

            if e in __all__:
                continue

            if True:
                __all__.append(e.__name__)
                globals()[e.__name__] = e

        if is_pkg:
            import_plugins(full_name)

import_plugins(__name__)

Так вот, с запуском из PyCharm проблем нет, но если запустить из командной строки, то выдаст ошибку:

Traceback (most recent call last):
    File "Camelia.py", line 12, in
      settings = Settings.Settings()
    File "C:\Users\ShadowOfLife\PycharmProjects\AeterrnoPy\Settings.py", line 10, in __init__
      self.inner_data = InnerDataPlugin()
  NameError: name 'InnerDataPlugin' is not defined

Что я делаю не так? Есть ли возможность заставить такой импорт работать с командной строки?
Структура проекта:

/Plugins
  -- /AeterrnoPy
  -- /Base
  -- /Data
  -------- __init__.py
  -------- InnerData.py  # тут находится InnerDataPlugin()
  -- /EzPy
  -- __init__.py # тут код для импорта
  /utils
  Camelia.py # бот
  Settings.py # сюда импортируются плагины

И содержимое Settings:
from Plugins import *

class Settings:
__slots__ = ("inner_data", "plugins", "user_plugins")

def __init__(self):
    self.plugins = ()
    self.user_plugins = ()
    self.inner_data = InnerDataPlugin()

    self.plugins = (
        AntiFloodPlugin(),
        self.inner_data,
        PairPlugin("pair test", "pt"),
        TestingPlugin("test", "tst"),
    )

    self.user_plugins = (
        PairUP("pair test", "pt"),
    )

UPD: Извиняюсь за использование изображений, исправил

A: Проблема в том, что Pycharm автоматически добавляет все директории с модулями проекта в PYTHONPATH.
Когда вы запускаете скрипт с консоли - он не видит директорий по которым раскиданы ваши модули (на это есть множество причин).
И выхода здесь есть два:

*

*Правильный - просто используйте относительный импорт, например:
from ..Plugins import *
import .Plugins
(поексперементируйте с путями, чтобы самому понять как это всё работает)

*Не очень правильный
Создайте в главной директории проекта init.py
Импортируйте в него все свои внутренние модули
Добавьте корневую директорию проекта в переменную PYTHONPATH вашей ОС, или же непосредственно в самом верху главного файла пропишите:
import sys
sys.path.append('/path/to_my_project')

A: В общем, ответ Alex мне не помог, ничего не изменилось. Проблему уже решил, но почему и как - объяснить не смогу. Импортировал в __init__.py базовый плагин, от которого наследуются остальные, и вместо того, чтоб добавлять в __all__ всё подряд, добавляю только подклассы BasePlugin. Теперь работает и с консоли, и с PyCharm, и с другого устройства тоже.
То есть, вместо:
if True:
    __all__.append(e.__name__)
    globals()[e.__name__] = e

Теперь:
if isinstance(e, type) and issubclass(e, BasePlugin) and e.__module__ == module.__name__:
    __all__.append(e.__name__)
    globals()[e.__name__] = e

Нужные плагины в переменной были в обоих случаях, но почему-то при наличии там чего-то лишнего импорт не срабатывал в командной строке.


text:
Q: Connecting phonegap with Facebook Please, any help/solutions for this:  connecting and merging Facebook with our phonegap application (version 3.0.9) so we may post on Facebook - from the phonegap applicaton's behalf using the post dialog.
Basically, when an action is done on the application, it would post to Facebook (such as when someone is listening to a song on Spotify and it says on FB, or when someone likes something on Instagram and it posts on FB, etc).
We are using phonegap version 3.0.9.

A: The Facebook plugin would be your best, and easiest, bet. Take a look at the documentation found here.


text:
Q: Copy/paste from vbox to windows I am using Windows 10 and VBox v5.1.6r110634 (Qt5.5.1). Ubuntu 16.04.1 LTS and GNOME Terminal 3.18.3.
I am trying to copy from a Ubuntu system to my Windows 10 Visual Studio v14.0.25431.01 Update 3. I have set Ubuntu's settings to be bidirectional just as described on a web page (Settings->General->Advanced->Shared Clipboard and Drag'n'Drop to Bidirectional). But the copy/paste from a terminal to Windows does not work. I have verified that the Copy operation in Ubuntu works because I can then Past to Ubuntu. But when I try to Paste to Visual Studio it does not work. I have tried a complete shutdown of Vbox and restarted it but still no help. I have checked to be sure I have the guest additions loaded so that is not the problem.
Does anyone have any ideas as to what may be going on?

A: Devices -> Insert Guest Additions CD Image -> Install -> Restart.
Remember activate bi-directional shared clipboard!

A: You may also need to install some libraries if its from a standard Ubuntu desktop build
sudo apt-get install virtualbox-guest-dkms virtualbox-guest-utils virtualbox-ext-pack

And Install Insert Additions CD Image from the device menu of the virtualbox window of the running VM.

A: How to enable bi-directional copy and paste on virtual box/ubuntu 16.4
pkill 'VBoxClient --clipboard' -f & sleep 1 && VBoxClient --clipboard
I ran this command on virtualbox(5.2)/ubuntu(16.4). It worked for me. I have enabled the bi-direction mode in settings->advance as well and after that ran this command.
Finally, trying so many methods, this one worked for me.


text:
Q: StarData, Altitude/Azimuth Anomaly with TimeZones I am trying to compute lunar parallax using the position of the star Regulus on February 19th of this year. I get different answers depending on how I specify the date.
Here are the particulars:
 star = regulus = Entity["Star", "Regulus"];
 date1 = DateObject[{2019, 2, 19, 0, 0, 27}, TimeZone -> -5]
 date2 = DateObject[{2019, 2, 19, 5, 0, 27}, TimeZone -> "GMT"]
 (* Note: explicit 5 with GMT *)

 date1 == date2                              (* True *)
 AbsoluteTime@date1 == AbsoluteTime@date2    (* True *)

I then define EntityProperties for retrieving Regulus's azimuth and altitude coordinates using both dates:
altitudeProperty1 =
  EntityProperty["Star", "Altitude", {"Date" -> date1}];
azimuthProperty1 =
  EntityProperty["Star", "Azimuth", {"Date" -> date1}];
altitudeProperty2 =
  EntityProperty["Star", "Altitude", {"Date" -> date2}];
azimuthProperty2 =
  EntityProperty["Star", "Azimuth", {"Date" -> date2}];

Querying StarData with these properties yields different results:
StarData[star, {azimuthProperty1, altitudeProperty1}]
StarData[star, {azimuthProperty2, altitudeProperty2}]

The answers produced are different:

I believe the first answer to be correct as checked by Stellarium and NAOJ. Interestingly, changing the "5" in date2 to "0", while leaving the TimeZone as "GMT", fixes the problem (leads to identical correct results).
(Using the Star entity instead of StarData produces identical results.)
My question is: am I misunderstanding how TimeZones work or is this a problem with MMA?
Note: I am running MMA 12.0.0.0 on a MacBook Pro with OSX 10.13.4.

A: This problem appears to have been fixed. In MMA version 12.1.0.0 the
answers come out the same.


text:
Q: creating .sh file to execute visual studio 2010 project I have a question: how can I create a .sh file to execute a visual studio 2010 console project in C#? thanks!

A: Do you mean running a bash-script? I found this
{
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "/tmp/bash.sh";
    psi.UseShellExecute = false;
    psi.RedirectStandardOutput = true;

    psi.Arguments = "test";
    Process p = Process.Start(psi);
    string strOutput = p.StandardOutput.ReadToEnd();
    p.WaitForExit();
    Console.WriteLine(strOutput);
}


text:
Q: Creating diagrams on LaTeX I am trying to recreate the diagram shown in the picture below using LaTeX.
For reference, I would like to be able to include an image/picture at the top of the diagram (in the picture you'll see my attempt at drawing a car and a tree). Then I want to be able to show a line connecting it to a {word}. And lastly, I'd like to connect that word to other words that are circled around. If possible, I would like to be able to link other diagrams to the words from the original diagram with simply lines, as shown in the picture below.
I would appreciate it if anyone could help me create a diagram like this, thanks!

A: You can include graphics in TikZ pictures and forest trees. So just replace example-image-a by an image of a car and example-image-b by an image of a tree.
\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{forest}
\usetikzlibrary{shapes.geometric,positioning}
\tikzset{elli/.style={ellipse,draw}}
\begin{document}
\begin{forest}
for tree={l sep+=1em,where level=2{elli}{}}
[{\includegraphics[width=1.5cm]{example-image-a}},alias=car
 [{\{word\}},alias=wordL
  [word,alias=elli1]
  [word,alias=elli2]
  [word,alias=elli3]
  [word,alias=elli4]
 ]
]
\node[right=2em of elli4,elli] (elliR) {word};
\node (wordR) at (elliR|-wordL) {{\{word\}}};
\node (tree) at (elliR|-car) {\includegraphics[width=1.5cm]{example-image-b}};
\draw (tree) -- (wordR) foreach \X in {3,4,R}
{(wordR) -- (elli\X)};
\end{forest}
\end{document}

And just for fun: drawing the car and the tree with TikZ.
\documentclass[border=3.14mm]{standalone}
\usepackage{forest}
\usepackage{tikzducks}
\usetikzlibrary{shapes.geometric,positioning}
\usetikzlibrary{decorations.pathmorphing,shapes}
\tikzset{elli/.style={ellipse,draw}}
\newsavebox\Car
\newsavebox\Tree
\begin{document}
\begin{lrbox}{\Car}
\begin{tikzpicture} see https://tex.stackexchange.com/users/101651/carlatex
\fill (-4.7,-0.8) arc(180:0:1.7 and 1.1) --cycle;
\fill (1.3,-0.8) arc(180:0:1.7 and 1.1) --cycle;
% right front wheel
\fill (-3.3,-0.1) circle (1.5cm);
% left front wheel
\shade[inner color=black,outer color=black!70] (-3,-0.7) circle (1.5cm);
\fill[black!20!white] (-3,-0.7) circle (0.8cm);
\foreach \X in {0,30,...,330} {\fill[black] (-3,-0.7) +({\X-5}:0.6) circle (1pt);}
% back wheel
\fill (2.7,-0.1) circle (1.5cm);
% back wheel left
\shade[inner color=black,outer color=black!70] (3,-0.7) circle (1.5cm);
\fill[black!20!white] (3,-0.7) circle (0.8cm);
\foreach \X in {0,30,...,330} {\fill[black] (3,-0.7) +({\X+11}:0.6) circle (1pt);}
% seat
\fill[top color=red,bottom color=red!20!black] (2.9,2.2) arc(0:360:3 and 0.3);
% driver
\begin{scope}[xshift=-2.3cm,yshift=1cm,scale=1.5]
\duck[squareglasses=blue!50!black,longhair=black];
\end{scope}
% right light
\shade[bottom color=red,top color=red!30] (-4.35,1) arc(-90:90:0.3 and 0.4) |-
cycle;
\shade[bottom color=yellow!30,top color=white] (-4.45,1) arc(-90:270:0.1 and
0.4);
% body
\shade[bottom color=red,top color=red!30] (-4.7,-0.8) arc(180:0:1.7) -- (-1.3,-0.8) -- (1.3,-0.8) arc(180:0:1.7)
-- (4.9,-0.8) arc(0:90:2 and 3)
arc(0:-180:3 and 0.3)
-- (-2.9,2.2) arc(90:180:2 and 3) -- cycle;
\shade[bottom color=red,top color=red!30] (-4.7,-0.8) arc(180:0:1.7 and 1.1) arc(0:180:1.7 and 1.8);
\shade[bottom color=red,top color=red!30] (1.3,-0.8) arc(180:0:1.7 and 1.1) arc(0:180:1.7 and 1.8);
% door
\draw[very thin] (1.1,1.9) to[out=-90,in=80] (1,-0.6) -- (-1,-0.6)
to[out=110,in=-90] (-1.1,1.9);
\node[blue,font=\sffamily\Huge] at (0,0.8) {\LaTeX};
% left light
\shade[bottom color=red,top color=red!30] (-4.4,0.8) arc(-90:90:0.3 and 0.4) |-
cycle;
\shade[bottom color=yellow!30,top color=white] (-4.4,0.8) arc(-90:270:0.1 and
0.4);
% windshield
\shade[bottom color=blue,top color=blue!20,opacity=0.3]
(-3.2,2.2) arc(180:130:3 and 0.3) arc(180:150:2.5 and 4)
arc(130:180:3 and 0.3) -- cycle;
\shade[bottom color=blue,top color=blue!20,opacity=0.3]
(-3.2,2.2) arc(180:230:3 and 0.3) arc(180:150:2.5 and 4)
arc(230:180:3 and 0.3) -- cycle;
\end{tikzpicture}
\end{lrbox}%
\begin{lrbox}{\Tree}
\begin{tikzpicture}[treetop/.style = {% from https://tex.stackexchange.com/a/101113/121799
    decoration={random steps, segment length=0.4mm},
    decorate
  },
  trunk/.style = {
    decoration={random steps, segment length=2mm, amplitude=0.2mm},
    decorate
  }]
\foreach \w/\f in {0.3/30,0.2/50,0.1/70} {
  \fill [brown!\f!black, trunk] (0,0) ++(-\w/2,0) rectangle +(\w,-3);
}
\foreach \n/\f in {1.4/40,1.2/50,1/60,0.8/70,0.6/80,0.4/90} {
   \fill [green!\f!black, treetop] ellipse (\n/1.5 and \n);
}
\end{tikzpicture}
\end{lrbox}%

\begin{forest}
for tree={l sep+=1em,where level=2{elli}{}}
[{\usebox\Car},scale=0.2,alias=car
 [{\{word\}},alias=wordL
  [word,alias=elli1]
  [word,alias=elli2]
  [word,alias=elli3]
  [word,alias=elli4]
 ]
]
\node[right=2em of elli4,elli] (elliR) {word};
\node (wordR) at (elliR|-wordL) {{\{word\}}};
\node[xscale=0.4,yscale=0.25] (tree) at (elliR|-car) {\usebox\Tree};
\draw (tree) -- (wordR) foreach \X in {3,4,R}
{(wordR) -- (elli\X)};
\end{forest}
\end{document}

No worries, this is an electric car, so the tree should be fine, and it is safe to use forest.


text:
Q: Por qué no puedo iniciar un objeto de una clase? Necesito poder acceder a los metodos de una clase que no es static, por lo que necesito crear un objeto de esa clase para poder acceder a sus metodos verdad?
Estoy diseñando una app simple que emula a un banco, por lo que necesito poder acceder a los metodos de la clase Banco (agregarSucursal, agregarCliente, etc.)
desde Main.
Creo un objeto en main de la siguiente manera
private static Bank bancoPrueba = new Bank("bancoPrueba");

pero aun así no puedo acceder a los metodos de la clase Bank usando algo como
bancoPrueba.agregarSucursal

Es como si el objeto no estuviera creado. Por qué?
//Main
    import java.util.Scanner;

public class Main {

    public static Scanner scanner = new Scanner(System.in);
    private static Bank galicia = new Bank("Galicia");

    public static void main(String[] args) {

        printOptions();

        boolean quit = false;
        while(!quit){
            System.out.println("6. Imprimir lista de opciones");
            int option = scanner.nextInt();
            switch(option){
                case 0:
                    quit = true;
                    break;
                case 1:
                    addSucursal();
                    break;
//                case 2:
//                    imprimirSucursales();
//                    break;

//                case 3:
//                    addNewClient();
//                    break;
//
//                case 4:
//                    agregarTransaccion();
//                    break;
//
//                case 5:
//                    imprimirClientesSucursal();
//                    break;
                case 6:
                    printOptions();
                    break;
            }
        }
    }

//Bank
import java.util.ArrayList;

public class Bank {

    private String name;
    private ArrayList<Sucursal> sucursales = new ArrayList<Sucursal>();

    //CONSTRUCTOR
    public Bank(String name) {
        this.name = name;
    }

    public void agregarSucursal(String sucursalName){
        new Sucursal(sucursalName);

    }

// Sucursal
public class Sucursal {

    private String sucursalName;
    ArrayList<Cliente> clientes = new ArrayList<Cliente>();

    public Sucursal(String name) {
        this.sucursalName = name;
        this.clientes = new ArrayList<Cliente>();
        System.out.println("Sucursal " + name + " creada.");
    }

    public void agregarCliente(String name, double initialTransaction){
        clientes.add(new Cliente(name, initialTransaction));
        System.out.println("Cliente " + name + " agregado a esta sucursal. Transaccion inicial: " + initialTransaction);
    }

    public static void agregarTransaccion(Cliente cliente, double transaccion){
        cliente.addTransactions(transaccion); //al ser STATIC no hace falta crear un Objeto Sucursal para poder llamarlo

    }

//GETTERS SETTERS

    public String getName() {
        return sucursalName;
    }
}

A: El problema es el acceso al método, y esto se debe a que el método esta siendo llamado desde un método estático que es main() , en este caso debes definir como estático (static) el método  agregarSucursal()  :
   public static void agregarSucursal(String sucursalName){
        new Sucursal(sucursalName);

    }

de esta forma lo puedes llamar como lo deseas realizar:
     Bank bancoPrueba = new Bank("bancoPrueba");
     bancoPrueba.agregarSucursal("Banco de 1990eam");

A: Si bien ahora lo estoy pudiendo invocar, al crear la sucursal invocando el metodo correspondiente (que a su vez llama al constructor de Sucursal) parecería que no puedo iniciar el objeto dado que el System.out sale vacío y lo mismo si imprimo una lista de sucursales.
//Banco.agregarSucursal
public void agregarSucursal(String sucursalName){
    sucursales.add(new Sucursal(sucursalName));

}

//Banco.imprimirSucursales
public void imprimirSucursales(){
    System.out.println("Lista de sucursales");
    for(int i = 0; i<this.sucursales.size();i++){
        System.out.println(this.sucursales.get(i).getSucursalName());

    }

}

//Constructor Sucursal y getName
public Sucursal(String name) {
        this.sucursalName = name;
        this.clientes = new ArrayList<Cliente>();
        System.out.println("Sucursal " + name + " creada.");
    }

        public String getName() {
        return sucursalName;
    }
}


text:
Q: Why is it that when calculating the electric field of a cylinder, the linear charge density is used? I think that the surface charge density is more appropriate as the cylinder, unlike a rod, does have a surface. However if I look at textbooks like Halliday or even stuff on the internet it seems everyone uses the linear charge density. Why is it so?

Example photos

A: People use the linear density because it is equivalent.

*

*If we consider a cylinder of radius $R$ with surface charge $\sigma$, then to calculate the electric field outside $(r>R)$ we apply Gauss' law choosing a cylinder of length $L$ as our Gaussian surface:
$$\iint\vec{E}\cdot\vec{dS}=\frac{(2\pi RL)\sigma}{\varepsilon_0}$$
and we get
$$\vec{E}=\frac{R\sigma}{r\varepsilon_0}\hat{r}$$

*Notice that this is the electric field that a linear density of value $\lambda=2\pi R\sigma$ would create if it were located at the center of the cylinder $(r=0)$. So this is saying us that we have an equivalence (a purely operational one); every time we want to calculate the field created by a (constant) charge $\sigma$ located at the surface of a cylinder we can just forget about the cylinder and replace it with a line of charge $\lambda=2\pi R\sigma$. The field created by the surface and the one by the line are the same in the region of interest.

*Notice finally, that the equivalence is something that we can expect by physical considerations. Consider the cylinder first. What charge is there in a given portion of length $L$? Well,
$$Q=\underbrace{(2\pi RL)}_{\rm surface}\sigma$$
or per unit length
$$\frac{Q}{L}=2\pi R\sigma.$$
So if the charge in the cylinder per unit length is $2\pi R\sigma$, it makes sense (physically) to put $\lambda=2\pi R\sigma$.

A: Usually, for simplicity, the cylinder is assumed to be infinite (practically the length is much greater than the radius), so that charge on the cylinder is much larger.
In order to tackle this, the term charge per unit length $(\lambda)$ is used which remains constant for uniform charge distribution and is more convenient.


text:
Q: Python 2 string somehow saved as pure Unicode I have the following strings in Chinese that are saved in a following form as "str" type:
\u72ec\u5230
\u7528\u8272
I am on Python 2.7, when I print those strings they are printed as actual Chinese characters:
chinese_list = ["\u72ec\u5230", "\u7528\u8272", "\u72ec"]
print(chinese_list[0], chinese_list[1], chinese_list[2])
>>> 独到 用色 独

I can't really figure out how they were saved in that form, to me it looks like Unicode. The goal would be to take other Chinese characters that I have and save them in the same kind of encoding. Say I have "国道" and I would need them to be saved in the same way as in the original chinese_list.
I've tried to encode it as utf-8 and also other encodings but I never get the same output as in the original:
new_string = u"国道"
print(new_string.encode("utf-8"))
# >>> b'\xe5\x9b\xbd\xe9\x81\x93'
print(new_string.encode("utf-16"))
# >>> b'\xff\xfe\xfdVS\x90'

Any help appreciated!
EDIT: it doesn't have to have 2 Chinese characters.
EDIT2: Apparently, the encoding was unicode-escape. Thanks @deceze.
print(u"国".encode('unicode-escape'))
>>> \u56fd

A: The \u.... is unicode escape syntax. It works similar to how \n is a newline, not the two characters \ and n.
The elements of your list never actually contain a byte string with literal characters of \, u, 7 and so on. They contain a unicode string with the actual unicode characters, i.e. 独 and so on.
Note that this only works with unicode strings! In Python2, you need to write u"\u....". Python3 always uses unicode strings.
The unicode escape value of a character can be gotten with the ord builtin. For example, ord(u"国") gives 22269 - the same value as 0x56fd.
To get the hexadezimal escape value, convert the result to hex.
>>> def escape_literal(character):
...     return r'\u' + hex(ord(character))[2:]
...
>>> print(escape_literal('国'))
\u56fd


text:
Q: "Unexpected quantifier" error with javascript regex When I use this regex declaration in javascript:
var phoneRegExp = /^(\+\s?)?((?<!\+.*)\(\+?\d+([\s\-\.]?\d+)?\)|\d+)([\s\-\.]?(\(\d+([\s\-\.]?\d+)?\)|\d+))*(\s?(x|ext\.?)\s?\d+)?$/i;

it gives me an "Unexpected quantifier" error in IE10.
Chrome reports an "Invalid group".
As far as I can see the expression is ok, I have tested it with http://regexhero.net/tester and it is the same as is used in the .NET4.5 PhoneAttribute
Any ideas?

A: Faced the same issue and solved it by reversing original regex pattern and replacing lookbehind with lookahead. The last trick is to reverse input string that is going to be tested against the regex.
This idea is well described in Steven Levithan's Mimicking Lookbehind in JavaScript blog post.
Below is my test page where you can see the working regex:
<html>
    <head>
        <title>Phone Number RegExp Test Page</title>
    </head>
    <body>
        <script>
            function validateInput() {
                var phoneRegex = new RegExp("^(\\d+\\s?(x|\\.txe?)\\s?)?((\\)(\\d+[\\s\\-\\.]?)?\\d+\\(|\\d+)[\\s\\-\\.]?)*(\\)([\\s\\-\\.]?\\d+)?\\d+\\+?\\((?!\\+.*)|\\d+)(\\s?\\+)?$", "i");

                var input = document.getElementById("tbPhone");
                var value = input.value.split("").reverse().join("");
                alert(phoneRegex.test(value));
            }
        </script>

        <input type="text" id="tbPhone" />
        <button onclick="javascript:testPhone()">Validate</button>
    </body>
</html>


text:
Q: Jacobi sums Gaussian Sum. Show $J(\rho^{'},\chi^{'}) = (- J(\rho,\chi))^s$ I want to show that $J(\rho^{'},\chi^{'}) = (- J(\rho,\chi))^s$, where $\rho^{'},\chi^{'}$ are characters of a finite field $F_{p^s}$ and $\chi,\rho$ are characters a finite field $F_p$.
My work:
I know / find out that
1) $J(\rho^{'},\chi^{'}) = \frac{g(\chi^{'})g(\rho^{'})}{g(\rho^{'}\chi^{'})} $
2) $ g(\chi^{'}) = (-g(\chi))^s $
That should be enough to prove my claim, but how exactly? In 1) I can replace numerator with 2). But what now?


text:
Q: My ToolBar is too high and because of that it looks ugly and the screen below is cropped, how do I fix it? Here's my toolbar screen.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

    <LinearLayout
    android:id="@+id/container_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <!-- Include your Toolbar -->
    <include
        android:id="@+id/mytoolbar"
        layout="@layout/toolbar" />
</LinearLayout>

<FrameLayout
    android:id="@+id/container_body"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1">
    <!-- Embed your fragment in a Layout View-->
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.Activities.MenuActivity"
        />
</FrameLayout>
 </LinearLayout>

How it looks on your phone:
You can see that the toolbar is too high.
Manifest:
<activity
        android:name="com.example.Activities.MenuActivity"
        android:label="@string/title_activity_test"
        tools:ignore="InnerclassSeparator" />
    <activity

Styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

MenuActivity.class
setContentView(R.layout.activity_menu);
    Toolbar toolbar = findViewById(R.id.mytoolbar);
    setSupportActionBar(toolbar);
    Drawer(toolbar,MenuActivity.this,MenuActivity.this);

    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle("Аппараты");
    }

void Drawer:
public void  Drawer(Toolbar toolbar, Context context, android.app.Activity activity){

    DatabaseReference rootRef2 = FirebaseDatabase.getInstance().getReference();
    DatabaseReference uidRef2 = rootRef2.child("users").child(getUid());
    ValueEventListener valueEventListener2 = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String email = dataSnapshot.child("account").getValue(String.class);
            String Avatar = dataSnapshot.child("Avatar").getValue(String.class);
            Long coinsAmount = dataSnapshot.child("coinsAmount").getValue(Long.class);

            String coinsView = "Баланс: " + coinsAmount;

                if (Avatar.equals("1")) {
                    avatar = (R.drawable.a1);
                }
                if (Avatar.equals("2")) {
                    avatar = (R.drawable.a2);
                }

            IProfile profile = new ProfileDrawerItem()
                    .withName(email)
                    .withEmail(coinsView)
                    .withIcon(avatar);

            AccountHeader headerResult = new AccountHeaderBuilder()
                    .withActivity(activity)
                    .withHeaderBackground(R.drawable.account_header_background)
                    .addProfiles(
                            profile
                    )
                    .build();

               result = new DrawerBuilder()
                    .withActivity(activity)
                    .withToolbar(toolbar)
                    .withAccountHeader(headerResult)
                    .addDrawerItems(
                            new PrimaryDrawerItem()
                                    .withName("Устройства")
                                    .withIcon(R.drawable.device)
                                    .withIdentifier(1)
                    )
                    .addDrawerItems(
                            new PrimaryDrawerItem()
                                    .withName("Сканер")
                                    .withIcon(R.drawable.scaner)
                                    .withIdentifier(2)
                    )
                    .addDrawerItems(
                            new PrimaryDrawerItem()
                                    .withName("Магазины")
                                    .withIcon(R.drawable.shop)
                                    .withIdentifier(3)
                    )
                    .addDrawerItems(
                            new PrimaryDrawerItem()
                                    .withName("Купоны")
                                    .withIcon(R.drawable.coupons)
                                    .withIdentifier(4)
                    )
                    .addDrawerItems(
                            new PrimaryDrawerItem()
                                    .withName("Архив Купонов")
                                    .withIcon(R.drawable.oldcoupons)
                                    .withIdentifier(5)
                    )
                    .withOnDrawerItemClickListener((view, i, iDrawerItem) -> {
                        if(iDrawerItem.getIdentifier() == 1 && !Activity.equals("Menu")){
                            Intent intent = new Intent(context,MenuActivity.class);
                            startActivity(intent);
                        }
                        else if(iDrawerItem.getIdentifier() == 2 && !Activity.equals("Scaner")){
                            Intent intent = new Intent(context,DecoderActivity.class);
                            startActivity(intent);
                        }
                        else if(iDrawerItem.getIdentifier() == 3 && !Activity.equals("Shop")){
                            Intent intent = new Intent(context,ShopActivity.class);
                            startActivity(intent);
                        }
                        else if(iDrawerItem.getIdentifier() == 4 && !Activity.equals("oldCoupons")){
                            Intent intent = new Intent(context,oldCouponsActivity.class);
                            startActivity(intent);
                        }

                        return false;
                    })
                    .build();

            Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(false);
            Objects.requireNonNull(result.getActionBarDrawerToggle()).setDrawerIndicatorEnabled(true);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }

    };
    uidRef2.addValueEventListener(valueEventListener2);

}

How to fix it and how do we all? I have long tried to fix it I used android:fitsSystemWindows="true" and I still did not help activity is cut only the first time if you restart the activity is all OK. I came to the conclusion that this may be due to firebase but how to solve this and eventually fix this problem I could not
Toolbar.xml
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:iosched="http://schemas.android.com/apk/res-auto"

android:id="@+id/toolbar_actionbar"
android:layout_width="match_parent"
android:layout_height="@dimen/materialize_toolbar"
android:background="@color/grey_500"
android:minHeight="?attr/actionBarSize"

android:theme="?attr/actionBarTheme" />

A: Try setting android:fitsSystemWindows="true" to your base linear layout.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">

Update - The answer that finally worked was to use CoordinatorLayout as the base layout.
P.S - To any person looking at this in the future, the other possible considerations were,

*

*Setting it in the theme using <item name="android:fitsSystemWindows">true</item>

*Setting it's value as false instead of true. It doesn't make logical sense, but I've seen people state that that works at times

*Ensure that you have android:minHeight="?attr/actionBarSize" in your Toolbar

*It might be worth completely replacing the container_toolbar LinearLayout with your Toolbar and set fitsSystemWindows as true.

*Using a CoordinatorLayout or DrawerLayout your base layout. They're supposed to handle fitsSystemWindows differently from the other 'basic' layouts.

*Consider the plethora of ways suggested here

*And if all else fails, then you can override fitSystemWindows(Rect insets) to get your desired layout as the official docs suggests.

A: Try simplifying your layout. Put the toolbar and fragment inside the LinearLayout
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

    <include
        android:id="@+id/mytoolbar"
        layout="@layout/toolbar" />

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.Activities.MenuActivity"
        />

</LinearLayout>


text:
Q: ¿como agrupar la cantidad facturada por divisa (currency rate) y por mes? Tengo la siguiente consulta:
select sh.CurrencyRateID, cr.ToCurrencyCode,
       sum(TotalDue) as [cantidad facturada], month(OrderDate) as mes
from sales.SalesOrderHeader sh
     join sales.CurrencyRate cr
         on sh.CurrencyRateID=cr.CurrencyRateID
group by sh.CurrencyRateID, cr.ToCurrencyCode, month(OrderDate)
order by sh.CurrencyRateID asc, 2 desc, 4

La salida es la siguiente,

pero ahora no se como agrupar el tipo de moneda,para que solo salga una vez,  y muestre el total

A: Esto sucede por que el agrupamiento se da por todas las columnas del GROUP BY y en consecuencia como la columna CurrencyRateID tiene 4 valores diferentes para el valor AUD de la columna ToCurrencyCode, se separa en estos 4 "sub grupos"
Simplemente debes eliminar del agrupamiento a la columna CurrencyRateID
SELECT cr.ToCurrencyCode,
       SUM(TotalDue) as [cantidad facturada],
       MONTH(OrderDate) as mes
   FROM sales.SalesOrderHeader sh
       JOIN sales.CurrencyRate cr
            ON sh.CurrencyRateID = cr.CurrencyRateID
   GROUP BY cr.ToCurrencyCode, MONTH(OrderDate)

Si también quieres eliminar la columna de mes, puedes hacer dos cosas.
Uno, eliminar MONTH(OrderDate) del GROUP BY y el SELECT, con lo que tendrás la suma total de todos los meses.
La otra es filtrar por un mes especifico y tendrás las suma total de un mes dado; Esto es opcional, eliminado la linea del WHERE alanza para obtener el total histórico.
SELECT cr.ToCurrencyCode,
       SUM(TotalDue) as [cantidad facturada]
   FROM sales.SalesOrderHeader sh
       JOIN sales.CurrencyRate cr
            ON sh.CurrencyRateID = cr.CurrencyRateID
   WHERE MONTH(OderDate) = 7
   GROUP BY cr.ToCurrencyCode


text:
Q: Prevent browser moving element when children are focused I am implementing a simple map. The map consists of a viewport, and the map image itself, which is actually a div with a background image.
The viewport is relatively positioned and it's overflow is hidden, and the map image is absolutely positioned within the viewport.
The map can be moved with the mouse within the viewport and the map can also be zoomed (just increasing the size of the image as the image is a .svg)
The map has points on it which the user can hover over to get a description in a tooltip of the point. The points can also be focused by tabbing to them.
Points are children of the map image div and are absolutely positioned by percentage (to retain the correct position when the map is zoomed)
When a point is focused, I want to move the map so that the point is in the middle of the viewport. I have written the code for this and it works fine. However, if a point is outside of the viewport (not visible) then the browser automatically tries to move the map so the point is visible. I don't want it to do this, as it is interfering with the code I have written to animate the map move. This is nothing to do with scrolling.
I am using jQuery and have tried e.preventDefault() and return false; in the focus handler for the map points but neither work.
Is preventing this behaviour even possible?
Thanks in advance

A: I have found out that the scroll value of the map viewport was being set by the browser in order to bring the map point into view. As I am moving the map by setting it's top and left positions, this is what was causing the issue.
The solution was to add the .scroll() event listener to the viewport and just set the scrollTop and scrollLeft values to 0 when the event is triggered


text:
Q: What is wrong with my code? I dont know what to do This is my source code, it show no error in the Ide but, it stop on the device.
I use speech to say something to the program, and the program depending of the record, show me differents answers.
I Dont know what more do. The problem apparently starts from the methodod setText.
Thank U
 protected static final int RESULT_SPEACH =1;
 private Button record, speak;

 TextToSpeech t1;
 String SpokedText;
 private EditText txtView;
 private EditText txtView2;
 TextToSpeech t1;

 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_mai);
 record = (Button) findViewById(R.id.record);
 speak = (Button) findViewById(R.id.speak);

speak.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        record();

    }
});
 }
public void record() {
    Intent reconize = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    reconize.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    reconize.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    reconize.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.Say_something));

    try {
        startActivityForResult(reconize, RESULT_SPEACH);

    } catch (ActivityNotFoundException a) {
        Toast t = Toast.makeText(getApplicationContext(), "Tu dispositivo no puede ejecutar este tipo de operaciones", Toast.LENGTH_LONG);
        t.show();
 }
 }

 @Override
 public void onActivityResult (int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode,resultCode,Data);
switch (requestCode) {
    case RESULT_SPEACH: {
        if (resultCode == RESULT_OK && null != Data) {
        SpokedText = data.getStringExtra(RecognizerIntent.EXTRA_RESULTS);
                txtView2.setText(SpokedText);
                setText(SpokedText);

                }break;
            }
        }
    }
  public void setText(String string){
    if (txtView2.equals("Good Morning")){
        txtView.setText("Good Morning Sir");
    }else if(txtView2.equals("I need your help")){
        txtView.setText("Ok, ¿How can i help you?");
    }

            }
   @Override
   public void onInit(int status) {
   if (status== TextToSpeech.SUCCESS){
        int result = t1.setLanguage(Locale.getDefault());
        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
            Log.e("TTS", "This Lenguaje is not supported");
        }else{
            speakOut();
        }
    }

}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void speakOut(){
    String text = txtView.getText().toString();

    t1.speak(text, TextToSpeech.QUEUE_FLUSH, null);

}
}

Could the problem may be in the AndroidManifest Xml?

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.dower.myapplication">

    <uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

    <activity android:name=".PantallaDeInicio"
        android:label="@string/StarScreen"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.PICK_ACTIVITY"></action>
            <category android:name="android.intent.category.LAUNCHER"></category>
        </intent-filter>

    </activity>

    <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity android:name=".Casanova"
                    android:label="@string/casaNova"
                    android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.PICK_ACTIVITY"></action>
                <category android:name="android.intent.category.APP_BROWSER"></category>
                <action android:name="android.intent.action.VOICE_COMMAND"></action>
                <category android:name="android.intent.category.VOICE"></category>

            </intent-filter>
        </activity>

        <!-- ATTENTION: This was auto-generated to add Google Play services to your project for
             App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>

A: The problem is that you can't equate a control with a string.
  if (txtView2.equals("Good Morning")){

Should be
if (txtView2.getText().toString().equals("Good Morning")){

And you need to do the same each time you want to check the string in TextView controls


text: Q: Intuitive definition of "rate of attraction" of a fixed point If possible, I would like to know if there is an easy and intuitive definition of the "rate of attraction" of a fixed point. I am especially interested in the difference between super-attractive and simple-attractive fixed point (e.g.: $x = \sqrt{\alpha}$ is a super-attractive fixed point of $f(x) = \frac{1}{2}(x+\frac{\alpha}{x})$, whereas it is a simple-attractive fixed point of $g(x) = \frac{x + \alpha}{x + 1}$).


text:
Q: Wince Call CreateMutex in Kernel I need to share a resource between the OEM Abstraction Layer (OAL) and a driver that will run outside of the kernel.  To share the resource I will create a mutex.  When I call CreateMutex (or any other function in coredll.lib) from the OAL I get a prefetch abort exception.
How do you create a mutex in the OAL (kernel space) in Windows Compact 7?

A: You cannot use a mutex, but you can use a critical section.
https://msdn.microsoft.com/en-us/library/ee478303.aspx
Critical section work between threads inside the same process and if your driver is a kernel mode driver and not a user mode one, it will run inside nk.exe, same process as OAL.
Instead of sharing the critical section (not easy since they can't be named) you can implement a couple of kernel IOCTLs to Enter/Leave it.


text:
Q: Rails 3.2.6; rake 0.9.2.2; db:migrate aborted I'm new to Rails, and am following the getting started guide on their website.
I'm getting an error when I run $ rake db:migrate in section: http://guides.rubyonrails.org/getting_started.html#generating-a-model
It worked for the first time in section: http://guides.rubyonrails.org/getting_started.html#running-a-migration
So I don't know what is wrong.
When I run $ rake db:migrate
==  CreateComments: migrating =================================================
-- create_table(:comments)
rake aborted!
An error has occurred, this and all later migrations canceled:

private method `test' called for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x007f83a27503c8>

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

So I followed the instructions to run it with the --trace argument; I was wondering if anyone has a clue what it means, and what the issue is?
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Invoke rails_env (first_time)
** Execute rails_env
** Execute db:load_config
** Execute db:migrate
==  CreateComments: migrating =================================================
-- create_table(:comments)
rake aborted!
An error has occurred, this and all later migrations canceled:

private method `test' called for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x007f8bacbba730>
/Users/parnmatt/Sites/test-rails/blog/db/migrate/20120627130542_create_comments.rb:5:in `block in change'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/connection_adapters/abstract/schema_statements.rb:160:in `create_table'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:466:in `block in method_missing'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:438:in `block in say_with_time'
/Users/parnmatt/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/benchmark.rb:280:in `measure'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:438:in `say_with_time'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:458:in `method_missing'
/Users/parnmatt/Sites/test-rails/blog/db/migrate/20120627130542_create_comments.rb:3:in `change'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:407:in `block (2 levels) in migrate'
/Users/parnmatt/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/benchmark.rb:280:in `measure'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:407:in `block in migrate'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/connection_adapters/abstract/connection_pool.rb:123:in `with_connection'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:389:in `migrate'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:528:in `migrate'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:720:in `block (2 levels) in migrate'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:775:in `call'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:775:in `block in ddl_transaction'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/connection_adapters/abstract/database_statements.rb:192:in `transaction'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/transactions.rb:208:in `transaction'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:775:in `ddl_transaction'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:719:in `block in migrate'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:700:in `each'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:700:in `migrate'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:570:in `up'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/migration.rb:551:in `migrate'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.6/lib/active_record/railties/databases.rake:153:in `block (2 levels) in <top (required)>'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `call'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `block in execute'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `each'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `execute'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/task.rb:158:in `block in invoke_with_call_chain'
/Users/parnmatt/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/task.rb:144:in `invoke'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/application.rb:116:in `invoke_task'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block (2 levels) in top_level'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `each'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block in top_level'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/application.rb:88:in `top_level'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/application.rb:66:in `block in run'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `run'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/gems/rake-0.9.2.2/bin/rake:33:in `<top (required)>'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/bin/rake:19:in `load'
/Users/parnmatt/.rvm/gems/ruby-1.9.3-p0/bin/rake:19:in `<main>'
Tasks: TOP => db:migrate

This is the migration code generated:
class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.string :commenter
      t.test :body
      t.references :post

      t.timestamps
    end
    add_index :comments, :post_id
  end
end

A: Looks like when you ran the generator you said 'test' instead of 'text' for body.
Should have been: $ rails generate model Comment commenter:string body:text post:references
Rake doesn't know what type t.test is...it would have been t.text


text:
Q: Modal touch event not working on Safari I created modal popup in JavaScript.
I would like to be able to close the popup by clicking/touching anywhere outside of it (popup is on Z-Index 1). Unfortunately, it doesn't close on Safari.
Example :

var modal = document.getElementById('myModal');
document.getElementById("modal-body").innerHTML += "hello!";
modal.style.display = "block";
window.onclick = function(event) {
  if (event.target === modal) {
    modal.style.display = "none";
  }
};
.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  /* 15% from the top and centered */
  padding: 5%;
  /*20px;*/
  border: 1px solid #888;
  width: 90%;
  /* Could be more or less, depending on screen size */
}

  I want to have popup closed when clicking whenever outside the popup

My JsFiddle Code
Any ideas?

A: Try and tell is it works ?!

var modal = document.getElementById('myModal');
document.getElementById("modal-body").innerHTML += "hello!";
modal.style.display = "block";

function DETECTBROWSER() {
 var HREFF,
  HREFTXT = "unknown";
 this.NAVIGATOR = navigator.userAgent;
 var NAV = navigator.userAgent;
 var gecko,
  navIpad,
  operatablet,
  navIphone,
  navFirefox,
  navChrome,
  navOpera,
  navSafari,
  navandroid,
  mobile,
  navMozilla,
  navUbuntu,
  navLinux;
 navLinux = NAV.match(/Linux/gi);
 navUbuntu = NAV.match(/Ubuntu/gi);
 gecko = NAV.match(/gecko/gi);
 navOpera = (NAV.match(/Opera|OPR\//) ? true : false);
 operatablet = NAV.match(/Tablet/gi);
 navIpad = NAV.match(/ipad/gi);
 navIphone = NAV.match(/iphone/gi);
 navFirefox = NAV.match(/Firefox/gi);
 navMozilla = NAV.match(/mozilla/gi);
 navChrome = NAV.match(/Chrome/gi);
 navSafari = NAV.match(/safari/gi);
 navandroid = NAV.match(/android/gi);
 mobile = NAV.match(/mobile/gi);
 window["TYPEOFANDROID"] = 0;
 window["NOMOBILE"] = 0;

 var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
 if (mobile) {
  var userAgent = navigator.userAgent.toLowerCase();
  if ((userAgent.search("android") > -1) && (userAgent.search("mobile") > -1)) {
   console.log("ANDROID MOBILE");
  } else if ((userAgent.search("android") > -1) && !(userAgent.search("mobile") > -1)) {
   console.log(" ANDROID TABLET ");
   TYPEOFANDROID = 1;
  }

 } else {
  NOMOBILE = 1;
 }
 //  FIREFOX za android
 if (navFirefox && navandroid && TYPEOFANDROID == 0) {
  HREFF = "#";
  HREFTXT = "mobile_firefox_android";
 }
 //  FIREFOX za android T
 if (navFirefox && navandroid && TYPEOFANDROID == 1) {
  HREFF = "#";
  HREFTXT = "mobile_firefox_android_tablet";
 }
 // OPERA ZA ANDROID
 if (navOpera && navandroid) {
  HREFF = "#";
  HREFTXT = "opera_mobile_android";
 } // provera
 // OPERA ZA ANDROID TABLET
 if (navOpera && navandroid && operatablet) {
  HREFF = "#";
  HREFTXT = "opera_mobile_android_tablet";
 } // provera
 //  safari mobile za IPHONE - i  safari mobile za IPAD i CHROME za IPAD
 if (navSafari) {
  var Iphonesafari = NAV.match(/iphone/gi);
  if (Iphonesafari) {
   HREFF = "#";
   HREFTXT = "safari_mobile_iphone";
  } else if (navIpad) {
   HREFF = "#";
   HREFTXT = "mobile_safari_chrome_ipad";
  } else if (navandroid) {
   HREFF = "#";
   HREFTXT = "android_native";
  }
 }
 // TEST CHROME
 if (navChrome && navSafari && navMozilla && TYPEOFANDROID == 1) {
  HREFF = "#";
  HREFTXT = "mobile_chrome_android_tablet";
 }
 if (navChrome && navSafari && navMozilla && TYPEOFANDROID == 0) {
  HREFF = "#";
  HREFTXT = "mobile_chrome_android";
 }
 if (navChrome && TYPEOFANDROID == 0) {
  HREFF = "#";
  HREFTXT = "chrome_browser";
 }
 if (navMozilla && NOMOBILE == 1 && gecko && navFirefox) {
  HREFF = "#";
  HREFTXT = "firefox_desktop";
 }
 if (navOpera && TYPEOFANDROID == 0 && !mobile) {
  HREFF = "#";
  HREFTXT = "opera_desktop";
 }

 //linux
 if (navUbuntu && navMozilla && navFirefox && navLinux) {
  HREFF = "#";
  HREFTXT = "firefox_desktop_linux";
 }
 if (navMozilla && navLinux && navChrome && navSafari) {
  HREFF = "#";
  HREFTXT = "chrome_desktop_linux";
 }
 if (navMozilla && navLinux && navChrome && navSafari && navOpera) {
  HREFF = "#";
  HREFTXT = "opera_desktop_linux";
 }

 /**
 * Template for this view's container...
 * NOMOBILE = 1 means desktop platform
 * @example This is ENUMERATORS for property NAME :
 * "mobile_firefox_android"
 * "mobile_firefox_android_tablet"
 * "opera_mobile_android"
 * "opera_mobile_android_tablet"
 * "safari_mobile_iphone"
 * "mobile_safari_chrome_ipad"
 * "android_native"
 * "mobile_chrome_android_tablet"
 * "mobile_chrome_android"
 * "chrome_browser"
 * "firefox_desktop"
 * "opera_desktop"
 * "firefox_desktop_linux"
 * "chrome_desktop_linux"
 * "opera_desktop_linux" .
 * @property NAME
 * @type {String}
 * @default "unknown"
 */
 this.NAME = HREFTXT;
 /**
 * NOMOBILE = 1 Means desktop platform (Any win , mac or linux etc..)
 * NOMOBILE = 2 Means mobile platform (iOS , android etc.)
 * @property NOMOBILE
 * @type Number
 * @default "unknown"
 */
 this.NOMOBILE = NOMOBILE;
}

var BROWSER = new DETECTBROWSER();

if (NOMOBILE == 0) {
//MOBILE DEVICES

window.addEventListener("touchstart",  function(event) {

  if (event.target === modal) {
    modal.style.display = "none";
  }

} , false);

}
else {

window.addEventListener("click",  function(event) {

  if (event.target === modal) {
    modal.style.display = "none";
  }

} , false);

}
.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  /* 15% from the top and centered */
  padding: 5%;
  /*20px;*/
  border: 1px solid #888;
  width: 90%;
  /* Could be more or less, depending on screen size */
}

  I want to have popup closed when clicking whenever outside the popup


text:
Q: Test method exception: Test method  exception:
System.InvalidOperationException: Could not find endpoint element  in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.

A: Make sure to put your client endpoints in the app.config file of your test project as well.


text:
Q: Create image with html and css table method I want to create image using HTML TABLE and also want to animate it.
But I cannot find anything to slow down the border collapse property.

  See the Pen
  Create image with html css, create image with html table by Rajat Gupta (@simplyrajatgupta)
  on CodePen.

A: Here is the way to do it. you have created the image by using small cells from table and assigning a background color for each cell. And each cell has border spacing you can adjust the space using border-spacing property in CSS insted of using border  border-collapse
So all you have to do is add a transition for changing the border-spacing property in CSS.
Here is the code to do it:
.styled-table,th, td
{
  border: 0px solid black;
  border-spacing: 10px;
  transition: all 2s ease;
}

.styled-table th,td
{
  width: 1px;
  height: 1px;
}

.styled-table:hover,th, td
{
  border-spacing: 0px;
}

I have reposted this answer because it would be helpful for others too.Thank you


text:
Q: Load external requirejs module into own application I have a large requirejs App. Now I have an external library that comes as a bunch of requireJs modules. My first idea was to compile the modules into a single file an require only this module. But this seems not to work. The compiled module looks like this
lib.js
define("a", function(){

})

define("b", function(){

})

define("", function(){

})

in my module I load it like this
define(['lib'], function(){
})


text:
Q: What is the easiest way to display the Properties of the Model as Label and Textbox? I am using the MVVM pattern with WPF and I do want to show all properties from the model in the View in a list of labels and textboxes. So the name of the property should be in a label and the value of the property should have a Binding to a Textbox. (See image below)

The model in this example has following properties: (of course with PropertyChanged)
public class HoseData
{
    public string Article {get; set;} = "6931313"
    public string Description {get; set;} = ""
    public string Type {get; set;} = "DKC"
}

Until now i do have this in my view:
<StackPanel>
    <StackPanel Orientation="Horizontal">
        <Label Content="Article" />
        <TextBox Text="{Binding Article}" />
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <Label Content="Description" />
        <TextBox Text="{Binding Description}" />
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <Label Content="Type" />
        <TextBox Text="{Binding Type}" />
    </StackPanel>
</StackPanel>

Is there an easy way to get such a View out of the Model? In my case the Model has 30 properties and maybe there is an easier way instead of changing the UI if a property is added or changed.

A: Use Reflection:
var hd = new HoseData();

...
PropertyInfo[] properties = typeof(HoseData).GetProperties();
foreach (PropertyInfo pi in properties)
{
    var name = pi.Name;
    var value = pi.GetValue(hd);
    var label = new Label()
    {
        Content = name
    };
    var textbox = new TextBox()
    {
        Text = value.ToString(),
    };
    var binding = new Binding(name)
    {
        Source = hd,
        Mode = BindingMode.TwoWay,
        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
    };
    textbox.SetBinding(TextBox.TextProperty, binding);
    var stackpanel = new StackPanel()
    {
        Orientation = Orientation.Horizontal
    };
    stackpanel.Children.Add(label);
    stackpanel.Children.Add(textbox);
    sp.Children.Add(yourMainStackPanel);
}

A: You could use the PropertyGrid control from the Extended WPF Toolkit:
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
...
<xctk:PropertyGrid ShowSearchBox="False" ShowTitle="False" ShowSummary="False" ShowAdvancedOptions="False"
                   ShowSortOptions="False">
    <xctk:PropertyGrid.SelectedObject>
        <local:HoseData />
    </xctk:PropertyGrid.SelectedObject>
</xctk:PropertyGrid>

A: You could try this detailsview control.
https://archive.codeplex.com/?p=wpfdetailsview


text:
Q: Windows Server 2008 R2: Internet access filtering related issues My current Windows Workplace Network need some users to have restricted access to the internet and some users to have full access to the internet.
So I used a OPENDNS as it turned out to be the most simple and yet cost effective option (as in free!) So I granted those users limited accounts and restricted groups of sites like file and video sharing, social networking, adult sites, etc in the OPENDNS control panel and point those users DNS setting to the OPENDNS.
Now I have decided to upgrade this network to Windows Server 2008 R2 environment, obviously for better management and to make use of centrallized file storage and access restrictions on the file server and I'm stuck again because I want to have some computers use the OPENDNS servers to continue the restrictions as that seems to be the easiest way to do so. But adding all computers on the network to the domain would also mean that these user would have to use the server's DNS which inturn would give them full access to the internet. Also in this latest environment some users have not to be given internet access at all (at least for the time being). Can someone help me here!

A: Yeah sure, for simple internet access control DNS can be used in a very primitive form, for people who don't know how DNS works and don't know how to get around your configuration... but for comprehensive control you need a comprehensive solution. DNS wasn't meant for the use you intend it for, and as such isn't a very robust, scalable, reliable, fool-proof solution for your needs.
My suggestion would be to look at a solution from Microsoft, or any one of the blue zillion vendors who have products that do what you need.

A: DNS isn't meant for Internet access control, you should use a firewall or a proxy server for that.
If you're going to set up a domain environment, there is a very definite need for all domain computer to use the domain DNS server(s) (usually being the domain controller(s)); "very definite need" meaning "do this, or everything will start behaving strangely and/or not working at all".
You could have your domain DNS server(s) use OpenDNS as a forwarder, instead of using your ISP's ones or looking up external names themselves; but this way, all DNS queries would come to OpenDNS from the DC(s), and it wouldn't be able to filter anything. The reverse also wouldn't work: you could have your users use OpenDNS and then have it forward queries for your internal AD domain to your domain controller(s) and resolve Internet queries itself... but Windows clients need to talk directly to domain DNS server(s), not only for name resolution, but also to register themselves in your internal DNS zone.
You should definitely look into a proxy or firewall solution; DNS just wasn't created for this.

A: DNS really is not going to work for access control.  As soon as a user finds out that it's possible to access sites (including proxy sites) by IP address, it's all over.
If you are looking for a free community web filtering platform, you might consider Untangle.

A: Domain machines will only use your domain's DNS servers if you haven't configured them otherwise with group policy.  Group the computers in various OU's according to whatever policy you have.  Then create group policy objects for each OU that explicitly sets the DNS settings.  You can find them here:
Administrative Templates\Network\DNS Client

But like joeqwerty mentioned, this is not going to stop technically savvy people from getting where they need to go.


text:
Q: Django Attribute error: "unicode object has no attribute tags" Everything works quite well,so I presumed anyways but when I runserver and click the title of my blog,i get an AttributeError saying 'unicode object has no attribute tags'
heres the the piece of code handling the tags
def post_detail(request, year, month, day, post):
     post_tags_ids = post.tags.values_list('id', flat=True)
     similar_posts =  Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
     similar_posts =  similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4]
     post = get_object_or_404(Post, slug=post,status='published',publish__year=year,publish__month=month,publish__day=day)
     return render(request,'blog/post/detail.html',{'post': post,'comments': comments,'comment_form': comment_form,'similar_posts': similar_posts})

A: It seems that the 'post' argument you are passing is not a model instance as you presume. I think you need to fetch the post object first. Assuming you are passing pk as post:
post_object = get_object_or_404(Post, pk=post)
post_tags_ids = post_object.tags.values_list('id', flat=True)


text:
Q: Jenkins continue running bat with errors I'm using Vector Cast to run tests for embedded software.
In order to start running the tests I run a bat file.
This bat file produces an error, prints it, and keeps running until it finishes.
When running the bat file using Jenkins, the job hangs at the same point the error suppose to be printed.
How can I tell Jenkins to ignore the error and just keep going?
This is the error from the cmd manuall run, and as you can see it keeps running after the error:
    Waiting for comreader to complete
    Error executing test harness to detect type and range data
    >>>
    >>> This might indicate a problem starting the harness execution or
    >>> capturing output data from your simulator or hardware target.
    >>> If the current configuration can be used successfully with other
    >>> environments, then there might be an execution problem related
    >>> to the code in this environment.
    Determining Basis Paths (LinearAlgebra)
    Determining Basis Paths (MathUtils)


text:
Q: Need to create and write information entered by user in swing application to a file I've created an desktop application using swings. I need to gather information inputted in the application and write that information into file when create file button is clicked. I'm quite new to this please help me. The below snippet is printing info to console but how to write it to file
public void actionPerformed(ActionEvent e)  {

    String str = (String)comboBox1.getSelectedItem();
    System.out.println("# Strategy: SAr, SPSL, PRISM, GANN, RRR \nstrategy="+str);

    String str1 = (String)comboBox2.getSelectedItem();
    System.out.println("\n# ss1 \nsupport-strategy="+str1);

    String str2 = (String)comboBox3.getSelectedItem();
    System.out.println("\n# silverm_i,silver_i,leadmini_i,lead_i,alumini_i,naturalgas_i,copperm_i,crudeoil_i,gold_i\ndata-source="+str2);

    String str3 = (String)comboBox6.getSelectedItem();
    System.out.println("\n# YES or NO\npositional-trading="+str3);

    String str4 = (String)comboBox4.getSelectedItem();
    System.out.println("\n# Data source options - DATABASE or CSV \ndata-from="+str4);

    String str5 = (String)comboBox5.getSelectedItem();
    System.out.println("\n# DEV or DEV \nenvironment="+str5);

    String str6 = (String)comboBox7.getSelectedItem();
    System.out.println("\n# Strategy: WAGHA_BORDER or REGULAR_TOP_BOTTOM_MOVEMENT_BASED_TREND (i.e. RBI) or REGULAR_TOP_BOTTOM_WITH_NO_TRADE_ZONE \ngann-strategy="+str6);
}

I've few date spinner object, checkboxes as well. how to gather information from those components.

A: Not quite sure about the spinner object question as it's been quite some time since I've used it, but as for writing to a file:
public void writeToFile() {
        try {

            String content = "This is the content to write into file";

            File file = new File("filename.txt");

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();

            System.out.println("Done writing to file.");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Please reply if there are any problems.
Source: MKYONG
EDIT:
If you need to read and update the file, which is not in your question what-so-ever, follow nIcE cOw's references.